content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _non_blank_line_count(string):
"""
Parameters
----------
string : str or unicode
String (potentially multi-line) to search in.
Returns
-------
int
Number of non-blank lines in string.
"""
non_blank_counter = 0
for line in string.splitlines():
if li... | dfa6f43af95c898b1f4763573e8bf32ddf659520 | 708,450 |
def encode_direct(list_a: list):
"""Problem 13: Run-length encoding of a list (direct solution).
Parameters
----------
list_a : list
The input list
Returns
-------
list of list
An length-encoded list
Raises
------
TypeError
If the given argument is not ... | 9a20ffd2051003d5350f7e059d98c35310bc9bbe | 708,451 |
import re
def _find_word(input):
"""
_find_word - function to find words in the input sentence
Inputs:
- input : string
Input sentence
Outputs:
- outputs : list
List of words
"""
# lower case
input = input.lower()
# split by whitespace
input = re.split(pattern = '[\s]+', string = input)
# find w... | c2e4aa6b5c127bf03593a9aa2c1ae035e83f5a64 | 708,452 |
import math
def truncate(f, n):
"""
Floors float to n-digits after comma.
"""
return math.floor(f * 10 ** n) / 10 ** n | ae7e935a7424a15c02f7cebfb7de6ca9b4c715c0 | 708,454 |
def get_core_blockdata(core_index, spltcore_index, core_bases):
"""
Get Core Offset and Length
:param core_index: Index of the Core
:param splitcore_index: Index of last core before split
:param core_bases: Array with base offset and offset after split
:return: Array with core offset and core le... | 85efb96fa45ecfa3f526374c677e57c70e3dc617 | 708,455 |
import argparse
def parse_args():
"""
Parse input arguments
Returns
-------
args : object
Parsed args
"""
h = {
"program": "Simple Baselines training",
"train_folder": "Path to training data folder.",
"batch_size": "Number of images to load per batch. Set ac... | 5edfea499b64d35295ffd81403e3253027503d41 | 708,456 |
from datetime import datetime
def timestamp(date):
"""Get the timestamp of the `date`, python2/3 compatible
:param datetime.datetime date: the utc date.
:return: the timestamp of the date.
:rtype: float
"""
return (date - datetime(1970, 1, 1)).total_seconds() | a708448fb8cb504c2d25afa5bff6208abe1159a4 | 708,457 |
def pratt_arrow_risk_aversion(t, c, theta, **params):
"""Assume constant relative risk aversion"""
return theta / c | ccbe6e74a150a4cbd3837ca3ab24bf1074d694c9 | 708,458 |
def getdate(targetconnection, ymdstr, default=None):
"""Convert a string of the form 'yyyy-MM-dd' to a Date object.
The returned Date is in the given targetconnection's format.
Arguments:
- targetconnection: a ConnectionWrapper whose underlying module's
Date format is used
- y... | 21d27c3ef4e99b28b16681072494ce573e592255 | 708,459 |
def operation_dict(ts_epoch, request_dict):
"""An operation as a dictionary."""
return {
"model": request_dict,
"model_type": "Request",
"args": [request_dict["id"]],
"kwargs": {"extra": "kwargs"},
"target_garden_name": "child",
"source_garden_name": "parent",
... | e7b63d79c6de73616b39e2713a0ba2da6f9e2a25 | 708,461 |
def memory_index(indices, t):
"""Location of an item in the underlying memory."""
memlen, itemsize, ndim, shape, strides, offset = t
p = offset
for i in range(ndim):
p += strides[i] * indices[i]
return p | ed97592aa5444cfd6d6894b042b5b103d2de6afc | 708,462 |
def _infer_color_variable_kind(color_variable, data):
"""Determine whether color_variable is array, pandas dataframe, callable,
or scikit-learn (fit-)transformer."""
if hasattr(color_variable, "dtype") or hasattr(color_variable, "dtypes"):
if len(color_variable) != len(data):
raise Value... | a1a21c6df4328331754f9fb960e64cf8bfe09be7 | 708,463 |
import os
def ParseChromeosImage(chromeos_image):
"""Parse the chromeos_image string for the image and version.
The chromeos_image string will probably be in one of two formats:
1: <path-to-chroot>/src/build/images/<board>/<ChromeOS-version>.<datetime>/ \
chromiumos_test_image.bin
2: <path-to-chroot>/ch... | 49652dad39bcc1df8b3decae4ec374adaf353185 | 708,464 |
from datetime import datetime
def datetime_to_epoch(date_time: datetime) -> int:
"""Convert a datetime object to an epoch integer (seconds)."""
return int(date_time.timestamp()) | 73767c663d66464420594e90a438687c9363b884 | 708,465 |
from functools import reduce
def inet_aton(s):
"""Convert a dotted-quad to an int."""
try:
addr = list(map(int, s.split('.')))
addr = reduce(lambda a,b: a+b, [addr[i] << (3-i)*8 for i in range(4)])
except (ValueError, IndexError):
raise ValueError('illegal IP: {0}'.format(s))
r... | abc16c14e416f55c9ae469b4b9c1958df265433c | 708,466 |
def helper():
"""I'm useful helper"""
data = {
"31 Dec 2019": "Wuhan Municipal Health Commission, China, reported a cluster of cases of pneumonia in Wuhan, Hubei Province. A novel coronavirus was eventually identified.",
"1 January 2020": "WHO had set up the IMST (Incident Management Support Tea... | 1f0f58505ce4179d56b2bf6e4cb29e42cdd7cfc9 | 708,467 |
def otherEnd(contours, top, limit):
"""
top与end太近了,找另一个顶部的点,与top距离最远
"""
tt = (0, 9999)
for li in contours:
for pp in li:
p = pp[0]
if limit(p[0]) and top[1] - p[1] < 15 and abs(top[0] - p[0]) > 50 and p[1] < tt[1]:
tt = p
return tt | 4f938d33ba28c1999603cd60381ed6d9aec23815 | 708,468 |
def preprocessing(string):
"""helper function to remove punctuation froms string"""
string = string.replace(',', ' ').replace('.', ' ')
string = string.replace('(', '').replace(')', '')
words = string.split(' ')
return words | 17f41a566c3661ab6ffb842ac6d610425fc779d1 | 708,469 |
def _get_rating_accuracy_stats(population, ratings):
"""
Calculate how accurate our ratings were.
:param population:
:param ratings:
:return:
"""
num_overestimates = 0
num_underestimates = 0
num_correct = 0
for employee, rating in zip(population, ratings):
if rating < em... | 6fefd6faf465a304acc692b465f575cc4c3a62e3 | 708,470 |
from typing import Optional
from typing import Any
def get_or_create_mpc_section(
mp_controls: "MpConfigControls", section: str, subkey: Optional[str] = None # type: ignore
) -> Any:
"""
Return (and create if it doesn't exist) a settings section.
Parameters
----------
mp_controls : MpConfigC... | 60b741f35e0a1c9fe924b472217e0e3b62a1d31e | 708,471 |
def encrypt(plaintext, a, b):
"""
加密函数:E(x) = (ax + b)(mod m) m为编码系统中的字母数,一般为26
:param plaintext:
:param a:
:param b:
:return:
"""
cipher = ""
for i in plaintext:
if not i.isalpha():
cipher += i
else:
n = "A" if i.isupper() else "a"
... | 0cbb57250d8d7a18740e19875f79127b8057ab06 | 708,472 |
import pathlib
import shlex
import os
def construct_gn_command(output_path, gn_flags, python2_command=None, shell=False):
"""
Constructs and returns the GN command
If shell is True, then a single string with shell-escaped arguments is returned
If shell is False, then a list containing the command and ... | 2177ea4436305733268a427e0c4b006785e41b2d | 708,473 |
def _url_as_filename(url: str) -> str:
"""Return a version of the url optimized for local development.
If the url is a `file://` url, it will return the remaining part
of the url so it can be used as a local file path. For example,
'file:///logs/example.txt' will be converted to
'/logs/example.txt'... | d1aef7a08221c7788f8a7f77351ccb6e6af9416b | 708,474 |
def CheckStructuralModelsValid(rootGroup, xyzGridSize=None, verbose=False):
"""
**CheckStricturalModelsValid** - Checks for valid structural model group data
given a netCDF root node
Parameters
----------
rootGroup: netCDF4.Group
The root group node of a Loop Project File
xyzGri... | d11ce42b041b8be7516f827883a37b40f6f98477 | 708,475 |
def link_name_to_index(model):
""" Generate a dictionary for link names and their indicies in the
model. """
return {
link.name : index for index, link in enumerate(model.links)
} | ba0e768b1160218908b6ecf3b186a73c75a69894 | 708,476 |
def get_border(border, size):
"""
Get border
"""
i = 1
while size - border // i <= border // i: # size > 2 * (border // i)
i *= 2
return border // i | 45233f53cdf6f0edb5b4a9262b61f2a70ac42661 | 708,477 |
import re
def _get_values(attribute, text):
"""Match attribute in text and return all matches.
:returns: List of matches.
"""
regex = '{}\s+=\s+"(.*)";'.format(attribute)
regex = re.compile(regex)
values = regex.findall(text)
return values | 59a0fdb7a39221e5f728f512ba0aa814506bbc37 | 708,478 |
def registry():
"""
Return a dictionary of problems of the form:
```{
"problem name": {
"params": ...
},
...
}```
where `flexs.landscapes.AdditiveAAVPackaging(**problem["params"])` instantiates the
additive AAV packaging landscape for the given set of paramet... | 5dd2e4e17640e0831daf02d0a2a9b9f90305a1c4 | 708,480 |
def is_in_period(datetime_, start, end):
"""指定した日時がstartからendまでの期間に含まれるか判定する"""
return start <= datetime_ < end | 3b830cb8d9e74934a09430c9cd6c0940cf36cf2e | 708,481 |
import requests
def get_session(token, custom_session=None):
"""Get requests session with authorization headers
Args:
token (str): Top secret GitHub access token
custom_session: e.g. betamax's session
Returns:
:class:`requests.sessions.Session`: Session
"""
sessi... | 88bf566144a55cf36daa46d3f9a9886d3257d767 | 708,482 |
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = unicodedata.normalize('NFD', text)
text = text.encode('ascii', 'ignore')
text = text.... | 4a6e11e0a72438a7e604e90e44a7220b1426df69 | 708,483 |
import json
def json_formatter(result, _verbose):
"""Format result as json."""
if isinstance(result, list) and "data" in result[0]:
res = [json.dumps(record) for record in result[0]["data"]]
output = "\n".join(res)
else:
output = json.dumps(result, indent=4, sort_keys=True)
re... | 68aae87577370d3acf584014651af21c7cbfa309 | 708,484 |
def pipe_hoop_stress(P, D, t):
"""Calculate the hoop (circumferential) stress in a pipe
using Barlow's formula.
Refs: https://en.wikipedia.org/wiki/Barlow%27s_formula
https://en.wikipedia.org/wiki/Cylinder_stress
:param P: the internal pressure in the pipe.
:type P: float
:param D: the ou... | 9985d35c2c55e697ce21a880bb2234c160178f33 | 708,485 |
import os
def parse_file_name(filename):
"""
Parse the file name of a DUD mol2 file to get the target name and the y label
:param filename: the filename string
:return: protein target name, y_label string (ligand or decoy)
"""
bname = os.path.basename(filename)
splitted_bname = bname.split... | 8f9de132e622feffc513453be36b80f386b36c9c | 708,486 |
def _IsSingleElementTuple(token):
"""Check if it's a single-element tuple."""
close = token.matching_bracket
token = token.next_token
num_commas = 0
while token != close:
if token.value == ',':
num_commas += 1
if token.OpensScope():
token = token.matching_bracket
else:
token = to... | 8d675bcee737ddb106817db79e2b989509d2efaa | 708,487 |
import numpy
def ReadCan(filename):
"""Reads the candump in filename and returns the 4 fields."""
trigger = []
trigger_velocity = []
trigger_torque = []
trigger_current = []
wheel = []
wheel_velocity = []
wheel_torque = []
wheel_current = []
trigger_request_time = [0.0]
tr... | 773657474462aa3a129ea7459c72ea0b0dc0cefa | 708,488 |
def delta_t(soil_type):
""" Displacement at Tu
"""
delta_ts = {
"dense sand": 0.003,
"loose sand": 0.005,
"stiff clay": 0.008,
"soft clay": 0.01,
}
return delta_ts.get(soil_type, ValueError("Unknown soil type.")) | c542adb7c302bc1f50eb4c49bf9da70932758814 | 708,489 |
def user(user_type):
"""
:return: instance of a User
"""
return user_type() | a8c8cd4ef57915c555864f6fc09dce63c2a1c6fb | 708,490 |
def true_or_false(item):
"""This function is used to assist in getting appropriate
values set with the PythonOption directive
"""
try:
item = item.lower()
except:
pass
if item in ['yes','true', '1', 1, True]:
return True
elif item in ['no', 'false', '0', 0, None, Fal... | 3e7c0cee07f6796c6134b182572a7d5ff95cf42d | 708,491 |
import time
def time_ms():
"""currently pypy only has Python 3.5.3, so we are missing Python 3.7's time.time_ns() with better precision
see https://www.python.org/dev/peps/pep-0564/
the function here is a convenience; you shall use `time.time_ns() // 1e6` if using >=Python 3.7
"""
return int(time... | 1bff241db79007314d7a876ddd007af137ba7306 | 708,492 |
import pipes
def login_flags(db, host, port, user, db_prefix=True):
"""
returns a list of connection argument strings each prefixed
with a space and quoted where necessary to later be combined
in a single shell string with `"".join(rv)`
db_prefix determines if "--dbname" is prefixed to the db arg... | 2c844def8e6f1154a9962d43c858b39b9a7adf2a | 708,493 |
def roi_intersect(a, b):
"""
Compute intersection of two ROIs.
.. rubric:: Examples
.. code-block::
s_[1:30], s_[20:40] => s_[20:30]
s_[1:10], s_[20:40] => s_[10:10]
# works for N dimensions
s_[1:10, 11:21], s_[8:12, 10:30] => s_[8:10, 11:21]
"""
def slice_inter... | d1070c8ec0c493296dfee6bdc54b7430e703bda8 | 708,494 |
def _flows_finished(pgen_grammar, stack):
"""
if, while, for and try might not be finished, because another part might
still be parsed.
"""
for stack_node in stack:
if stack_node.nonterminal in ('if_stmt', 'while_stmt', 'for_stmt', 'try_stmt'):
return False
return True | dd0fe435d1328b3ae83ba2507006b6825ca23087 | 708,495 |
def PositionToPercentile(position, field_size):
"""Converts from position in the field to percentile.
position: int
field_size: int
"""
beat = field_size - position + 1
percentile = 100.0 * beat / field_size
return percentile | c75869f3d7f8437f28d3463fcf12b2b446fe930a | 708,496 |
from typing import Tuple
import os
from typing import cast
def _terminal_size(fallback: Tuple[int, int]) -> Tuple[int, int]:
"""
Try to get the size of the terminal window.
If it fails, the passed fallback will be returned.
"""
for i in (0, 1):
try:
window_width = os.get_termin... | 3254068444167bad0b87479001b0c22887b32a60 | 708,497 |
import ast
def _compile(s: str):
"""compiles string into AST.
:param s: string to be compiled into AST.
:type s: str
"""
return compile(
source = s,
filename = '<unknown>',
mode = 'eval',
flags = ast.PyCF_ONLY_AST,
) | 4709cfa84ab6e5d7210924cf3aa206a1d297b7bd | 708,498 |
def temp_get_users_with_permission_form(self):
"""Used to test that swapping the Form method works"""
# Search string: ABC
return () | 72390791304d62fc5d78720aac4e2807e918587c | 708,499 |
def hi_joseangel():
""" Hi Jose Angel Function """
return "hi joseangel!" | 5889a51977d3ec2269040a9a7e7968801209ff25 | 708,500 |
def pytest_report_header(config, startdir):
"""return a string to be displayed as header info for terminal reporting."""
capabilities = config.getoption('capabilities')
if capabilities:
return 'capabilities: {0}'.format(capabilities) | 4e6ada67f5f08c1db8f5b6206089db4e3ee84f46 | 708,501 |
def chessboard_distance(x_a, y_a, x_b, y_b):
"""
Compute the rectilinear distance between
point (x_a,y_a) and (x_b, y_b)
"""
return max(abs(x_b-x_a),abs(y_b-y_a)) | 9b11bf328faf3b231df23585914f20c2efd02bf9 | 708,502 |
def str_with_tab(indent: int, text: str, uppercase: bool = True) -> str:
"""Create a string with ``indent`` spaces followed by ``text``."""
if uppercase:
text = text.upper()
return " " * indent + text | 3306ba86781d272a19b0e02ff8d06da0976d7282 | 708,503 |
from typing import List
def finding_the_percentage(n: int, arr: List[str], query_name: str) -> str:
"""
>>> finding_the_percentage(3, ['Krishna 67 68 69', 'Arjun 70 98 63',
... 'Malika 52 56 60'], 'Malika')
'56.00'
>>> finding_the_percentage(2, ['Harsh 25 26.5 28', 'Anurag 26 28 30'],
... 'Har... | 86c2ad777c667f9ba424bc2b707f46465a10accc | 708,505 |
def mvg_logpdf_fixedcov(x, mean, inv_cov):
"""
Log-pdf of the multivariate Gaussian distribution where the determinant and inverse of the covariance matrix are
precomputed and fixed.
Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is
irrelevant ... | 648d1925ed4b4793e8e1ce1cec8c7ccd0efb9f6b | 708,506 |
def extrode_multiple_urls(urls):
""" Return the last (right) url value """
if urls:
return urls.split(',')[-1]
return urls | 34ec560183e73100a62bf40b34108bb39f2b04b4 | 708,508 |
def take_last_while(predicate, list):
"""Returns a new list containing the last n elements of a given list, passing
each value to the supplied predicate function, and terminating when the
predicate function returns false. Excludes the element that caused the
predicate function to fail. The predicate fun... | 19468c9130e9ab563eebd97c30c0e2c74211e44b | 708,509 |
def abs_p_diff(predict_table, categA='sandwich', categB='sushi'):
"""Calculates the absolute distance between two category predictions
:param predict_table: as returned by `predict_table`
:param categA: the first of two categories to compare
:param categB: the second of two categoreis to compare
:r... | 235bfc7df29ac4a2b67baff9dfa3ee62204a9aed | 708,512 |
def _is_target_feature(column_names, column_mapping):
"""Assert that a feature only contains target columns if it contains any."""
column_names_set = set(column_names)
column_types = set(column['type']
for column_name, column in column_mapping.iteritems()
if column_name i... | 098af45938c616dd0ff2483a27131f15ba50797b | 708,513 |
def validate_engine_mode(engine_mode):
"""
Validate database EngineMode for DBCluster
Property: DBCluster.EngineMode
"""
VALID_DB_ENGINE_MODES = (
"provisioned",
"serverless",
"parallelquery",
"global",
"multimaster",
)
if engine_mode not in VALID_DB... | 69f7952a998b6ca593106c92710909104e21f55f | 708,514 |
def num_false_positives(df):
"""Total number of false positives (false-alarms)."""
return df.noraw.Type.isin(['FP']).sum() | 6aa339b86d15072c6a6910a43e70281575da5d36 | 708,515 |
def gcd_recursive_by_divrem(m, n):
"""
Computes the greatest common divisor of two numbers by recursively getting remainder from
division.
:param int m: First number.
:param int n: Second number.
:returns: GCD as a number.
"""
if n == 0:
return m
return gcd_recursive_by_div... | bd25d9cea4813e523ea6bb9bd85c24bf43dd2744 | 708,516 |
def get_mzi_delta_length(m, neff=2.4, wavelength=1.55):
""" m*wavelength = neff * delta_length """
return m * wavelength / neff | 5bcd4b9b217c79a06b48856f7801060787f12e52 | 708,517 |
def create_include(workflow_stat):
"""
Generates the html script include content.
@param workflow_stat the WorkflowInfo object reference
"""
include_str = """
<script type='text/javascript' src='bc_action.js'>
</script>
<script type='text/javascript' src='bc_""" + workflow_stat.wf_uuid +"""_data.js'>
</script>
"... | 24151952c9dd5bc4034916dae90a3760fc06ca44 | 708,519 |
import subprocess
def run_command_unchecked(command, cwd, env=None):
"""Runs a command in the given dir, returning its exit code and stdio."""
p = subprocess.Popen(
command,
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
)
std... | 89c6fd0acf7e8bb81c837f78252bdaa30fe39ad1 | 708,520 |
import sys
def postfix(itemString):
"""transform infixExpre into postfixExpre
Algorithm:
step1: if operator, stack in;
step2: if "(", stack in.
step3: if variable, pop out the all continued unary operator until other operator or "("
step4: if ")", pop out all operators until "(... | 1c3bee30f450c1dfab6ca7d0dd057465d8b6e8e5 | 708,521 |
def getSuffixes(algorithm, seqType) :
""" Get the suffixes for the right algorithm with the right
sequence type
"""
suffixes = {}
suffixes['LAST'] = {}
suffixes['BLAST'] = {}
suffixes['BLAST']['nucl'] = ['nhr', 'nsq', 'nin']
suffixes['BLAST']['prot'] = ['phr', 'psq', 'pin']
s... | 9ab699a71be73381c4dff555f0ef19201589e82f | 708,522 |
def compare_names(namepartsA, namepartsB):
"""Takes two name-parts lists (as lists of words) and returns a score."""
complement = set(namepartsA) ^ set(namepartsB)
intersection = set(namepartsA) & set(namepartsB)
score = float(len(intersection))/(len(intersection)+len(complement))
return score | 87cbceaaa0acce0b83b5faf66cbe909ad52382eb | 708,523 |
def commonprefix(a, b):
"""Find longest common prefix of `a` and `b`."""
pos = 0
length = min(len(a), len(b))
while pos < length and a[pos] == b[pos]:
pos += 1
return pos, b | 75e2f9ac6c3d0c38986cba5f8409ddc87fe8edbe | 708,524 |
import math
def get_polyend_circle_angles(a, b, isLeft):
"""
theta0 = pi/2 + betta, theta1 = 2 * pi + betta;
betta = pi/2 - alpha;
alpha = atan(a)
"""
if a is None and b is None:
return None, None
alpha = math.pi / 2.0 if a is None else math.atan(a)
betta = math.pi / 2.0 - a... | 9547ba4ea9f74cba3d52d90bb24dc8c4b246fbff | 708,525 |
import re
def get_search_cache_key(prefix, *args):
""" Generate suitable key to cache twitter tag context
"""
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
retur... | f3ff5baa13e4e84deb5c13cd8d5b618ba75c8699 | 708,526 |
def set_prior_6(para):
"""
set prior before the first data came in
doc details to be added
"""
n_shape = para['n_shape']
log_prob = [ [] for i_shape in range(n_shape) ]
delta_mean = [ [] for i_shape in range(n_shape) ]
delta_var = [ [] for i_shape in range(n_shape) ]
time_since_last... | e97944e1c48ca6def16308584dfe04eaebae6259 | 708,527 |
def overviewUsage(err=''):
""" default overview information highlighting active scripts"""
m = '%s\n' %err
m += ' The following scripts allow you to manage Team Branches (TmB) on SalesForce.\n'
m += ' Use one of the scripts below to meet your needs.\n'
m += ' \n'
m += ' 1. First link Task Br... | ba62773dd8be21d17c44e8e295c8228d568512a0 | 708,528 |
def lorem():
"""Returns some sample latin text to use for prototyping."""
return """
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nis... | 6ddacdb23b7c62cf930e622a7fd801b514a419ae | 708,529 |
def make_list_table(headers, data, title='', columns=None):
"""Build a list-table directive.
:param headers: List of header values.
:param data: Iterable of row data, yielding lists or tuples with rows.
:param title: Optional text to show as the table title.
:param columns: Optional widths for the ... | 569370b8359ad25bf255f940b5a89d93d896804d | 708,530 |
def split_val_condition(input_string):
"""
Split and return a {'value': v, 'condition': c} dict for the value and the condition.
Condition is empty if no condition was found.
@param input A string of the form XXX @ YYYY
"""
try:
(value, condition) = [x.strip() for x in input_string.s... | 97c5733a80b3348928b95e2430bf3630867b2050 | 708,531 |
def pre_process(dd, df, dataset_len, batch_size):
"""Partition one dataframe to multiple small dataframes based on a given batch size."""
df = dd.str2ascii(df, dataset_len)
prev_chunk_offset = 0
partitioned_dfs = []
while prev_chunk_offset < dataset_len:
curr_chunk_offset = prev_chunk_offset... | a0a19916d60476430bdaf27f85f31620f2b5ae2a | 708,532 |
def _make_unique(key, val):
"""
Make a tuple of key, value that is guaranteed hashable and should be unique per value
:param key: Key of tuple
:param val: Value of tuple
:return: Unique key tuple
"""
if type(val).__hash__ is None:
val = str(val)
return key, val | 65d746276f635c129aa0a5aeb9b9f467453c0b2a | 708,533 |
def headline(
in_string,
surround = False,
width = 72,
nr_spaces = 2,
spacesym = ' ',
char = '=',
border = None,
uppercase = True,
):
"""return in_string capitalized, spaced and sandwiched:
============================== T E S T... | 1848d91bbf6c9d2216338f35433a26bcd3854664 | 708,534 |
def try_(func, *args, **kwargs):
"""Try to call a function and return `_default` if it fails
Note: be careful that in order to have a fallback, you can supply
the keyword argument `_default`. If you supply anything other
than a keyword arg, it will result in it being passed to the wrapped
function a... | 206b25bd2e345d9cd6423e2cbc2706c274f36c89 | 708,535 |
def get_label_names(l_json):
"""
Get names of all the labels in given json
:param l_json: list of labels jsons
:type l_json: list
:returns: list of labels names
:rtype: list
"""
llist = []
for j in l_json:
llist.append(j['name'])
return llist | bab12bedc8b5001b94d6c5f02264b1ebf4ab0e99 | 708,536 |
def _n_pow_i(a, b, n):
"""
return (1+i)**k
"""
x = a
y = b
for i in range(1, n):
x1 = (x*a) - (y*b)
y1 = (y*a) + (x*b)
x = x1
y = y1
return x, y | 35b00c7bc76aaf19a5acdf012e63c9c0c50e5d1d | 708,537 |
def cg_file_h(tmpdir):
"""Get render config."""
return {
'cg_file': str(tmpdir.join('muti_layer_test.hip'))
} | caedb2324953e4ca90ebffdf80be60fed1b8026d | 708,538 |
def interpolate_peak(spectrum: list, peak: int) -> float:
""" Uses quadratic interpolation of spectral peaks to get a better estimate of the peak.
Args:
- spectrum: the frequency bin to analyze.
- peak: the location of the estimated peak in the spectrum list.
Based off: htt... | 0e74057908e7839438325da9adafdf385012ce17 | 708,539 |
def find_title(item):
"""Title of the video"""
title = item['snippet']['title']
return title | 9c6f64e02d959d46cfd1e4536f5faf7ec0c281bd | 708,540 |
import hashlib
def calc_fingerprint(text):
"""Return a hex string that fingerprints `text`."""
return hashlib.sha1(text).hexdigest() | 8be154e4e32ae9412a73e73397f0e0198ae9c862 | 708,541 |
import six
def pad_for_tpu(shapes_dict, hparams, max_length):
"""Pads unknown features' dimensions for TPU."""
padded_shapes = {}
def get_filler(specified_max_length):
if not specified_max_length:
return max_length
return min(specified_max_length, max_length)
inputs_none_filler = get_filler(hp... | b72e1463fad9740c8a265b795c4b3c5a45e42a9a | 708,542 |
def has_balanced_parens(exp: str) -> bool:
"""
Checks if the parentheses in the given expression `exp` are balanced,
that is, if each opening parenthesis is matched by a corresponding
closing parenthesis.
**Example:**
::
>>> has_balanced_parens("(((a * b) + c)")
False
:par... | f76c7cafcf6aadd0c2cb947f0c49d23835a9f6e4 | 708,543 |
def _is_binary(c):
"""Ensures character is a binary digit."""
return c in '01' | b763a5a8ba591b100fea64a589dcb0aea9fbcf53 | 708,544 |
def read_frame_positions(lmp_trj):
""" Read stream positions in trajectory file corresponding to
time-step and atom-data.
"""
ts_pos, data_pos = [], []
with open(lmp_trj, 'r') as fid:
while True:
line = fid.readline()
if not line:
break
... | c168f08577e38758bf3d9d42bae8379125d7fc33 | 708,545 |
def home():
"""
Display Hello World in a local-host website
"""
return 'Hello World' | f65a035d679878cfd897c9ea9c79fc41cf76db95 | 708,546 |
def sum_by_letter(list_of_dicts, letter):
"""
:param list_of_dicts: A list of dictionaries.
:param letter: A value of the letter keyed by 'letter'.
"""
total = 0
for d in list_of_dicts:
if d['letter'] == letter:
total += d['number']
return total | bffc5990eaa9e352d60d86d40b8a8b7070fd00c0 | 708,547 |
def gate_settle(gate):
""" Return gate settle times """
return 0 | f452a343550c4f7be2133119c89dc386665921c4 | 708,548 |
def strip_trailing_characters(unstripped_string, tail):
"""
Strip the tail from a string.
:param unstripped_string: The string to strip. Ex: "leading"
:param tail: The trail to remove. Ex: "ing"
:return: The stripped string. Ex: "lead"
"""
if unstripped_string.endswith(str(tail)):
... | dbd09fe9a58b0fb3072a680a9c7ac701257ebfcd | 708,549 |
def is_prime(x):
""" Prove if number is prime """
if x == 0 or x == 1:
return 0
for i in range(2, x//2 +1):
if x % i == 0:
return 0
return 1 | 63980c49b9ea05458ecafe874073805df50ce1d0 | 708,550 |
import re
def isphone(value, locale='en-US'):
"""
Return whether or not given value is valid mobile number according to given locale. Default locale is 'en-US'.
If the value is valid mobile number, this function returns ``True``, otherwise ``False``.
Supported locales are: ``ar-DZ``, ``ar-SY``, ``ar-S... | 2e3de8fb6aad000c21ea560521f81c4e9bf2e090 | 708,551 |
def _darken(color):
"""
Takes a hexidecimal color and makes it a shade darker
:param color: The hexidecimal color to darken
:return: A darkened version of the hexidecimal color
"""
# Get the edge color
darker = "#"
hex1 = color[1:3]
hex2 = color[3:5]
hex3 = color[5:7]
for val... | 5b43785572f9685906e73f4bf856cf4d693f6411 | 708,552 |
def flatten_acfg_list(acfg_list):
"""
Returns a new config where subconfig params are prefixed by subconfig keys
"""
flat_acfg_list = []
for acfg in acfg_list:
flat_dict = {
prefix + '_' + key: val
for prefix, subdict in acfg.items()
for key, val in subdic... | ae586bc49ee31db022f388492acbbf5e8d02b09d | 708,553 |
from typing import Optional
def q_to_res(Q: float) -> Optional[float]:
"""
:param Q: Q factor
:return: res, or None if Q < 0.25
"""
res = 1 - 1.25 / (Q + 1)
if res < 0.0:
return None
return res | 98380be0c8fbd3bfd694d7851f35488d74cdd862 | 708,554 |
def id_str_to_bytes(id_str: str) -> bytes:
"""Convert a 40 characters hash into a byte array.
The conversion results in 160 bits of information (20-bytes array). Notice
that this operation is reversible (using `id_bytes_to_str`).
Args:
id_str: Hash string containing 40 characters.
Returns... | cd6a702343f1267e17710305f9aed70613feacb3 | 708,555 |
def create_process_chain_entry(input_object, python_file_url,
udf_runtime, udf_version, output_object):
"""Create a Actinia command of the process chain that uses t.rast.udf
:param strds_name: The name of the strds
:param python_file_url: The URL to the python file that defin... | 78a76275a2f1dba30627f1a52acd88d2ce851ccc | 708,556 |
import random
def define_answer(defined_answer):
"""
ランダムに「正解」を生成する
1桁ずつ、0~15までの乱数を引いて決めていく
count桁目の乱数(digit_kari)を引いた時、count-1桁目までの数字と重複がないかをチェック。
重複がなければ、引いた乱数(digit_kari)をans_list[count]に保存。
重複してたらその桁の乱数を引き直す。
"""
global ans_str #,ans_list
if type(defined_answer) == st... | fa19b2e28864d4c09458582d6dea80b81b3426f6 | 708,557 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.