content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import copy
def clone(obj):
"""Clone the object
@param obj: object to be cloned
@return object cloned.
"""
return copy.copy(obj) | d0b2ac2fed8e26a42f72da7e154d3f8a021e4709 | 630,010 |
def quaternionMsgToTuple(msg):
"""Helper function for converting a quaternion msg to a tuple"""
return (msg.x, msg.y, msg.z, msg.w) | a80c72ea4beea3a58be15f101a56c8b5e6248eb6 | 630,012 |
def _do_magick_convert_enlighten_border(width, height):
"""
Build the command line arguments to enlighten the border in four regions.
:param int width: The width of the image.
:param int height: The height of the image.
:return: Command line arguments for imagemagicks’ `convert`.
:rtype: list
... | 314fefe6c78fa865d82d2f7ec33709ad2b41fe52 | 630,013 |
def subtraction(left, right):
"""Subtraction of two streamlines dict (see hash_streamlines)"""
return {k: v for k, v in left.items() if k not in right} | 3f693db824d01da7981c2e4fe6bf09db7d92e332 | 630,014 |
import subprocess
def get_git_username() -> str:
"""
获取git username
:return: git username
"""
# 优先取本地配置
resource_cmd_list = [["git", "config", "user.name"], ["git", "config", "--global", "user.name"]]
for resource_cmd in resource_cmd_list:
process = subprocess.Popen(resource_cmd, ... | b3cdbe4b7fb225d1f80fe414316f315433f7dc23 | 630,015 |
from typing import Union
def any_to_int(any: Union[None, str]) -> int:
"""
Convert int string to integer. if this value is `None`, return `0`
Args:
any (Union[None, str]): value to convert
Returns:
int: converted integer
"""
if any is None:
return 0
return int(any) | 64ee3bd2efd610132d1a44c9bf7caa531b0869e3 | 630,016 |
def args_dict_split(all_arguments):
"""
This functions split the super set of arguments to smaller dictionaries
all_arguments: Dictionary
All input arguments parsed
return: Dictionary, Dictionary, Dictionary
We return four dictionaries for init, script, spark arguments, singlenode arguments
... | 109b328f3f3495952fc820a53b76f0a915acfbf8 | 630,018 |
def fake_urldelete(c_client, url, headers):
"""
A stub delete_status() implementation that returns True
"""
return True | 8c2a24b618ea1be5376a0fd2af3659ab4b1054f5 | 630,019 |
def fn1Test(string, outputFile):
"""
Function appends the next character after the last character in the given
string to the string, writes the string to a file, and returns it. For
example, if string is "AB", we will write and return "ABC".
"""
rV = string + chr(ord(string[-1]) + 1)
with o... | 5f292d3383e9efb1a38f20cf8a5ac9dd71cd914a | 630,020 |
def platform_parameters(parser):
""" imx6ull platform parameters """
parser.add_argument("--ext_tools", type=str, default="", help="")
parser.add_argument("--tflite", type=str, default="./platforms/plugin_imx6ull/TensorflowLiteMicro",
help="tensorflow lite micro dir")
parser.add_... | 7d61b2718423017f58b0ff48358e202de7884a5e | 630,021 |
def _get_attention_sizes(resnet_size):
"""The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
"""
choices = {
18: [False, [False, True], [True, False], False],... | 8d3f3faf19883b36b7b1fc2535f688132acec5f7 | 630,022 |
def load_sum(sum_file):
"""
*.sum file is the catalog summary file after Hyperinverse.
This function returns a dict:
-key is event id
-value is an array with below component:
--Str format event time "yyyymmddhhmmss**", also the event folder.
--event longitude
... | e7488c70f9eab35f52b4884c365497c529ca500e | 630,024 |
def echo(**kwargs):
"""Can take any keyword argument and prints its name and value"""
for k, v in kwargs.items():
print('**', k, '=', v)
return kwargs | 74a417cddfbd1962f52a6503715688bf3c20874a | 630,025 |
from datetime import datetime
def parse_datetime(s, fmt='%Y%m%d%H%M%S'):
"""
>>> parse_datetime('20170403153428')
datetime.datetime(2017, 4, 3, 15, 34, 28)
>>> parse_datetime('2017-04-03T15:34:28', fmt='%Y-%m-%dT%H:%M:%S')
datetime.datetime(2017, 4, 3, 15, 34, 28)
"""
return datetime.strp... | cfbd9303e25554cd24897162b2c87b9a957c3a44 | 630,026 |
def to_md(journal):
"""Returns a markdown representation of the Journal"""
out = []
year, month = -1, -1
for e in journal.entries:
if not e.date.year == year:
year = e.date.year
out.append(str(year))
out.append("=" * len(str(year)) + "\n")
if not e.dat... | c265a603a6fc3c364abceaabcf9001a2a0253066 | 630,027 |
def _str_to_bool(string):
"""
Converts command line boolean string to python boolean
:param string: The command line string
:return: The boolean interpretation of the string
"""
return string.lower() in ("yes", "true", "t", "1") | 5428bd1bf1b05ccec6613ecf382bac3399009cec | 630,028 |
import six
def generic_request_func(self, path, method, body=None, **kwargs):
"""
This method allows for generic requests to be made against the Demisto server to endpoints that
may not be exposed directly.
:param path: str - Path of the endpoint.
:param method: str - Type of API method to use.
... | 9f76e3e02d97eedf3961d6693798c9de0d62d278 | 630,029 |
def go_environment_vars(ctx):
"""Return a map of environment variables for use with actions, based on
the arguments. Uses the ctx.fragments.cpp.cpu attribute, if present,
and picks a default of target_os="linux" and target_arch="amd64"
otherwise.
Args:
The skylark Context.
Returns:
A dict of envir... | fd22dfa05d3601143193835c7f1ea26ff9aac8b2 | 630,030 |
import re
def _triple_under_to_dots(astring):
"""Convert all instances of '___' to '.'."""
return re.sub(r'___', '.', astring) | 4601813747dd9d06401e28ffd6c5703a86c0d74a | 630,031 |
def generate_codex(lexicon, inverse_codex=False):
"""
Given a list of words, creates a codex of unique numeric keys assigned to the words.
Example:
input: ['boy', 'apple', 'dog', 'cat']
output: {'apple': 0, 'boy': 1, 'cat': 2, 'dog': 3}
Input:
lexicon: (list) List of strings, c... | 3d7cd7eb67d85ee1536f2daa45481224287e7386 | 630,032 |
import numpy
def companion_matrix(p):
"""Assemble the companion matrix associated with a polynomial
whose coefficients are given by `poly`, in order of decreasing
degree.
Currently unused, but might find a role in a custom polynomial
root-finder.
References:
1) http://en.wikipedi... | b4104bcae014cafe2b794d94ecc447986961a6e5 | 630,033 |
def getParamCombinations(data_joined):
"""
Generates a list containing all identified parameter combinations within the dataset
"""
# Identify parameter combinations
para_combs = []
for i in data_joined.index:
kappa = data_joined.loc[i, 'kappa']
sigRamp = data_joined.loc[i, 'sig... | 5a4e6d22cf375c78ad78595bc46afb56ac48feda | 630,034 |
import math
def LinEx(y: int, est: int):
"""
A function that return the error for a given estimation of the number of calls
:param y: truth
:param est: estimation (ŷ in the folowing formula)
:return: LinEx(y, ŷ) = exp[α(y − ŷ)] − α(y − ŷ) − 1
"""
alpha = 0.1
prod = alpha * (y - est)
... | 469c23fd3d732ff7cba9778afef137492b10ea65 | 630,035 |
import copy
import random
def nx_color_spread(init_pt, graph,maxtsteps):
""" Function to perform the random simulation of spreading the GHZ state on
a weighted graph
Parameters
----------
init_pt, any type:
Label for the initial point we are spreading from. Should be present in
th... | 7602912060402feca5ff69bbd56f685a6c5dc1fd | 630,036 |
import torch
def knn_withdis(x, k):
"""
:param x: (B,3,N)
:param k: int
:return: (B,N,k_hat)
"""
inner = -2 * torch.matmul(x.transpose(2, 1), x)
xx = torch.sum(x ** 2, dim = 1, keepdim = True)
pairwise_distance = -xx - inner - xx.transpose(2, 1)
idx = pairwise_distance.topk(k = k,... | 0235e635fde6d7f2599811e80cb32faed46cfc1d | 630,037 |
def AZ2pdg(A, Z):
"""Conversion of nucleus with mass A and chage Z
to PDG nuclear code"""
# 10LZZZAAAI
pdg_id = 1000000000
pdg_id += 10*A
pdg_id += 10000*Z
return pdg_id | 3dfd4dc46d57d92ed18fb7911b1679e80b557fb2 | 630,038 |
import argparse
import os
def handle_args():
""" Parse cli arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--image_dir',
type=str,
default=os.getcwd(),
help='where the image directory is'
)
parser.add_argument(
'--image',
t... | 8394b7e349c341c31aba211400a3187d396b29d8 | 630,039 |
import re
def normalize(data):
""" Eats text. Replaces special characters by convertign them to normal
characters, spaces or nothing. Returns text. """
# Special characters to be replaced when normalizing the text:
replacement_table = {
'[àáâ]': 'a',
'[èéêë]': 'e',
'[ìíîï]... | dc9565e8d0e875dd873500280f0768e1590f9d62 | 630,040 |
import os
import sys
def setup_run(status):
"""
This function sets up where the predictions are loaded in from and where polygonization,
smoothing, and rasterizing are saved to. Set up to work only with GeoTIFFs.
"""
# File path to the predictions.
main_path = "/file/path/to/predictions/"
... | 2b107e442808e239551d21eccebaef5f802b6e71 | 630,041 |
import os
def datapackage_exists(repo):
"""
Check if the datapackage exists...
"""
datapath = os.path.join(repo.rootdir, "datapackage.json")
return os.path.exists(datapath) | b02d06c7cd9f2da02dd8eecb85352eb5ea36c2c3 | 630,042 |
from typing import OrderedDict
def dequantize_model_weights(quantized_weights):
"""De-quantize quantized weights."""
dequantized_weights = OrderedDict()
for name, quantized_weight in quantized_weights.items():
dequantized_weight = quantized_weight.scale * (
quantized_weight.tensor.floa... | 5cffe2b89f459f21d3ee273d7ffa335a37d1b016 | 630,044 |
def extract_section_by_name(path, section_name):
"""
:param path:
:type path: list
:param section_name:
:type section_name: str
:return:
:rtype: list|None
"""
section = section_name.split(" ")
predicate = lambda x, section: section == x[:len(section)]
try:
return ... | 639668e1ae0f7f3d92c6506218225d08f16a5e34 | 630,045 |
import torch
def farthest_point_sample(x, npoint):
"""
Input:
xyz: pointcloud data, [B, N, C]
npoint: number of samples
Return:
centroids: sampled pointcloud data, [B, npoint, C]
"""
B, N, C = x.shape
S = npoint
y = torch.zeros(B, S, C).cuda()
distance = torch.o... | 6d79458253d0242e87b11ddf3f172269af2a71f5 | 630,046 |
def build_grid_from_file(file):
"""
According a text file used as map generating a grid for a level
:param file:
:return: grid . Type 2 dimension Array
"""
grid = []
with open(file, "r") as f:
for line in f:
row = []
for c in line[:-1]:
row.app... | d9eb7bc7c8c6a90def927888fee3b2d041bd7032 | 630,047 |
def get_quote_style(str):
"""find which quote is the outer one, ' or "."""
quote_char = None
at = None
found = str.find("'")
found2 = str.find('"')
# If found == found2, both must be -1, so nothing was found.
if found != found2:
# If a quote was found
if found >= 0 and found2 >= 0:
# If bo... | f216d7cdf038137234249fd89e5c5794c373193b | 630,048 |
import inspect
def _get_frame_args(frame):
"""Get the formatted arguments and class (if available) for a frame"""
arginfo = inspect.getargvalues(frame)
try:
if not arginfo.args:
return '', None
# There have been reports from the field of python 2.6 which doesn't
# return a na... | 268631995c8c0b48b74728ed5fba7951b91b1f8c | 630,049 |
def personalGreeting(username):
"""
function: personalGreeting
Write a personalGreeting function which, after asking for the user’s name, outputs a
personalised greeting. E.g., for user input Sam, the function should output the
greeting Hello Sam, nice to see you! (note the details of the spaces a... | 2f4b08e275335cf19fd704df987907e168e0baa2 | 630,050 |
def attribute(key, value):
"""
Makes an attribute for lxml.
"key"="value"
:param str key: key of the attribute
:param str value: value of the attribute
:return dict attr: attribute for lxml
"""
attr = {key: value}
return attr | 1134c1e8e13b1cea554cd9d4c3d459eb582fa6aa | 630,051 |
def constantstress(x, ystress=0.1):
"""Constant stress model
Note:
.. math::
\sigma=\sigma_y
Args:
Returns:
stress : Shear Stress, [Pa]
"""
return ystress | e536c79dc1d544e2ed0fbb7b8e98511fa84a3f50 | 630,052 |
from textwrap import dedent
def map_strings_to_line_numbers(module):
"""
Walk ``module.ast``, looking at all string literals. Return a map from
string literals to line numbers (1-index).
:rtype:
``dict`` from ``str`` to (``int``, ``str``)
"""
d = {}
for field in module.block.string... | 29733d59f48ff92b893cb9bcc2826addba0b06e9 | 630,053 |
def _match_authorizables(base_authorizables, authorizables):
"""
Method to check if authorizables (entity in CDAP) is contained (the children) of base_authorizables
If so, base_authorizables should be exactly the same as the leading part of authorizables
:return: bool: True if match else False
"""
return au... | 3af027793c3e39600f74a97216a3566b69ff6213 | 630,054 |
import queue
import threading
def multithreading_reader(readers, queue_size=1000):
"""
multithreading_reader use python multi thread to read data from readers
and then use queue to merge all
data. The process number is equal to the number of input readers, each
process call one reader.
CPU usa... | 46e15e62e68dd5dd97fd6f50558ddcea299312b2 | 630,055 |
import os
def get_file(dirct, contains=[""]):
""" Given a directory, this function finds a file that contains each
string in an array of strings. It returns the string
:param dirct: The directory to be searched in.
:param contains: An array of strings, all of which must be contained in
... | b737100db1fea7dde2de7e8e1cba000e70052e61 | 630,056 |
import sys
import select
def kbhit():
"""Wait till next key struck, or a burst of paste pasted"""
rlist = [sys.stdin]
wlist = list()
xlist = list()
timeout = 0
selected = select.select(rlist, wlist, xlist, timeout)
(rlist_, _, _) = selected
if rlist_ == rlist:
return True | 815c522e01f495d95fb8039cfa5b8fa8d1620222 | 630,057 |
def step_constant(step):
"""Use this function when you want the step to remain fixed in every iteration (typically good for
instances when you know approximately how long the function should poll for)"""
return step | 21ca043a234e67d7dc9e37319f5c547032fe9673 | 630,058 |
def processor(document: dict) -> dict:
"""
The default document processor for job documents. Transforms projected job documents to a structure that can be
dispatches to clients.
1. Removes the ``status`` and ``args`` fields from the job document.
2. Adds a ``username`` field.
3. Adds a ``create... | 5471be9ed0ae4d5fd20d0172b7d0411ff5337f88 | 630,059 |
def make_from_namedtuple(t, **kwargs):
"""
t是namedtuple,复制一份t,但其中部分字段更新为kwargs的值
:param t:
:param kwargs:
:return:
"""
d = t._asdict()
d.update(kwargs)
cls = type(t)
return cls(**d) | 4a4247eb01967ad430c30245b1379953f754dc25 | 630,060 |
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['cache'] = 86400
desc['description'] = """This plot presents a histogram of the change
in temperature over a given number of hours."""
desc['arguments'] = [
dict(type='zstation', name='zst... | fcba0edd5185078ad161cffa8d97bcea16d3076b | 630,061 |
def is_solvable_seed(seed):
"""Returns True if the given seed would generate a solvable pirellone instance, False otherwise."""
# We reserve those seed divisible by 3 to the NOT solvable instances
return (seed % 3) != 0 | 8ea7a6e7f0b859a09217bba1fc71bbd40f38b391 | 630,062 |
import subprocess
def are_untracked_files() -> bool:
""" Check if there are any untracked files
Returns
-------
Bool indicating if there are any untracked files. False means no files.
"""
untracked = subprocess.check_output(['git', 'ls-files', '--others', '--exclude-standard']).decode('utf-8'... | 13b18d7857c288024c340f44c5796e08e30be873 | 630,063 |
def clean_string(string: str) -> str:
"""
Removes control characters from a string.
>>> clean_string('This is a sentence\\r with newline.')
'This is a sentence with newline'
>>> clean_string('')
''
>>> clean_string(' This is a sentence\\r with. newline. ')
'This is a sentence with. n... | 55d6be1d4b3c47ca38a6dcbd300c755f8c7090c1 | 630,065 |
from pandas import DataFrame
import re
def meta_from_txt(target):
"""Parses target text file containing Texas PUDF metadata and builds a pandas DataFrame object.
"""
pattern = '(?P<field_number>\d+\w?)\s+(?P<field>\S+)\s+(?:(?P<label>.*?)\s*)(?P<position>\d+)\s+(?P<width>\d+)\s+(?P<data_type>\w+)'
jo... | 2227c75905b106f22ea2f7a0ae75be9fe4b90309 | 630,066 |
def return_string_vcu():
""" This function should return a string with the lowercase value of vcu"""
return_value = "vcu"
return return_value | 3a85a321e804b028b42fdc21732ed90a83100699 | 630,067 |
def updateModuleHealth(error):
"""(Integration only)
Updated integration module health with given error message
:type error: ``str``
:param error: The error message to display in the integration module health
:return: No data returned
:rtype: ``None``
"""
return "" | d3abde9ea5b02ad66618f55e2355df1ee150d81a | 630,069 |
import sqlite3
def fetch_naming_prefix(database):
""" Get naming prefix from the database run_info table """
conn = sqlite3.connect(database)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT value FROM run_info WHERE item = 'idprefix'")
prefix = cursor.fetchone()[0]... | 5a61bc6863c42b88abafc5211c1b51970ae8d44f | 630,070 |
def call_sig(args, kwargs):
"""Generates a function-like signature of function called with certain parameters.
Args:
args: *args
kwargs: **kwargs
Returns:
A string that contains parameters in parentheses like the call to it.
"""
arglist = [repr(x) for x in args]
arglist... | a66af732966f5bfc613d105076363424891aaa90 | 630,071 |
def upload_files(files):
"""Build up uploaded or updated files' structure"""
_upload_files = {}
for obj in files:
content = obj.readlines()
if not content:
continue
_upload_files[obj.name.split('/')[-1]] = {'content' : \
''.join(content)}
obj.close... | b25e92056e9b1d4a3a017b297deb1a8575ad5443 | 630,072 |
import cmath
def is_integral(x):
"""Return whether the argument is equal to its integer part."""
if isinstance(x, complex):
if x.imag:
return False
x = x.real
return not cmath.isinf(x) and not cmath.isnan(x) and x == int(x) | 33cb18f84b9778c56e7df1b601458f2404f9075a | 630,073 |
import torch
def gpu_memory():
"""return the maximum allocated GPU memory
Returns
-------
allocated GPU memory in bytes.
"""
memory = torch.cuda.max_memory_allocated()
return memory | f9ece2387e4844c63bfe46158dfcc9c55d61fca6 | 630,074 |
def parse_claim(claim):
"""
Parse a line of input
Example claim:
#1 @ 861,330: 20x10
"""
tokens = claim.split(" ")
claim_id = int(tokens[0][1:])
(offset_x, offset_y) = tokens[2].split(',')
offset_x = int(offset_x)
offset_y = int(offset_y[:-1])
(width, height) = tokens[3].sp... | d534e204f88841b0dfd34c0501cb2dfb545c4fd4 | 630,075 |
import subprocess
def get_repo(top):
"""
Get python scripts from repository
"""
# rc = subprocess.call(["git", "clone", "https://github.com/Iwan-Zotow/runEGS.git"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
rc = subprocess.call(["svn", "checkout", "https://192.168.1.230/svn/XCSW/MC_simulatio... | 98d1c7a9710e9f053359200072a73053ec225085 | 630,076 |
def maskedgenerator(generatorfunction):
"""Decorator that adds outputs masking to a generator.
A "mask" parameter is added to the generator function, which expects
a list of boolean variables. The mask is iterated in parallel to the
generator, blocking from the output those items with a False value... | efc66cc56ca696bb325c58bfb233c88cc9e48753 | 630,077 |
import ast
def matches_attr(node, name):
"""Determines if the ``ast.Call`` node points to an ``ast.Attribute`` node with a matching name.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
name ... | fe76ee845fabc965ba15475c2a6c4098cbeae221 | 630,078 |
def config_is_runnable(config):
"""Is this logger configuration runnable? (Or, e.g. does it just have
a name and no readers/transforms/writers?)
"""
if not config:
return False
return 'readers' in config or 'writers' in config | 081563080d7b860866b3e0871258470c9ed58bd7 | 630,079 |
def delete_comma(value):
""" Returns a string without its final comma."""
items = value.split(',')
last = items.pop()
return '%s%s' % (','.join(items), last) | 2ddd68851d8cae7883e1ef3802ae07ad08fcfaaf | 630,080 |
def concat_list(in_list1=None, in_list2=None):
"""
Parameters
----------
in_list1 : list or str
file path or a list of file paths
in_list2 : list or str
file path or a list of file paths
Returns
-------
out_list : list
a list of file paths
"""
if in_lis... | d6e67bc5f906b81029230fb030ea7b8ce7fe7759 | 630,081 |
def _args(param):
"""Return a string with all the inputs property formatted. """
if not param:
return ''
return '%s, ' % ', '.join([par['name'][1:-1] for par in param]) | d59cd86f87dae7a2fe6489adacd1031c96e5232d | 630,083 |
import string
def is_string_printable(string_):
"""Check if a string is printable"""
return set(string_) - set(string.printable) | cd244c331fd366f352f7289cc063ab255a7c4cc5 | 630,084 |
def lifetime(mass1: float):
"""
Stellar lifetime function of Maeder & Maynet (1989) extrapolated by Chiappini, Matteucci & Gratton (1997).
See also Tornatore (2007) for use case in stellar chemical enrichment.
-----
tau: stellar age (one star) [Gyr]
mass: stellar mass (one star) [Msun]
"""
... | 77af14c42d1ea7c3837804c294fd616deb070204 | 630,085 |
def _case_insensitive_attr(node, lowercase_attr):
"""Find attribute name regardless of case"""
lowercase_attr = lowercase_attr.lower()
for attr in node.attrib:
if attr.lower() == lowercase_attr:
return attr | da8f60219dc826e32721f31dcdde3fdbbd3d6d65 | 630,086 |
import pprint
def _get_column_index(i, inputs):
"""
Taken from https://github.com/onnx/sklearn-onnx/blob/9939c089a467676f4ffe9f3cb91098c4841f89d8/skl2onnx/common/utils.py#L50.
Returns a tuples (variable index, column index in that variable).
The function has two different behaviours, one when *i* (col... | 016cdcee266f36dcaad6a96788d3899348f4155c | 630,088 |
def access_token_invalid_():
"""
An invalid access token.
"""
return "XXX" | 16d7ede7f653eabc55af98397f63748b3fca6ad5 | 630,089 |
import networkx
def walls_to_graph(walls):
"""Return a networkx Graph object given the walls of a maze.
Parameters
----------
walls : list[(x0,y0), (x1,y1), ...]
a list of wall coordinates
Returns
-------
graph : networkx.Graph
a networkx Graph representing the free squ... | eccfd3d9ca582ee4eafe9cb385c252277b52c3b7 | 630,090 |
def disabling_button(n_clicks):
"""
Disabling the button after its being clicked once
"""
if n_clicks >= 1:
return {'display':"none"} | 5c1482a566b1ca077de5592289fad0acb50dae16 | 630,091 |
def is_palindrome(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.
>>> all(is_palindrome(key) is value for key, value in test_data.items())
True
"""
end_i = len(s) - 1
for start_i in range(end_i):
if s[start_i] != s[end_i]:
return False
... | cc6f9e60fac8907e6b6cc7bd59d7c99940656da8 | 630,092 |
def dict2xml(dictionary, root="topsApp", topcomp="topsinsar"):
"""Convert simple dictionary to XML for ISCE."""
def add_property(property, value):
xml = f" <property name='{property}'>{value}</property>\n"
return xml
def add_component(name, properties):
xml = f" <componen... | 76c3cbd64e1118da0391be40448a42990a83cf15 | 630,093 |
def piggy_points(score):
"""Return the points scored from rolling 0 dice.
score: The opponent's current score.
"""
scoreSq = score ** 2
smallestDigit = -1
while scoreSq > 0:
currentDigit = scoreSq % 10
scoreSq = scoreSq // 10
if currentDigit < smallestDigit or smallestD... | c9e51513899bb717ee37f10bf9533b1759c4671e | 630,094 |
def build_args_stdio(settings):
"""Build arguments for calling pylint.
:param settings: client settings
:type settings: dict
:return: arguments to path to pylint
:rtype: list
"""
pylint_args = settings.get('args')
if pylint_args is None:
return []
return pylint_args | 0a1c7fd036220a8cc2c03091f21d742bd3758d77 | 630,095 |
import os
def get_directories(root):
"""
gets a list of all directories in given root directory.
it only returns directories in the root path.
:param str root: root path.
:rtype: list[str]
"""
folders = []
for root, directories, file_names in os.walk(root):
for item in dire... | c34ce077df39410944e2f6a397846bb7b56273b9 | 630,096 |
def _list_to_index_dict(lst):
"""Create dictionary mapping list items to their indices in the list."""
return {item: n for n, item in enumerate(lst)} | 38d8b9a963ebdd40b8f14b3052937e3450853fab | 630,097 |
def CheckNoPragmaOnce(input_api, output_api,
source_file_filter):
"""Make sure that banned functions are not used."""
files = []
pattern = input_api.re.compile(r'^#pragma\s+once',
input_api.re.MULTILINE)
file_filter = lambda x: (input_api.FilterSourceFile(x... | d19cb2b408f5fb72c686ca7928e5bb182994505d | 630,098 |
import random
import string
def random_id(length=5):
"""Generate a random ID of 5 characters to append to qsub job name."""
return ''.join(random.sample(string.ascii_letters + string.digits, length)) | c69c5f50e8a913b67eed1f9449b992f87f976552 | 630,099 |
import json
def intrinsics(kinect, path='calibrate/IR/intrinsics_retrieved_from_kinect_mapper.json', write=False):
"""
Retrieve the depth camera intrinsics from the kinect's mapper
and write them at: calibrate/IR/intrinsics_retrieved_from_kinect_mapper.json
:param kinect: kinect instance
:param pa... | 811b4128090a7015d297a0bd85432ad321369e99 | 630,100 |
import requests
def connection_ok(base_url):
"""Check whetcher connection is ok
Post a request to server, if connection ok, server will return http response 'ok'
Args:
none
Returns:
if connection ok, return True
if connection not ok, return False
Raises:
none
... | b4d6bdfe2ec8d511238a65ef359abfbed0b5f86a | 630,101 |
def update(mean1, var1, mean2, var2):
"""
新的均值和方差 更新
:param mean1:
:param var1:
:param mean2:
:param var2:
:return:
"""
new_mean = (mean1 * var2 + mean2 * var1) / (var1 + var2)
new_var = 1 / (1 / var1 + 1 / var2)
return [new_mean, new_var] | eb929b2addaed27774cadea07a425eac890b22c4 | 630,103 |
def find_deep(neighs_info):
"""Find deep from a raw structure.
Parameters
----------
neighs_info: tuple
the neighbourhood information.
Returns
-------
deep: int
the level in which the information is provided.
"""
if '__len__' not in dir(neighs_info):
deep =... | 4cb8f62747bd86c7444bd45b4d1562dc58c49cb6 | 630,104 |
def _pick_mimetype(env):
"""Detect the http indicated mime to send back.
Note that as it gets into the ACCEPT header honoring, it only looks for
application/json and else gives up and assumes html. This is because
browsers are very chaotic about ACCEPT HEADER. It is assumed that
XMLHttpRequest.se... | a5fff76f167bac1742f4b6b56e35c53386b4ffa8 | 630,105 |
def _display_time(seconds: float, granularity=2) -> str:
"""Return a human readable instruction for some time duration.
Copy and pasted from:
https://stackoverflow.com/questions/4048651/python-function-to-convert-seconds-into-minutes-hours-and-days/4048773
If the number is positive, it returns the tim... | 98ea02ab39ca4394ca15a3e622e0e6df21ccd594 | 630,106 |
import random
import copy
def partition(n,m,minQuota,maxQuota):
"""
Function to partion a particular integer.
Parameters:
n (int) - the number we want to partition.
m (int) - the number of blocks we want.
minQuota (int) - the minimum size of a block.
maxQuota (int) - the m... | 73587a6c4544be9c282d94027c18299bcf29adfc | 630,107 |
def PPV_OR(odd_ratio, power, alpha, verbose=True):
"""
returns PPV from odd_ratio, power and alpha
parameters:
-----------
odd_ratio: float
P(H_A)/(1-P(H_A))
power: float
Power for this study
alpha: float
type I risk of error
Returns:
----------
... | 50f0a18a5b45d7e4d7621fb1ea0c61c7a74cc55d | 630,108 |
def split_by_link(data):
"""
splits PTCF information by link ids (e.g. "ds1_1-ds2_1") to store the data under a given key for easier access (-> focus-on-hover!)
:param data: ptcf data frame
:return: PTCF split by link
"""
split_data = {}
data['cluster_id'] = data['ds1_cluster'] + "-" + data['ds2... | 1d16658057900702c9d367dec2ec11826a217177 | 630,109 |
def extractStationsFromFile(stations_file):
"""
Reads file and extracts stations to a list.
"""
df = open(stations_file)
station_ids = df.read().split()
df.close()
return station_ids | 2d38092fa4afaf91f0de4fd9a5b3e3cbfc65c98b | 630,110 |
import copy
def change_defaults(defaults,key,value):
""" Change a defaults dictionary's key 'key'
to have a default value 'value'. """
defaults = copy.deepcopy(defaults)
if isinstance(defaults,tuple):
defaults=list(defaults)
for i,default in enumerate(defaults):
if def... | 3c8b4266e3e77ede6317fd1a974fa96ed358d1c4 | 630,111 |
def create_violin_plot(df, columns, title):
"""
This method will create violin plots given a DataFrame and columns.
Args:
df (pandas.DataFrame): data that will be displayed
columns (list): list of columns
title (str): violin plot title
Returns:
... | fbe4008b811aa126143f0175da034af5c592e005 | 630,112 |
from typing import MutableMapping
def collect_media_urls(data, media_urls):
"""
Recursively collects media urls from all keys of a tweet.
"""
for val in data.values():
if isinstance(val, MutableMapping):
_media_urls = collect_media_urls(val, media_urls)
elif isinstance(val,... | 4fd7ab14a04bfa7a767a651350284d7c20442988 | 630,113 |
import requests
from typing import Counter
def suggest_stations(text, threshold=0.5, min_n=3, max_n=10, s_coef=1e-3, l_coef=1e-3, len_coef=-1e-5):
""" Получение списка станций по префиксу названия.
Ответ - список станций в формате [({'n': name, 'c': code, ...}, score), ...],
где name - название станции,... | 9b857da7f7c0083c67b004f090607967c53abcc1 | 630,114 |
def randUniqueInt(self, r, N, vmin, vmax):
"""
Function for/to <short description of `netpyne.network.conn.randUniqueInt`>
Parameters
----------
self : <type>
<Short description of self>
**Default:** *required*
r : <type>
<Short description of r>
**Default:** *r... | d7370907172b79ada68831f52bd29537ae5cc172 | 630,115 |
def location_check(csv_name):
"""
Function creates path for giving csv file (based on csv file name)
:param csv_name: csv file name
:return: path where to save giving file
"""
csv_name = str(csv_name)
tournament_type = csv_name[-13:-11]
tournament_gender = csv_name[-7]
team_individu... | 3815ed24bb6315df87db9cb0d13ed04adf514940 | 630,116 |
def safe_ord(character):
"""
Ethereum RLP Utils:
Returns an integer representing the Unicode code point of the character or int if int argument is passed
:param character: character or integer
:return: integer representing the Unicode code point of the character or int if int argument is passed
... | 1a5a1f1c1a758fe3211dbe94caaa70bda9df2534 | 630,117 |
import typing
import importlib
def get_metrics_postprocessor_fn(module_fn_name: typing.Optional[str]):
"""Load and validate the metricsd post processing function"""
if not module_fn_name:
return None
module, sep, fn_name = module_fn_name.rpartition(".")
assert all(
(module, sep, fn_nam... | bf979e5e0c47c841642b6001c6b4df7d69494d5f | 630,119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.