content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import sys
import subprocess
def _input_password() -> str:
"""
Get password input by masking characters.
Similar to getpass() but works with cygwin.
"""
sys.stdout.write("Password :\n")
sys.stdout.flush()
subprocess.check_call(["stty", "-echo"])
password = input()
subprocess.check_... | 8d3dbc3f6221f3a2558dab5617227b2f6e4940ca | 1,626 |
def solution2(arr):
"""improved solution1 #TLE """
if len(arr) == 1:
return arr[0]
max_sum = float('-inf')
l = len(arr)
for i in range(l):
local_sum = arr[i]
local_min = arr[i]
max_sum = max(max_sum, local_sum)
for j in range(i + 1, l):
local_sum... | 835240bb4f70e5b6425a6ac0d2a4210e2c8a0ad0 | 1,628 |
import os
def df_to_hdf5(df, key, dir_path):
"""
Save the DataFrame object as an HDF5 file. The file is stored
in the directory specified and uses the key for the filename
and 'h5' as the extension.
:param df: DataFrame to save as a file
:param key: ID for storage and retrieval
:param dir_... | aaf7e2d9f64da6f53b2fc908cc59d9331172c614 | 1,629 |
def _get_connection_params(resource):
"""Extract connection and params from `resource`."""
args = resource.split(";")
if len(args) > 1:
return args[0], args[1:]
else:
return args[0], [] | 87cdb607027774d58d1c3bf97ac164c48c32395c | 1,630 |
import subprocess
def download_archive(url, out_path):
"""Downloads a file from the specified URL to the specified path on disk."""
return subprocess.call(['curl', url, '-o', out_path]) | e3c59f542a8fa662169d74428ed98dbf79d3d705 | 1,631 |
def import_class(class_object):
"""
Import a class given a string with its name in the format module.module.classname
"""
d = class_object.rfind(".")
class_name = class_object[d + 1:len(class_object)]
m = __import__(class_object[0:d], globals(), locals(), [class_name])
return getattr(m, clas... | 82df3ed7d646bd423ccefacc00493e917f13c430 | 1,633 |
def get_examples(mode='train'):
"""
dataset[0][0] examples
"""
examples = {
'train':
({'id': '0a25cb4bc1ab6f474c699884e04601e4', 'title': '', 'context': '第35集雪见缓缓张开眼睛,景天又惊又喜之际,长卿和紫萱的仙船驶至,见众人无恙,'
'也十分高兴。众人登船,用尽合力把自身的真气和水分输给她。雪见终于醒过来了,但却一脸木然,全无反应。众人向常胤求助,却发现人世界竟没有雪见的身世纪录。长卿询问清微的身世,... | 0b5fb45bcac847cd3f7e7b3e5b264e350c891211 | 1,634 |
def prepare_default_result_dict(key, done, nodes):
"""Prepares the default result `dict` using common values returned by any
operation on the DHT.
Returns:
dict: with keys `(k, d, n)` for the key, done and nodes; `n` is a list
of `dict` with keys `(i, a, x)` for id, address, and expirat... | 420beb66352fee7b4d38f6b4cf628cbaa86a03df | 1,635 |
def MatchScorer(match, mismatch):
"""Factory function that returns a score function set to match and mismatch.
match and mismatch should both be numbers. Typically, match should be
positive and mismatch should be negative.
Resulting function has signature f(x,y) -> number.
"""
def scorer(x, y... | fe3829efc64cb4d9785e52b8af6949c147481902 | 1,636 |
def _compute_paddings(height_pad_amt, width_pad_amt, patch_axes):
"""Convert the total pad amounts to the format needed by tf.pad()."""
top_pad = height_pad_amt // 2
bottom_pad = height_pad_amt - top_pad
left_pad = width_pad_amt // 2
right_pad = width_pad_amt - left_pad
paddings = [[0, 0] for _ in range(4... | 3a5154ba0fa6808bc6dc8e20fcb4203324762ba9 | 1,637 |
def get_first(somelist, function):
""" Returns the first item of somelist for which function(item) is True """
for item in somelist:
if function(item):
return item
return None | 81976910c46102d3b15803d215f3bf5a554f9beb | 1,638 |
import sys
import locale
def get_process_output(process, encoding=None):
"""Get the output from the process."""
output = process.communicate()
returncode = process.returncode
if not encoding:
try:
encoding = sys.stdout.encoding
except Exception:
encoding = loc... | 84622c05e84627d0651d21194391c672fb111b6f | 1,639 |
import itertools
def remove_duplicates(llist):
"""
Removes any and all duplicate entries in the specified list.
This function is intended to be used during dataset merging and
therefore must be able to handle list-of-lists.
:param llist: The list to prune.
:return: A list of unique elements ... | cbdf1a4db99a7a5fac37f25776cc1387ed8c54e0 | 1,640 |
def nonseq():
""" Return non sequence """
return 1 | 7c8f4a616a6761153226d961be02f6cf5b0cc54a | 1,642 |
def kubernetes_node_label_to_dict(node_label):
"""Load Kubernetes node label to Python dict."""
if node_label:
label_name, value = node_label.split("=")
return {label_name: value}
return {} | c856d4e6d1f2169f7028ce842edc881cbca4e783 | 1,643 |
import os
def get_datafiles(datadir, prefix = ""):
"""
Scan directory for all csv files
prefix: used in recursive call
"""
datafiles = []
for fname in os.listdir(datadir):
fpath = os.path.join(datadir, fname)
datafile = os.path.join(prefix, fname)
if os.path.isdir(fpa... | 9d975985a7b16af75436f8941881982f8a39d5d7 | 1,645 |
import os
def load_fonts(folder="fonts/latin"):
"""Load all fonts in the fonts directories
"""
fonts = []
if folder is not None:
if os.path.isdir(folder):
# the folder exists whether it is relative or absolute path
for font in os.listdir(folder):
if fon... | 87e15b826e99b3d350fcb4ad8e58ac968644a4d0 | 1,647 |
def smallest_subarray_with_given_sum(arr, s):
"""Find the length of the smallest subarray whose sum is >= s.
Time: O(n)
Space: O(1)
>>> smallest_subarray_with_given_sum([2, 1, 5, 2, 3, 2], 7)
2
>>> smallest_subarray_with_given_sum([2, 1, 5, 2, 8], 7)
1
>>> smallest_subarray_with_giv... | 4a1d63619fc200c32ffae80dc7d404f486efcdd1 | 1,648 |
def teraflops_for_accelerator(accel):
"""
Stores the number of TFLOPs available to a few accelerators, including driver handicaps.
Args:
accel (str): A string descriptor of which accelerator to use. Must be either "3090" or "V100".
Returns:
accel_flops (int): an integer of how many TFL... | a491beb06baf73325e2e7b5f0876e98ea312e2aa | 1,650 |
import numpy as np
import copy
def copy_ffn(model):
"""Copy feed forward network model.
Args:
model: A previously created ffn model
Returns:
A copy of the model
"""
#init model as list holding data for each layer start with input layer
newmodel = []
newmodel.append({
... | 5bde1163d5d53a75839b15aaa38a28ecc54b195c | 1,651 |
def is_big(label: str) -> bool:
"""Returns whether or not a cave is large based on its label"""
return label.isupper() | 7abdb0c5687e7870c96b767dc498e1f3c4ed21fe | 1,652 |
def _name_cleaner(agent_name):
"""Renames agent_name to prettier string for plots."""
rename_dict = {'correct_ts': 'Correct TS',
'kl_ucb': 'KL UCB',
'misspecified_ts': 'Misspecified TS',
'ucb1': 'UCB1',
'ucb-best': 'UCB-best',
'non... | e874745e804e07e385b377ec0ecd4247640ef6ce | 1,653 |
def add_training_args(parser):
"""Training arguments."""
group = parser.add_argument_group('train', 'training configurations')
group.add_argument('--experiment-name', type=str, default="gpt-345M",
help="The experiment name for summary and checkpoint")
group.add_argument('--batch... | 05c71d77320644fdaf00ef1638e76dbbce60ffb5 | 1,654 |
def _uniqueElements(an_iterable):
"""
:param iterable an_iterable:
:param int idx:
:return list: has only one occurrence of each element
"""
used = []
unique = [x for x in an_iterable if x not in used and (used.append(x) or True)]
return unique | 8290d30e48c3ade4a547d7c3a8cf0c57b8d45b19 | 1,655 |
def _bias_scale(x, b, data_format):
"""The multiplication counter part of tf.nn.bias_add."""
if data_format == 'NHWC':
return x * b
elif data_format == 'NCHW':
return x * b
else:
raise ValueError('invalid data_format: %s' % data_format) | 19e5bb9419827f6e6976b1c5ed3cd40cdd676ad0 | 1,656 |
import re
def checkTableName(tables):
""" Check if table name has an underscore or not."""
bad = set()
output = []
for i in tables:
if re.search('.*_.*', i):
bad.add(i)
if bad:
output.append("These tables have underscores in the name")
for i in bad:
... | 2847c20712e6ce92367772678d058a05b5d10dc3 | 1,657 |
def get_wrf_config(wrf_config, start_date=None, **kwargs):
"""
precedence = kwargs > wrf_config.json > constants
"""
if start_date is not None:
wrf_config['start_date'] = start_date
for key in kwargs:
wrf_config[key] = kwargs[key]
return wrf_config | c9e070b91ab93a7cb81a576aa799537361b7a26f | 1,658 |
def hamming(s1, s2):
"""Return the hamming distance between 2 DNA sequences"""
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) + abs(len(s1) - len(s2)) | e3e1f3e9cc883f27d26f00c1b3c9495d29c1a139 | 1,659 |
def nasnet_dual_path_scheme_ordinal(module,
x,
_):
"""
NASNet specific scheme of dual path response for an ordinal module with dual inputs/outputs in a DualPathSequential
module.
Parameters:
----------
module : nn.Module
... | aef487a25bc3349f14a112826ee4f8e8912dd324 | 1,660 |
import sqlite3
def get_exp_date_stats(db_file_name, Table):
"""Caculate exp date stats of collection"""
conn = sqlite3.connect(db_file_name)
c = conn.cursor()
c.execute('''SELECT exp, count(exp) FROM {} GROUP BY exp'''.format(Table))
exp_dict = {}
results = c.fetchall()
for result in res... | 7641d6309939359c1d790b66a1310b5b78be99a4 | 1,661 |
def print_scientific_16(value: float) -> str:
"""
Prints a value in 16-character scientific notation.
This is a sub-method and shouldnt typically be called
.. seealso:: print_float_16 for a better method
"""
if value == 0.0:
return '%16s' % '0.'
python_value = '%16.14e' % value # ... | 18072bfb5cc51e83f1c26086558abc4019e4737e | 1,663 |
def _interpolate_target(bin_edges, y_vals, idx, target):
"""Helper to identify when a function y that has been discretized hits value target.
idx is the first index where y is greater than the target
"""
if idx == 0:
y_1 = 0.
else:
y_1 = y_vals[idx - 1]
y_2 = y_vals[idx]
edg... | 7a84bc846c8446aa7449732fdb60171d6f144863 | 1,664 |
def count_path_recursive(m, n):
"""Count number of paths with the recursive method."""
def traverse(m, n, location=[1, 1]):
# return 0 if past edge
if location[0] > m or location[1] > n:
return 0
# return 1 if at end position
if location == [m, n]:
return ... | ad31718d179bf46966117ecfa414807e6d356634 | 1,665 |
def likelihood(sent, ai, domain, temperature):
"""Computes likelihood of a given sentence according the giving model."""
enc = ai._encode(sent, ai.model.word_dict)
score, _, _= ai.model.score_sent(enc, ai.lang_h, ai.ctx_h, temperature)
return score | 8332dfc8c2dba18a117768043dff67e632cc22ff | 1,667 |
def _build_xyz_pow(name, pref, l, m, n, shift=2):
"""
Builds an individual row contraction line.
name = pref * xc_pow[n] yc_pow[m] * zc_pow[n]
"""
l = l - shift
m = m - shift
n = n - shift
if (pref <= 0) or (l < 0) or (n < 0) or (m < 0):
return None
mul = " "
if pref =... | 0dbae02252b27845e795a586e2e28b58c948fa1d | 1,668 |
def sort_drugs(processed_data, alpha_sort, **kwargs):
"""
Sorts all drug names, as primary keys of processed data dictionary. Sorting
is governed by primary criteria of decreasing cost, then secondary criteria
of alphabetical order. Secondary criteria ignores unsafe characters if
"alpha_sort" is Tru... | aa3727dc52f0204c7c39807982a998cc03fabd2d | 1,669 |
import math
def make_axis_angle_matrix(axis, angle):
"""construct a matrix that rotates around axis by angle (in radians)"""
#[RMS] ported from WildMagic4
fCos = math.cos(angle)
fSin = math.sin(angle)
fX2 = axis[0]*axis[0]
fY2 = axis[1]*axis[1]
fZ2 = axis[2]*axis[2]
fXYM = axis[0]*axis... | 1bef075e63b26559184025a69f47d8c1b6dccf1d | 1,670 |
from pathlib import Path
import os
import json
def find_latest(message_ts: str, post_dir: Path) -> str:
"""Retrieves the latest POST request timestamp for a given message."""
latest_ts = message_ts
for postfile in os.listdir(os.fsencode(post_dir)):
if (filename := os.fsdecode(postfile)).endswith('... | 5c5203cf1adc572cf7e9908dcd3c856de7c0f0da | 1,671 |
def get_bio(x, lang='en'):
"""Get the one-sentence introduction"""
bio = x.loc[16][lang]
return bio | 8c9ddabd2e6ada790af2b85a3fb656291f3ee5bd | 1,673 |
def query_all():
"""Queries all matches in Elasticsearch, to be used further for suggesting
product names when a user is not aware of them.
"""
query_all = {
"query": {"match_all": {}},
}
return query_all | 9d15297cf82d813ff0a0688f5c25e2ca6fa145d3 | 1,674 |
def greet(lang):
"""This function is for printing a greeting in some
selected languages: Spanish, Swedish, and German"""
if lang == 'es':
return 'Hola'
elif lang == 'ge':
return 'Hallo'
elif lang == 'sv':
return 'Halla'
else:
return 'Hello' | dcbe0fb39e735666b36780ee8d06b457e0a9541e | 1,676 |
import torch
def hamming_dist(y_true, y_pred):
"""
Calculate the Hamming distance between a given predicted label and the
true label. Assumes inputs are torch Variables!
Args:
y_true (autograd.Variable): The true label
y_pred (autograd.Variable): The predicted label
Returns:
... | 0edda102820626b824861ac0f05d4d77f5def432 | 1,677 |
import re
def rmchars(value):
"""Remove special characters from alphanumeric values except for period (.)
and negative (-) characters.
:param value: Alphanumeric value
:type value: string
:returns: Alphanumeric value stripped of any special characters
:rtype: string
>>> import utils
... | 63428103f7da4184c6d9f33a9d05b02ce17f2448 | 1,679 |
def _filename_pattern(ext):
"""Returns an re matching native or tfrecord files of format `ext`."""
return r".*\.{}(\.tfrecord)?(\.gz)?".format(ext) | 6ec5a86dbba2432293451ca7dff0a0d1d5091bf0 | 1,681 |
def _extract_protocol_layers(deserialized_data):
"""
Removes unnecessary values from packets dictionaries.
:param deserialized_data: Deserialized data from tshark.
:return: List of filtered packets in dictionary format.
"""
packets_filtered = []
for packet in deserialized_data:
packe... | 3c3a899909c5278b29ffb402ccb4d8dde24fce3a | 1,682 |
def has_xml_header(filepath):
"""
Return True if the first line of the file is <?xml
:param filepath:
:return:
"""
return True | 21fdbdf36cf08ca18d8a0f0d7f7d2201b243c558 | 1,684 |
def Get_Histogram_key(qubitOperator):
"""
Function to obtain histogram key string for Cirq Simulator.
e.g.
PauliWord = QubitOperator('X0 Z2 Y3', 0.5j)
returning: histogram_string = '0,2,3'
Args:
qubitOperator (openfermion.ops._qubit_operator.QubitOperator): QubitOper... | f574f7b3f6c43de7b3121d4e49240a84a4bcfdfc | 1,686 |
def get_column_labels():
"""
This function generates a list of column names for the extracted features
that are returned by the get_features function.
"""
# list the names of the extracted features
feature_labels = ["amplitude_envelope",
"root_mean_square_energy",
... | c140ced9c4344bd7a4029d331d50ebe0750fac0a | 1,687 |
def corr_finder(X, threshold):
""" For each variable, find the independent variables that are equal to
or more highly correlated than the threshold with the curraent variable
Parameters
----------
X : pandas Dataframe
Contains only independent variables and desired index
threshold:... | 3b32a3eacb721ff09f6b5614c0ada82df814d5fa | 1,688 |
def base_conv(num, base):
"""Write a Python program to converting
an Integer to a string in any base"""
_list = []
if num//base == 0:
return str(num%base)
else:
return (base_conv(num//base, base) + str(num%base)) | 9fcc28ccfe8ba80d974cc4012aad456bfb8c9544 | 1,690 |
def origin_trial_function_call(feature_name, execution_context=None):
"""Returns a function call to determine if an origin trial is enabled."""
return 'RuntimeEnabledFeatures::{feature_name}Enabled({context})'.format(
feature_name=feature_name,
context=execution_context
if execution_cont... | 201dbe8449373dbad0144633350d3e6adbb58b80 | 1,691 |
def get_bit(byteval, index) -> bool:
"""retrieve bit value from byte at provided index"""
return (byteval & (1 << index)) != 0 | 1fe020449ae2ae2513073835db6f75b24e558fdb | 1,692 |
import ast
import sys
def ast_parse_node(node):
"""
:param ast.Node node: an ast node representing an expression of variable
:return ast.Node: an ast node for:
_watchpoints_obj = var
if <var is a local variable>:
# watch(a)
_watchpoints_localvar = "a"
elif ... | 22b3b6fed61e18ed6dc742040a365ebca8847fd5 | 1,693 |
def toint16(i):
""" Convert a number to a hexadecimal string of length 2 """
return f'{i:02x}' | 3effd2b3f011a962beac19682ad29e930eb0f057 | 1,695 |
def get_cpu_cores():
"""获取每个cpu核的信息
Returns:
统计成功返回是一个元组:
第一个元素是一个列表存放每个cpu核的信息
第二个元素是列表长度, 也就是计算机中cpu核心的总个数
若统计出来为空, 则返回None
"""
cpu_cores = []
with open('/proc/cpuinfo') as f:
for line in f:
info = line.strip()
if info.starts... | ad66faac3a956b1922173263415890bc543e0bba | 1,696 |
def heuristical_lengths(items):
"""
heuristical_lengths tries to deriver the lengths of the content of items.
It always returns a list.
a) If typeof(items) is a string, it'll return [len(items)]
b) If typeof(items) is a dict, it'll return [len(items)]
c) If typeof(items) is either list or tuple,... | 94a0759bcdc2e57431e8524f164a51f2091b6e61 | 1,701 |
def next(space, w_arr):
""" Advance the internal array pointer of an array """
length = w_arr.arraylen()
current_idx = w_arr.current_idx + 1
if current_idx >= length:
w_arr.current_idx = length
return space.w_False
w_arr.current_idx = current_idx
return w_arr._current(space) | 668fec305ed6bbe05895f317e284c7d2e4f83189 | 1,702 |
def clean_record(raw_string: str) -> str:
"""
Removes all unnecessary signs from a raw_string and returns it
:param raw_string: folder or file name to manage
:return: clean value
"""
for sign in ("'", '(', ')', '"'):
raw_string = raw_string.replace(sign, '')
return raw_string.replace... | ea484934dc10da879ede883287fc1d650cda74b8 | 1,704 |
import csv
def read_manifest_from_csv(filename):
"""
Read the ballot manifest into a list in the format ['batch id : number of ballots']
from CSV file named filename
"""
manifest = []
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter = ",")
for ... | b04b6a1b20512c27bb83a7631346bc6553fdc251 | 1,705 |
def _find_data_between_ranges(data, ranges, top_k):
"""Finds the rows of the data that fall between each range.
Args:
data (pd.Series): The predicted probability values for the postive class.
ranges (list): The threshold ranges defining the bins. Should include 0 and 1 as the first and last val... | 323986cba953a724f9cb3bad8b2522fc711529e5 | 1,706 |
def path_inclusion_filter_fn(path, param, layer):
"""Returns whether or not layer name is contained in path."""
return layer in path | c93aa83e67c600cd83d053d50fbeaee4f7eebf94 | 1,709 |
import socket
import time
def is_tcp_port_open(host: str, tcp_port: int) -> bool:
"""Checks if the TCP host port is open."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) # 2 Second Timeout
try:
sock.connect((host, tcp_port))
sock.shutdown(socket.SHUT_RD... | cbe4d0ae58610b863c30b4e1867b47cb1dbdfc3d | 1,711 |
def load_replica_camera_traj(traj_file_path):
"""
the format:
index
"""
camera_traj = []
traj_file_handle = open(traj_file_path, 'r')
for line in traj_file_handle:
split = line.split()
#if blank line, skip
if not len(split):
continue
camera_traj.a... | 1879c97ed5ce24834689b156ffdc971b023e67f2 | 1,713 |
def punctuation(chars=r',.\"!@#\$%\^&*(){}\[\]?/;\'`~:<>+=-'):
"""Finds characters in text. Useful to preprocess text. Do not forget
to escape special characters.
"""
return rf'[{chars}]' | b2fd23d8485c3b6d429723a02a95c981982559b5 | 1,714 |
def shift_time(x, dt):
"""Shift time axis to the left by dt. Used to account for pump & lamp delay"""
x -= dt
return x | c93fdddea8e41221583139dcc7a2d81177ba7c17 | 1,715 |
def log2_fold_change(df, samp_grps):
"""
calculate fold change - fixed as samp_grps.mean_names[0] over samp_grps.mean_names[1],
where the mean names are sorted alphabetically. The log has already been taken,
so the L2FC is calculated as mean0 - mean1
:param df: expanded and/or filtered dataframe
... | 07fcef6f5143095f4f8f77d0251bbd7ecd486fd9 | 1,716 |
def configure_smoothing(new_d,smoothing_scans):
"""
# <batchstep method="net.sf.mzmine.modules.peaklistmethods.peakpicking.smoothing.SmoothingModule">
# <parameter name="Peak lists" type="BATCH_LAST_PEAKLISTS"/>
# <parameter name="Filename suffix">smoothed</parameter>
# <parameter nam... | 031586cf5dbb9fdf1fb6762a89a988367d172942 | 1,717 |
def clean_key(func):
"""Provides a clean, readable key from the funct name and module path.
"""
module = func.__module__.replace("formfactoryapp.", "")
return "%s.%s" % (module, func.__name__) | 946288cd231148eb39af5d1e7e0b957d9f2131e8 | 1,719 |
def multiply(a,b):
"""
multiply values
Args:
a ([float/int]): any value
b ([float/int]): any value
"""
return a*b | 67a85b1675da48684e9de7e9834d3daa4357699b | 1,720 |
def check_method(adata):
"""Check that method output fits expected API."""
assert "labels_pred" in adata.obs
return True | 78c1a5181395f1675854333c30bf617c578cc1d4 | 1,722 |
def extract_traceback(notebook):
""" Extracts information about an error from the notebook.
Parameters
----------
notebook: :class:`nbformat.notebooknode.NotebookNode`
Executed notebook to find an error traceback.
Returns
-------
bool
Whether the executed notebook has an er... | 9af26f973e6810936eaa68058efcdb7bc145803b | 1,723 |
import time
def cachedmethod(timeout):
"""
Function decorator to enable caching for instance methods.
"""
def _cached(func):
if not(hasattr(func, 'expires')):
func.expires = {}
func.cache = {}
def __cached(self, *args, **kwargs):
if(timeout and func.expires.get(repr(self), 0) < time.time()):
if(r... | dd8999a60aa6d92e6b442c7c0661d88cd0e8590e | 1,725 |
import argparse
def parse_options(args):
"""
Parse commandline arguments into options for Monitor
:param args:
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--tcp",
required=True,
action="append",
help="TCP/IP address to monitor, e.g... | adda9497c230b885887b8c21f8e1adfd8bdd2376 | 1,726 |
def prod_cart(in_list_1: list, in_list_2: list) -> list:
"""
Compute the cartesian product of two list
:param in_list_1: the first list to be evaluated
:param in_list_2: the second list to be evaluated
:return: the prodotto cartesiano result as [[x,y],..]
"""
_list = []
for element_1 in ... | 9fdbfc558f5ec3b11c78535b9125e0a1c293035e | 1,727 |
from typing import Dict
def _extract_assembly_information(job_context: Dict) -> Dict:
"""Determine the Ensembl assembly version and name used for this index.
Ensembl will periodically release updated versions of the
assemblies which are where the input files for this processor
comes from. All divisi... | b78513b826c0a12bf87563095e33320aee328b76 | 1,729 |
async def cors_handler(request, handler):
"""Middleware to add CORS response headers
"""
response = await handler(request)
response.headers['Access-Control-Allow-Origin'] = '*'
return response | c9f33261b1fb2e6dc3ab3139e657106a94c5bfd1 | 1,730 |
import hmac
import hashlib
def get_proxy_signature(query_dict, secret):
"""
Calculate the signature of the given query dict as per Shopify's documentation for proxy requests.
See: http://docs.shopify.com/api/tutorials/application-proxies#security
"""
# Sort and combine query parameters into a sin... | c234f18c1d44a936c4844ae2fe1b912a624eef61 | 1,732 |
import copy
def __yaml_tag_test(*args, **kwargs):
"""YAML tag constructor for testing only"""
return copy.deepcopy(args), copy.deepcopy(kwargs) | 0abeb68caf32912c7b5a78dacbc89e537061a144 | 1,735 |
import hashlib
def cal_md5(content):
"""
计算content字符串的md5
:param content:
:return:
"""
# 使用encode
result = hashlib.md5(content.encode())
# 打印hash
md5 = result.hexdigest()
return md5 | 0cd26654c364e34ecc27b0a0b4d410a539e286c3 | 1,736 |
def _inv_Jacobian_2D(J, detJ):
""" manually invert 2x2 jacobians J in place """
tmp = J[:, 1, 1, :] / detJ
J[:, 0, 1, :] = -J[:, 0, 1, :] / detJ
J[:, 1, 0, :] = -J[:, 1, 0, :] / detJ
J[:, 1, 1, :] = J[:, 0, 0, :] / detJ
J[:, 0, 0, :] = tmp
return J | 23b1ff231e32f09f09dbae781f7e97354f3ca811 | 1,737 |
def to_square_feet(square_metres):
"""Convert metres^2 to ft^2"""
return square_metres * 10.7639 | 50510aad230efcb47662936237a232662fef5596 | 1,738 |
import json
def load_id_json_file(json_path):
"""
load the JSON file and get the data inside
all this function does is to call json.load(f)
inside a with statement
Args:
json_path (str): where the target JSON file is
Return:
ID list (list): all the d... | fd0f7fb73636cdf407b4de3e1aa3ae66dcc8f964 | 1,739 |
import os
def get_py_path(pem_path):
"""Returns the .py filepath used to generate the given .pem path, which may
or may not exist.
Some test files (notably those in verify_certificate_chain_unittest/ have a
"generate-XXX.py" script that builds the "XXX.pem" file. Build the path to
the corresponding "genera... | 0bc97d23138c44e051282fdfa22517f1289ab65a | 1,745 |
import re
def parse_path_length(path):
"""
parse path length
"""
matched_tmp = re.findall(r"(S\d+)", path)
return len(matched_tmp) | 762e2b86fe59689800ed33aba0419f83b261305b | 1,747 |
def check_permisions(request, allowed_groups):
""" Return permissions."""
try:
profile = request.user.id
print('User', profile, allowed_groups)
is_allowed = True
except Exception:
return False
else:
return is_allowed | 4bdb54bd1edafd7a0cf6f50196d470e0d3425c66 | 1,748 |
def ask_name(question: str = "What is your name?") -> str:
"""Ask for the users name."""
return input(question) | 1cc9ec4d3bc48d7ae4be1b2cf8eb64a0b4f94b23 | 1,750 |
def last(*args):
"""Return last value from any object type - list,tuple,int,string"""
if len(args) == 1:
return int(''.join(map(str,args))) if isinstance(args[0],int) else args[0][-1]
return args[-1] | ad8d836597dd6a5dfe059756b7d8d728f6ea35fc | 1,751 |
def is_float(s):
"""
Detertmine if a string can be converted to a floating point number.
"""
try:
float(s)
except:
return False
return True | 2df52b4f8e0835d9f169404a6cb4f003ca661fff | 1,752 |
def process_mean_results(data, capacity, constellation, scenario, parameters):
"""
Process results.
"""
output = []
adoption_rate = scenario[1]
overbooking_factor = parameters[constellation.lower()]['overbooking_factor']
constellation_capacity = capacity[constellation]
max_capacity = ... | 0619c397a21d27440988c4b23284e44700ba69eb | 1,754 |
def identify_ossim_kwl(ossim_kwl_file):
"""
parse geom file to identify if it is an ossim model
:param ossim_kwl_file : ossim keyword list file
:type ossim_kwl_file : str
:return ossim kwl info : ossimmodel or None if not an ossim kwl file
:rtype str
"""
try:
with open(ossim_kwl_... | 9a63a8b5e7ece79b11336e71a8afa5a703e3acbc | 1,755 |
def convert_cbaois_to_kpsois(cbaois):
"""Convert coordinate-based augmentables to KeypointsOnImage instances.
Parameters
----------
cbaois : list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or i... | 6eee2715de3bfc76fac9bd3c246b0d2352101be1 | 1,756 |
def get_zcl_attribute_size(code):
"""
Determine the number of bytes a given ZCL attribute takes up.
Args:
code (int): The attribute size code included in the packet.
Returns:
int: size of the attribute data in bytes, or -1 for error/no size.
"""
opts = (0x00, 0,
0x... | 99782c86be2413410c6819a59eadf0daba326af2 | 1,758 |
def _get_function_name_and_args(str_to_split):
"""
Split a string of into a meta-function name and list of arguments.
@param IN str_to_split String to split
@return Function name and list of arguments, as a pair
"""
parts = [s.strip() for s in str_to_split.split(" | ")]
if len(parts) < 2:
... | 1dae51c87e727d7fa6a3a8012f9768b9ca3364e7 | 1,759 |
def list_of_paths():
"""
It lists all the folders which not contain PET images
"""
return ['.DS_Store', 'localizer', 'Space_3D_T2_FLAIR_sag_p2', 'AXIAL_FLAIR', 'MPRAGE_ADNI_confirmed_REPEATX2', 'Axial_PD-T2_TSE',
'Axial_PD-T2_TSE_repeat', 'MPRAGE_SAG_ISO_p2_ND', 'Axial_PD-T2_TSE_confi... | bc74024d49396f80947b3cb0a45066381b7d3af4 | 1,761 |
import torch
def index_initial(n_batch, n_ch, tensor=True):
"""Tensor batch and channel index initialization.
Args:
n_batch (Int): Number of batch.
n_ch (Int): Number of channel.
tensor (bool): Return tensor or numpy array
Returns:
Tensor: Batch in... | 52a16ad4afcf931ba4cda9c014d47050970995c5 | 1,763 |
def calc_floodzone(row):
"""Extracts the FEMAZONE of an SFHA based on each row's attributes.
This function acts on individual rows of a pandas DataFrame using
the apply built-in.
Parameters
----------
row : Pandas Series
A row of a pandas DataFrame
Returns
-------
str
... | 5bb6f3f7cfc1b6bce41ad7a752845287759c16ad | 1,766 |
import re
def remove_space(text):
"""
Funcion que elimina espacios
:param str text: texto a procesar
"""
return re.sub(r"\s+", " ", text).strip() | 729d26bb6acbaa8da4c945d2ea6646ebb90f3122 | 1,767 |
import base64
def getFilePathBase():
"""
获取请求url文件的文件路径
:return: php->base64 code
"""
code = """
@ini_set("display_errors","0");
@set_time_limit(0);
@set_magic_quotes_runtime(0);
header("Content-Type:application/json");
$res = array();$res["path"] = dirname(__FILE__);
echo ("<ek>... | afcb1a5bf2972a2b13a32edcd8a9b968742bf7f3 | 1,768 |
import logging
def say_hello(name):
"""
Log client's name which entered our application and send message to it
"""
logging.info('User %s entered', name)
return 'Hello {}'.format(name) | b79865cca34d1430bf47afabf7c96741d59ac560 | 1,770 |
def merge_dicts(dictionaries):
"""Merges multiple separate dictionaries into a single dictionary.
Parameters
----------
dictionaries : An iterable container of Python dictionaries.
Returns
-------
merged : A single dictionary that represents the result of merging the all the
... | 1a2b5f3c539937e2e27a55ce3914f7368f0a7296 | 1,771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.