content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def timedistr(lstpos):
"""return a list of time distribution,
-2048..0..2047 -> 2048..4096.0..2047 or 0-4096 overall
-2048..2048 ~ -180~180 with the T center at 0
so to get back: i - 4096 if i > 2047
against the position
"""
#pos360 = [int(360*i/4096) for i in lstpos]
## import numpy as n... | 0a8b62bc8a3f744c5a281574ccab71a4ba8b80ab | 648,448 |
def pre(sql_in, params):
"""
Pre process sachima sql into agg mode before run it
usage:
"model": [("s_0038_apply.sql", db.ENGINE_IMPALA_DW, pivot_table.pre)],
"""
measures = params.get("measures") # measure_name,sum
p_index = params.get("row_dims") # list
p_col = params.get("col_dim... | 872db7b7acedea40aa55a48c620b59f221743016 | 648,449 |
def IsFatalPushFailure(push_stdout):
"""True if retrying push won't help."""
return '(prohibited by Gerrit)' in push_stdout | 393093702179378f827772e6a635e30b1c9aa4d5 | 648,450 |
def srun(arg_dict,qos=True,time=10,mem=4):
"""Return srun call, with certain parameters appended.
Arguments:
----------
arg_dict : dict
Dictionary of arguments passed into this script, which is used to append parameters to srun call.
qos : bool, optional
Quality of service, set to ... | 7769b4023a2caa9a3b0bfe47ea12af48ecf930f6 | 648,451 |
from functools import reduce
def reduce1_factorial(num):
"""Solution that uses reduce and a lambda"""
return reduce(lambda x, y: x * y, range(1, num + 1), 1) | 58a9709dc025749a57cfb0fd33b5a418a1d5975f | 648,452 |
import os
def get_high_res_hands(
folder_bought_template='misc/ten24_TexturesHands_R_L_RL_{:04d}/',
folder_inhouse_template='misc/may_2018_inhouse_mpi_hands_{:04d}/',
res=512,
split='train',
hand_type='BOTH',
texture_types=['in_house', 'bought']):
"""
Args:
... | 82c3188db67dc857a961666b10f4f29a5b406686 | 648,453 |
def split_unique(df_data, field):
"""
Split the DataFrame based on unique value from field
Parameters
----------
df_data : pandas DataFrame
Original data to split
field : String
Column name to split data on unique value
Returns
-------
df_split : dict
A dic... | e062b5721b80e29c0871b43fe1ae2081e04c9569 | 648,454 |
def get_edge_vertex_ids(g, sort=True):
"""get_edge_vertex_ids
Returns a list of tuples containing the source and target for each edge in
the graph.
Parameters
----------
g : :obj:`graph_tool.Graph`
A graph with edges.
sorted : :obj:`bool`:
Determines whether... | 8d942e7ff62213510de7ebefc53faeef0f4de07b | 648,455 |
def make_comment_body(comment_text):
"""Build body of the add issue comment request"""
return {
"body": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
... | a193e4ea6ab1257130cf05177b34060803e49fae | 648,456 |
def logistic(x, r):
"""Logistic map, with parameter r."""
return r * x * (1 - x) | cea604f4bac55d9229add831fd3c3f36a0bcf212 | 648,457 |
import uuid
def generate_unique_node():
""" Generate a unique node label."""
return str(uuid.uuid1()) | 375109d497ad635717e305a7b102f88ac0e13b1a | 648,458 |
def get_emotion_dict(emo_metrics):
"""Returns a dictionary in which keys are emotions and values are confidences.
Args:
emo_metrics: A list of dictionaries, which each have the keys 'name' and
'confidence', describing emotions detected from FeelNet.
Returns:
A dictionary as described above.
"""
... | 911f317ac6a63318f8fe1366251edb84d6feb1b1 | 648,459 |
import re
def isExist(content, error_print):
"""
:method: a sub-method to check isExist
:param content: string;the content which is checked
:param error_print: string
:return: string("yes" or "no")
"""
pat_nothing = re.compile(r'No items found')
searchable = re.search(pat_nothing, cont... | 77e731c4289779c1d5a931c38fb67aa336da40ae | 648,460 |
import zipfile
import os
def unzip(filename):
""" unzip a file
"""
try:
with zipfile.ZipFile(filename,"r") as zip_ref:
zip_ref.extractall(os.path.dirname(filename))
except Exception as oops:
print("nvdjsonloader.py.unzip: %s, %s" % (oops, filename))
return False
... | 29a14f0f1ad96c655c689fbe622cf8ca27b561fc | 648,461 |
import random
def split_rollouts(rollouts, train_frac=0.9):
"""Train-test split
Useful for sample_batch
"""
idxes = list(range(rollouts['obses'].shape[0]))
random.shuffle(idxes)
if train_frac is not None:
n_train_examples = int(train_frac * len(idxes))
train_idxes = idxes[:n_train_examples]
va... | 7c0305b16a78e4391ab65eba9dbbcc111342c969 | 648,462 |
def encode_int(i):
"""Encode an integer for a bytes database."""
return bytes(str(i), "utf-8") | 96f405d02c1fd53316ad9b81cfc8e5eceac453f1 | 648,463 |
def obj_to_dict(obj):
"""Converts XML object to an easy to use dict."""
if obj is None:
return None
res = {}
res['type'] = obj.tag
res['id'] = obj.get('id')
res['version'] = int(obj.get('version'))
res['deleted'] = obj.get('visible') == 'false'
if obj.tag == 'node' and 'lon' in o... | fe87dc779a948a1161bb6b570c128fd996ccfda4 | 648,464 |
from typing import List
from pathlib import Path
from typing import Set
def get_cl_tags(files: List[Path]) -> List[str]:
"""
Come up with descriptive tags given a list of files changed.
For each path, use the first rule that applies in the following order:
1) Pick the path component right after the last "li... | bb274802e7e9f00af3c76c36b8ba48b085266db2 | 648,466 |
def sep_params(model, loaded_roberta_keys):
"""Separate the parameters into loaded and not loaded."""
loaded_params = dict()
not_loaded_params = dict()
params_to_freeze = []
small_lr_params = dict()
large_lr_params = dict()
for n, p in model.named_parameters():
if n in loaded_roberta... | 3b1e55b1c4c96faaa910c601a1444562b3b10208 | 648,467 |
def _make_list(x):
"""Make list when it is necessary"""
if type(x) == list:
return x
return [x] | b58da8ae9dd1c75a8a270d3b3364ec53167b2e9c | 648,468 |
def define_query(ra, dec, radius, use_all=False, extra=None):
"""
Define the SQL search string based on input, can be used by sqlcl
!!! NOTE !!!
This is still a very rough search,
"""
radius += 0.12
if extra:
radius += extra
# convert into arcmin
radius *= 60.0
if (use_... | 5984f48881fc21ce8a979a637d27b4a9d81ea2c8 | 648,469 |
def get_go_version():
"""Not currently implemented"""
return None | df8835284a3b81c7851cb719a0c0954ed229b451 | 648,471 |
def get_tuner_submodel_name(output_model_name="tuned_climpp", num_years=10, margin_in_days=45):
"""Returns submodel name for a given setting of model parameters
"""
return f"{output_model_name}_on_years{num_years}_margin{margin_in_days}" | 33b64040446de89387fd85bd58c47873712a3bd6 | 648,472 |
def validate_params(parameters, context=False, other_params={}):
"""Takes a list of parameters from a HTTP request and validates them
Returns a string of errors (or empty string) and a list of params
"""
# Initialize error and params
error_response = ''
params = {}
if context:
par... | 4526bb553e7ebaebe680a9a5acfda356621a019b | 648,473 |
def compute_chi_of_U(Z):
"""
Eq. 22 in Ferrara et al. 2019
"""
chi = 8.7e+4*Z
return chi | 5f3c45175e0b454c92596bbe46c849ca16994bcb | 648,474 |
def is_user_defined_new_style_class(obj):
"""Returns whether or not the specified instance is a user-defined type."""
return type(obj).__module__ != '__builtin__' | ecf5b6af6432648327551f06f758ac539fcef7fb | 648,475 |
def face_uv_get(face):
""" Workaround 2.5x change.
"""
me = face.id_data
uv_faces = me.uv_textures.active
if uv_faces:
return uv_faces.data[face.index]
else:
return None | 65556a6b8b3669e923e819d6fecc0602f64cda38 | 648,476 |
def test_nan(dataframe):
"""
Test if dataframe contains nan value
Parameters
----------
dataframe: pandas dataframe
Raises
------
ValueError
If contains nan, raise ValueError
Returns
-------
is_valid: boolean
True if did not contain nan, False if contain
... | 1dcc96521fbbff2f95d7e4395367f50882c3b96b | 648,477 |
def calculate_interest_amount_stipend(starting_amount, interest_rate):
"""
After X number of years, how much would I have in the bank?
:param starting_amount: The amount of money the bank has to start with.
:type starting_amount: double
:param interest_rate: The rate that interest is being added int... | 1b0f323a6b22e5fcdaf370bb62a7551c10cd76d0 | 648,479 |
import math
def absoluteAngleDifference(angle1, angle2, rad=1):
""" https://gamedev.stackexchange.com/questions/4467/comparing-angles-and-working-out-the-difference"""
ref = 180
if rad:
ref = math.radians(180)
diff = ref - abs( abs(angle1 - angle2) - ref)
return diff | 1f40a0cb37cafd59e1aa35f815f791fa2b7cd790 | 648,480 |
from bs4 import BeautifulSoup
def make_soup(xml_tree):
"""make beautifulsoup object for interpret xml file
Arguments:
xml_tree {string} -- content of xml file
Returns:
(list,string,bool) -- return list of all doc and root name in xml file
and check for exception files
"""
... | c849ab22a5e5cab55138f0d706d14426fdefd106 | 648,481 |
import math
def split_array_averagely(arr, m):
""" split the array to n small chunks with nearly the same sizes.
Args:
arr:
m:
Returns:
"""
n = int(math.ceil(len(arr) / float(m)))
return [arr[i:i + n] for i in range(0, len(arr), n)] | 5c1d466328eda29fcab521a8fa45a6576c5c39c7 | 648,482 |
def hits(service):
"""Returns metric 'Hits'."""
return service.metrics.select_by(**{'system_name': 'hits'})[0] | 001ff6efcc1e3027d0c1c2ab1d39f0c3e04d4643 | 648,483 |
def parse_field(field_string):
"""
Get a tuple of the first entries found in an psimitab column
(xref, value, desc)
:param field_string:
:return: A tuple (xref, value, desc) - desc is optional
"""
parts = field_string.split(":")
xref = parts[0]
rest = parts[1]
if "(" in rest:
... | 2e8454b29bd9be18601460a293b8ff0d72580b75 | 648,484 |
def get_package_name(package, customer=None, python="2.7"):
""" returns the egg filename (without the fs path),
e.g. nexiles.gateway.appservice-1.0.0-py2.7-customer.egg
"""
if customer:
return "{}-{}-py{}-{}.egg".format(
package.import_name,
package.version,
... | e0a5801cfe9e2ea0bf62cab9aa89f08a0394c612 | 648,485 |
def d1d2_index(det_df,d1,d2):
"""
Return the index of a given detector pair from det_df.
Parameters
----------
det_df : pandas dataFrame
dataFrame of detector pair indices and angles
d1 : int
detector 1 channel
d2 : int
detector 2 channel
Returns
---... | 540ef78b15ab8d5e85efd3b9528c199a1e21ad43 | 648,486 |
def mutable_set_of_primitives(primitives):
"""
Fixture that yields back :class:`~collections.MutableSet` instances that contain
a single primitive value.
"""
return {primitives} | 8e95860e899725b7152e97412490ddd43c0d96c6 | 648,487 |
import os
def ensure_file(file):
"""Ensure a single file exists, returns the full path of the file if True"""
# tilde expansion
file_path = os.path.expanduser(file)
assert os.path.isfile(file_path), "The file {} doesn't exist. Please create the file first".format(file)
return file_path | 08feb042bc24a81c1b6ba5fc94756670d7458b53 | 648,488 |
def load_from_file(ids, data_path = "."):
"""
Takes an array of ids or single id and loads that srt file and returns
the srt files in a dictionary with IDs as keys.
"""
if type(ids) is int or type(ids) is str:
with open(data_path+str(ids)+".srt","r") as f:
data = f.read()
... | 55b7eda06e6d7a2e928745e3ab3bba273bfb9723 | 648,490 |
from datetime import datetime
def parse_time(s='2016-03-16T17:31:14Z'):
"""
Converts Piazza Date-time format into a
pythonic construct.
Examples of Piazza Datetime:
- 2016-03-16T17:31:14Z
"""
format = "%Y-%m-%dT%H:%M:%SZ"
return datetime.strptime(s,format) | c8f2c7d31f091b2d0470a23eafc81e36bf09d685 | 648,491 |
from typing import Dict
from typing import Any
def occluders_too_close(occluder: Dict[str, Any], x_position: float, x_scale: float) -> bool:
"""Return True iff a new occluder at x_position with scale x_scale
would be too close to existing occluder occluder."""
existing_scale = occluder['shows'][0]['scale'... | a7a11b9b759fa743689e96f283ab0b9b34ee754d | 648,493 |
import argparse
def build_parser():
""" Build argument parser. """
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Required args
parser.add_argument("--test_gct_path", "-t", required=True,
help="path to i... | 3a99bf423a4b1e748d9f3816485f061bccb60fac | 648,494 |
def get_inputs(node, kwargs):
"""Helper function to get inputs"""
name = node["name"]
outputs_lookup = kwargs["outputs_lookup"]
inputs = node["inputs"]
attrs = node.get("attrs", {})
input_nodes = []
for ip in inputs:
input_node_name = outputs_lookup[ip[0]][ip[1]].name
input_... | b9b434505ccec5bb50bb97ef247c70b5d5ecf18f | 648,495 |
def write_header(header):
"""Write the header. Not implemented."""
return (header or []) | 29da9bb38544073dd65a6d5e32078c67fdd94ccb | 648,496 |
def safe_classifier(request, classifier):
"""
Fixture - instantiate NfqClassifier and clear **all** after test
:param request: test function
:type request: `:class:_pytest.python.SubRequest`
:param classifier: classifier fixture
:type classifier: `:class:common.classifier.NfqClassifier`
:r... | 2b3ef6b2b7c17139c61d8545219087d7951c4232 | 648,497 |
def birch(V, E0, B0, BP, V0):
"""
From Intermetallic compounds: Principles and Practice, Vol. I: Principles
Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos
paper downloaded from Web
case where n=0
"""
E = (
E0
+ 9 / 8 * B0 * V0 * ((V0 / V) ** (2 / 3) - 1... | a43c8af1a07ada8a8ab94fc7ce6d7fd677f09d12 | 648,498 |
def build_phenotype(phenotype_info):
"""Build a phenotype term object
Args:
phenotype(dict)
Returns:
phenotype_obj(dict)
"""
phenotype_obj = dict(
phenotype_id=phenotype_info["phenotype_id"],
disease_models=phenotype_info["disease_models"],
... | 5fd35c0b1a90b9d565f3363002116df38685a02f | 648,499 |
import os
def run_local_cmd(cmd, get_output = False):
"""
Runs a local command. Optionally, return the cmd output.
Input:
- cmd: Command to run.
- get_output: whether to return the output of the cmd.
"""
print( "Local cmd $ %s" % cmd )
if not ... | c1e20ea3565cedb02c30a8aa49d7f29f5ab78361 | 648,500 |
import numpy
def min_(x):
"""
[Y,I] = MIN(X) returns the index of the minimum value in vector I.
If the values along the first non-singleton dimension contain more
than one minimal element, the index of the first one is returned.
"""
if x.size <= 0:
return (numpy.array([None]), numpy.a... | b0a8e76f6a4b65a006b9273b20e30964c3945863 | 648,502 |
import re
def parse_show_install(cmd_output):
"""
Parse output of 'show install request'
:param cmd_output: an iterable of lines (str) from the command output
:return: (is_complete, is_success) tuple of bool. is_complete indicates whether the request completed,
is_success indicates whether... | c08af55ae1f07a0a2bf02dc86e1728ceec358c45 | 648,503 |
from typing import List
def split_string(x: str, n: int) -> List[str]:
"""
Split string into chunks of length n
"""
# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa
return [x[i:i+n] for i in range(0, len(x), n)] | f0ad8cb6208616d274ee8749fb5b4a51391b0c8d | 648,504 |
import tempfile
import os
import subprocess
def _markdown2wiki(markdown):
"""
Convert markdown to JIRA wiki format. Uses https://github.com/Shogobg/markdown2confluence
"""
if markdown is None:
return "\n" # Allow empty/blank input
with tempfile.TemporaryDirectory() as tmp_dir:
md_... | 02a956976aae4b2df400b1040fb6f16c3d328afc | 648,505 |
def _is_tabular(structure):
""" Determines if a PDS4 structure can be shown as a table.
Tabular structures are either:
(1) Tables, or
(2) Arrays
Parameters
----------
structure : Structure
PDS4 structure to check.
Returns
-------
bool
True if *structure... | e8dba310360e2c1c042aa3ddfe5330ce65ed7c78 | 648,506 |
def calc_row2(r, m1, m2):
""" Calculate a row 'r' of the multiplication output of matrices m1 and m2 """
d = []
print('Calculating for',r)
for y in range(m2.m):
# import pdb;pdb.set_trace()
# import forkedpdb;forkedpdb.ForkedPdb().set_trace()
d.append(sum(item[0]*item[1] f... | bbf48ac574697e1c263e45c521dd29cc7c981404 | 648,507 |
def init_track_kwargs(object_type):
"""
:returns: kwargs dict fro Track initialisation
"""
return {
'title': None,
'artist': None,
'album': None,
'duration': None,
'position': None,
'thumbnail_url': None,
'metadata': {
'object_id': None... | d48145882547658d468e189816a593a66830a8f3 | 648,508 |
def get_localized_name(name):
"""Returns the localizedName from the name object"""
locale = "{}_{}".format(
name["preferredLocale"]["language"],
name["preferredLocale"]["country"]
)
return name['localized'].get(locale, '') | efa32f51bf89d1f2262a225dcfb13ea3ae2fedbc | 648,509 |
import pathlib
import numpy
import io
def load_vec(
emb_path: pathlib.Path,
n_max: int = 200_000,
) -> numpy.ndarray:
"""Load vectors from FastText file."""
vectors = []
word2id = {}
with io.open(emb_path, 'r', encoding='utf-8', newline='\n', errors='ignore') as f:
next(f)
for... | c29f39d35d6ef9465e6f43d667b82487772bdd34 | 648,510 |
from datetime import datetime
def time_to_datetime(t_time):
"""
时间戳转datetime
"""
try:
d_time = datetime.fromtimestamp(t_time)
except OSError as ose:
return None
return d_time | bf7e9a23b866c838a2d28ddc03cac8f94d3ad814 | 648,511 |
def sort_strlist(s):
"""Deserialise, sort, and reserialise a list of strings in the format "potato,spade,elephant" """
return ','.join(sorted(s.strip().split(','))) | 94a575ba07d2d71f3c1f248fd5dbf90b1f7da3cc | 648,512 |
from bs4 import BeautifulSoup
def getText(keyfile):
"""
Extracts text from specified input file
@params:
keyfile - Required : file to process (file)
"""
try:
soup = BeautifulSoup(keyfile, "html.parser")
for script in soup(["script", "style"]):
script.extract(... | 6abdfe659986c22044f5aedbc847e747f495177f | 648,513 |
def format_tune_string(infos):
"""
Contruct a string from a dict created from an "User tune" event.
:param dict infos: The informations
:return: The formatted string
:rtype: :py:class:`str`
"""
elems = []
track = infos.get('track')
if track:
elems.append(track)
title = i... | c65e4a2b263bda1e75ceb68fa2c46e0b56bd2d83 | 648,514 |
import unittest
def test_suite():
"""Return the test suite, duh flake8.
Come on! If a function is obviously named it shouldn't require a docstring. This is pretty much like
commenting obvious code::
x += 1 # Increment x by 1
It's just noise and doesn't add anything. Inane flake8 adherence ... | 270d4971f62a5acce2bca921d12852af8611f54a | 648,515 |
def build_slack_payload(budgets, image_url):
"""
Builds the payload that is sent to the Slack webhook about
our budget overspend.
"""
details = "\n".join(
[f"{b.name}: {b.forecasted_spend} > {b.budget_limit}" for b in budgets]
)
return {
"username": "aws-budgets",
"i... | 314904333dd420aed9406f9078a6417ee65aa429 | 648,516 |
from typing import Callable
def _get_add_function() -> Callable:
"""
Return a function with the ability to track state, used for testing.
"""
def func(x: int, y: int) -> int:
func.executed = True # type: ignore[attr-defined]
return x + y
func.executed = False # type: ignore[att... | a06004f32b78d3562cd8409ab30583a37b764234 | 648,517 |
import re
def does_not_have_bad_pairs(chars):
"""
It does not contain the strings ab, cd, pq, or xy, even if they are part of
one of the other requirements.
"""
bad_pairs = ['ab', 'cd', 'pq', 'xy']
if not re.search('|'.join(bad_pairs), chars):
return True
return False | 5057b7d3bf27604b1a845a12c30307d248ab9098 | 648,520 |
def get_attribute(t, key: str):
"""
Get an attribute from a given callable
:param t: the callable
:param key: the key, the attributes name
:return: the attribute data
"""
return getattr(t, key) | b322382ae2273ec45e8f08b43abdfc1582fb0b4d | 648,521 |
import math
def scaling(axis_len):
"""Scaling of plot figure size
Parameter:
----------
axis_len : int
Number of rows or columns
Return:
----------
scale : float
scale for axis
"""
return 0.5/math.log10(axis_len) | 4af5c0e77b7f8e66ee44df4e95848271dfbe60df | 648,522 |
import pkg_resources
import json
def _load_data(file: str) -> dict:
"""Load the one of the data json files."""
stream = pkg_resources.resource_stream(__name__, file)
return json.load(stream) | f187809bc9fb6849e373ecf87414411611e43011 | 648,523 |
def der_order(order: int) -> str:
"""Return correct suffix for order.
>>> der_order(1)
... "1-st"
>>> der_order(4)
... "4-th"
"""
_suffix = ["st", "nd", "rd"]
if order - 1 > 3:
return f"{order}-th"
else:
return f"{order}-{_suffix[order - 1]}" | e073135851a8848c41fbdff75215cc0dfe3df7cd | 648,524 |
def accuracy(output, target):
"""
Computes accuracy, from predicted and true labels.
"""
batch_size = target.size(0)
_, pred = output.topk(1, 1, True, True)
correct = pred.eq(target.view(-1, 1).expand_as(pred))
correct_total = correct.float().sum()
return correct_total * (100.0 / batch_... | bbe07357c5d395a78553933403b220258029797e | 648,525 |
from typing import Set
def match_events(
a: Set[str],
b: Set[str]
) -> bool:
"""
Checks if two groups of events are matched.
:returns:
`True` - match found, `False` otherwise.
"""
return any(x in b for x in a) | a8653c9355629e661ba07ee12e759102426380dc | 648,527 |
def sel_class(num, prob):
""" Set num to 1 with with sufficient probability """
if num < prob:
return 0
else:
return 1 | 6b37ec485fbd1e364edb68eec137623000ea6d53 | 648,528 |
import os
import tarfile
def MkTarball(src, dst_tar_file):
"""Make tarball.
Note: basename of |src| would show up as a file's directory name in
a tar file.
e.g.
If you give "/tmp/foo/bar" that has followings inside as |src|:
/tmp/foo/bar/gomacc
/tmp/foo/bar/compiler_proxy
then, the generated arch... | 380cb771d624617791ca02778b635ea03e9cf506 | 648,529 |
def multicommand_get_command_short_help(self, ctx, cmd_name):
"""Returns the short help of a subcommand
It allows MultiCommand subclasses to implement more efficient ways to provide the subcommand short help, for
example by leveraging some caching.
Parameters
----------
ctx : click.core.Contex... | 0255615202c52f9a6ca82b12d273a97efbbee42d | 648,530 |
import json
def _parse_article_nos(dct):
"""\
Parses the article numbers.
Returns either a dict or None.
"""
article_numbers = dct.get('ft_article_nos')
if article_numbers in (None, '[]'):
return {}
# Use '' as key since JSON accepts only strings as key, not None / null
return... | a7f4ea0588b305b4614b5a5d08b25dac903e4dbe | 648,531 |
import string
import random
def id_generator(size=10, chars=string.ascii_letters + string.digits):
"""Method to create random ids
:param size: define the string size
:param chars: the characters to be use to create the string
return ''.join(random.choice(chars) for x in range(size))
"""
retu... | b626b6a25aff24b1f14183c1bb26a3600342c0b4 | 648,532 |
def mydub(a):
"""Double a
"""
return a * 2 | bf039316d510db53264ab435e5092477bd57e397 | 648,533 |
import torch
def get_IoU(predictions: torch.Tensor, labels: torch.Tensor, threshold: float = 0.5):
"""Code inspired by
https://www.kaggle.com/iezepov/fast-iou-scoring-metric-in-pytorch-and-numpy
"""
eps = 1e-6
# assert N x H x W
if len(predictions.shape) != 3:
predictions.unsqueeze_(0)... | e0189c98a09033f4ff80cedf9b638432c272edc8 | 648,534 |
def strip_comments(line: str) -> str:
"""Remove comments from line"""
# comment at the beginning of the line
if line.startswith("#"):
return ""
# in-line comment
left = line.rsplit("#", 1)[0]
# be sure we are not inside a string
if left.count('"') % 2 == 0 and left.count("'") % 2 ==... | bdefd26b2822e6126a7633ed9b954936d7660094 | 648,535 |
def get_alphabet_mapping(filename):
"""
Given a filename, return a 2D list of [alphabet1, alphabet2] representing
two alphabet list mappings
"""
with open(filename) as data:
res = []
for line in data.read().splitlines():
alphabet = []
for letter in line:
... | b3b007184b4849ce07097974d5e136f7adffc4dd | 648,536 |
def HMStime(s):
"""
Given the time in seconds, an appropriately formatted string.
"""
if s<60.:
return '%.3f s'%s
elif s<3600.:
return '%d:%.3f'%(int(s/60%60),s%60)
else:
return '%d:%d:%.3f'%(int(s/3600),int(s/60%60),s%60) | bb8f86084bc6a6473d4775d48439061f17c44000 | 648,537 |
import collections
def unique2lists(list1, list2, add=False):
"""Unique list1 and list2 based on list1
Args:
list1(list):
list2(list):
add(Optional(bool)): add list2 elements with list1 duplicates
Returns:
list,list
"""
if add:
cntr = collections.Counter()
... | 5f0fb90498339f6115b083a06fddf01385544be8 | 648,538 |
def format_ISO_time(year,doy,timestr):
"""
Format an ISO-like time string: YYYY-DDDTHH:MM
@param year : 4-digit year
@type year : str
@param doy : 3-digit day of year
@type doy : str
@param timestr : HHMM
@type timestr : str
@return: str
"""
return year + '-' + doy + 'T' + timestr[0:2] + ':... | fcaf101e1253beb02480f3c5db63355981674374 | 648,539 |
import click
def validate_page_size(ctx, param, value):
"""Ensure that a valid value for page size is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter("Page size must be non-zero or unset.", param=param)
return value | e0618c5c1b880f47bd719072d18123199aa447c2 | 648,540 |
def residual(coord_vec, vec_map, point_coords, from_point, to_point, from_to_delta):
"""Callback for scipy.optimize.leastsq() to place points
"""
# Write the iterated coordinates back into the DataFrame
num_points = len(coord_vec) / 2
point_coords.loc[vec_map,'ew'] = coord_vec[num_points:]... | 2a92d98455e0c6e2056a79fadaa9cc6b0e7724f4 | 648,541 |
import multiprocessing
def numberOfProcessors():
""" return the number of Processors """
return multiprocessing.cpu_count() | 02f61e0a19fb83ad7cc865b7041dff86fa312805 | 648,542 |
def thirtyone_check_en(df, tweet_lang_col_name):
"""
Check if tweet language is English when tweet_language column is present
"""
non_en_tweets = []
for i, j in df.iterrows():
if(df[tweet_lang_col_name].iloc[i] != 'en'): # check if tweet_language is 'e... | ff47b6cc39027c3a34a9b0c91f9fc6355fcc04b4 | 648,543 |
import string
def normalize(s):
""" Normalize a string. """
if not isinstance(s, str):
s = str(s)
return string.capwords(" ".join(s.strip().split())) | 831f5f784237d1a5bf2db852d3292a101f631e1a | 648,544 |
def get_detname(det_id):
"""Return NRC[A-B][1-5] for valid detector/SCA IDs"""
det_dict = {481:'A1', 482:'A2', 483:'A3', 484:'A4', 485:'A5',
486:'B1', 487:'B2', 488:'B3', 489:'B4', 490:'B5'}
scaids = det_dict.keys()
detids = det_dict.values()
detnames = ['NRC' + idval for idval in d... | 1180da0fd65c96ef698142f6e88091488c8c27e5 | 648,545 |
import time
def log(msg):
"""Print string s and current time."""
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
return f"{current_time} | {msg}" | 1e0119a8e82f4f6db81dcda6b690c133c4d89234 | 648,546 |
import re
def extract_keywords(value):
""" Extract all keywords from the string.
"""
keywords = [k.strip() for k in str(value or '').replace(
'[inline]', '').split('.') if k.strip() != '']
keywords = [re.sub(r' ([0-9]+)\[pp\]$', ' \\1 Per Player', k, re.I)
for k in keyw... | cdb5dca862816e9ef2b8369aa674d3a0e1dc49b9 | 648,547 |
def scalar(p1, p2):
"""Scalar product between p1 and p2"""
return p1.x*p2.x + p1.y*p2.y + p1.z*p2.z | bc9437ac2d1a10f901170a8fa6984f52f99e983e | 648,548 |
import re
def partial_format(target, **kwargs):
"""Formats a string without requiring all values to be present.
This function allows substitutions to be gradually made in several steps
rather than all at once. Similar to string.Template.safe_substitute.
"""
output = target[:]
for tag, var in re.findall... | 8d3bb177f967b386e19058c8bca219772ca35260 | 648,549 |
def get_ins_mapping(ins_list, attr, deep=False):
"""
Create a dict map of the specified object list with the specified attribute
:param ins_list:
:param attr:
:param deep:
:return:
"""
map_dict = {}
if deep is True:
keys = attr.split('.')
for item in ins_list:
... | 9e9a03ddc5af90f800acbdc0db5d59a253a9f046 | 648,550 |
def human_list(l):
"""
Formats a list of strings in a human-friendly way.
"""
l = ["'{0}'".format(x) for x in l]
if len(l) == 0:
return 'nothing'
elif len(l) == 1:
return l[0]
elif len(l) == 2:
return ' and '.join(l)
else:
return ', '.join(l[:-1]) + ' and... | c8985459cbbd080b2471f34883d04454c6f93adf | 648,551 |
import requests
def get_saved_peripherals(api_url, protocol):
"""
To be used at bootstrap, to check for existing peripherals, just to make sure we delete old and only insert new
peripherals, that have been modified during the NuvlaBox shutdown
:param api_url: url of the agent api for peripherals
... | d1651a25cba1dae2dc87c1cf3405440bbdde7308 | 648,553 |
import random
import string
def random_string(len):
"""generate n-length random string
Args:
len (int): length of string
"""
return "".join(random.choices(string.ascii_letters + string.digits, k=len)) | a64ba34ee5d635045f4e2ea7801afcf7080d9203 | 648,554 |
import warnings
import inspect
def _get_members(*args, **kwargs):
"""
Same as :func:`inspect.getmembers` except that it will silence warnings,
which avoids triggering deprecation warnings just because we are scanning a
class
"""
with warnings.catch_warnings():
warnings.simplefilter(act... | ab272c18f9d689e97da0d95722eeab11d678efea | 648,555 |
import math
def test3(x, sin=math.sin):
"""
>>> %timeit test3(123_456)
105 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
"""
res = 1
for _ in range(1000):
res += sin(x)
return res | 43f36f9b2e0d261c47414fdae4300b260973c400 | 648,556 |
import collections
def format_int_list(int_list, delim=',', range_delim='-', delim_space=False):
"""
Returns a sorted range string from a list of positive integers
(*int_list*). Contiguous ranges of integers are collapsed to min
and max values. Reverse of :func:`parse_int_list`.
Args:
int... | aa18a3608b15f35f7c34d258f16ee57e152977c6 | 648,557 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.