content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import time
def float_scalar(size=DEF_MATRIX, rep=DEF_REP):
"""
Returns the execution time of performing the sum of a random number to
each element of a random real matrix.
Parameters
----------
size : int
The dimension of the square matrix that will be used in... | 99e24af45a64d8d3b98df23cc87c1dfb4b1163ea | 46,062 |
def xr_ds_ex(decode_times=True, nyrs=3, var_const=True):
"""return an example xarray.Dataset object, useful for testing functions"""
# set up values for Dataset, 4 yrs of analytic monthly values
days_1yr = np.array([31.0, 28.0, 31.0, 30.0, 31.0, 30.0, 31.0, 31.0, 30.0, 31.0, 30.0, 31.0])
time_edges = n... | fd06fa2fc5816b44c04804a41f595aad15d34d82 | 46,064 |
def evaluate(gold, pred):
"""
Produce CoNLL 2005 SRL evaluation results for a provided sentences given as lists of tags, with the first list being a
list of targets. For example, [['-', 'love', '-'], ['(A0*)', '(V*)', '(A1*)']].
:param gold: gold labels
:param pred: predicted labels
:return: SRL... | b968c362bf8a8f743c77e290341a653a5dcfe375 | 46,065 |
def setup_platform(opp, config, add_entities, discovery_info=None):
"""Set up the Pushbullet Sensor platform."""
try:
pushbullet = PushBullet(config.get(CONF_API_KEY))
except InvalidKeyError:
_LOGGER.error("Wrong API key for Pushbullet supplied")
return False
pbprovider = PushB... | 0e782e48e09b9d6ace51359a7fcfb77e455d7071 | 46,067 |
def decode_from_bioes(tags):
"""
Decode from a sequence of BIOES tags, assuming default tag is 'O'.
Args:
tags: a list of BIOES tags
Returns:
A list of dict with start_idx, end_idx, and type values.
"""
res = []
ent_idxs = []
cur_type = None
def flush():
... | 0308b2e0e527a03a2e2168143fb6b022c3a19496 | 46,068 |
def getMaxVoltCurr(ser):
"""Get the maximum voltage and current from the supply. The response is an array: [0] = voltage, [1] = current"""
resp = spdQuery(ser, "GMAX\r")
print(resp)
return [int(resp[0][0:3])/10., int(resp[0][3:5])/10.] | 27c9b70118477d8c60eb0fe245ef3a73ed1782bd | 46,069 |
from datetime import datetime
from typing import Union
def datetime_x_days_ago_at_y_oclock(
tz_aware_original_time: datetime, x: int, y: Union[int, float], z: str
) -> datetime:
"""Returns the datetime x days ago a y o'clock as determined from the perspective of timezone z."""
if isinstance(y, float):
... | cd0b13b2c3d219c549a4c8415232546fdaf87499 | 46,071 |
from datetime import datetime
def timedelta2str(time_delta: timedelta) -> str:
"""Convert a timedelta object to its DICOM string counterpart.
Parameters
----------
time_delta : timedelta
The timedelta object to convert to string.
Returns
-------
str
The timdelta objected ... | 1e2e12fe833e2a2968c051c919300c366d655bcf | 46,072 |
def getServiceForQS(query_str):
"""URI ends is followed by HTTP version (space-delimited)
"""
query_params = parse_qs(query_str)
if ('s' in query_params):
return query_params['s'][-1]
eprint('HTTP request captured, but no service in URI. attributing data to _unspecified.')
return '_unspeci... | 6e9bd10f2c1ba618e2c3b180fef583069e5e9214 | 46,073 |
from typing import Callable
def lazy_property(func: Callable) -> Callable:
"""
Decorator that makes a property lazy-evaluated. Inspired by:
https://stevenloria.com/lazy-properties.
Arguments:
func: The function to be decorated as a lazy @property.
Returns:
Callable: The decorated ... | 1633bf51cd32a1f4851aa17fd7da20fd79e0d921 | 46,074 |
def cancel_order(order_id):
"""
:param order_id:
:return:
"""
params = {}
url = "/v1/order/orders/{0}/submitcancel".format(order_id)
return api_key_post(params, url) | 6ae1ec7673e4cc153c06d4bb2d077c8c2b4313e1 | 46,075 |
def create():
"""Create a new post for the current user."""
if request.method == "POST":
group = request.form["group"]
name = request.form["name"]
rating = request.form["rating"]
trigger = request.form["trigger"]
error = None
if not name:
error = "Nam... | bc73b21357d9d3fd1dd08d81781bc0c6698ca4fe | 46,076 |
from typing import Optional
def get_ssl_cipher_suite(load_balancer_id: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSslCipherSuiteResult:
"""
This data source provides details about a specific Ss... | ca52b18977c883c39ed3389ac35f7cf85b03df58 | 46,077 |
def plot_cospectra(cosp, freqs, ylabels=None, title='Cospectra'):
"""Plot cospectral matrices
Parameters
----------
cosp : ndarray, shape (n_freqs, n_channels, n_channels)
ndarray of cospectra.
freqs : ndarray, shape (n_freqs,)
The frequencies associated to cospectra.
Returns
... | e0e62401c26677f1f7596744de93f3715fefdd48 | 46,078 |
def update_account(admin_id, root, service_name, data):
"""Method to update the account for given storage service.
Args:
admin_id (str): Root privileges flag.
root (str): Root privileges activation flag.
service_name (str): The... | a975f01481cc621a787bd2d4688c8034820c87a8 | 46,080 |
def Distance(distance='euclidean', **kwargs):
"""Construct a factory function that produces Distance nodes.
Parameters
----------
distance : str, callable
Specifies the distance function to use (See elfi.Distance).
**kwargs
Any additional arguments to elfi.Distance.
Returns
---... | ac788acb2fd1332b70269fc95d461eab4facf34b | 46,082 |
def generate_body(du_dept_dict):
"""Return HTML that will be used for the body content of the box report BlogPage"""
body = '<ul>'
for item in du_dept_dict.items():
body += '<li>{}: {} GB</li>'.format(item[0], int(item[1]) / 1000000) # Convert to GB
body += '</ul>'
return body | 66e67abb1870440106ee6914b2110d29fcc3e1cd | 46,083 |
def file_handler_test_file() -> FileHandler:
"""Fixture returns FileHandler instance.
FileHandler is constructed from test xlsx file
in input_for_tests directory.
Returns:
:obj:`FileHandler`: Instantiated with actual Excel doc.
"""
file_handler_test_file = FileHandler(
"input_f... | c366e06ddba2ebea22e3c5e732aea1bcef0a60cd | 46,084 |
import warnings
import six
import pickle
def load_dygraph(model_path, keep_name_table=False):
"""
To load python2 saved models in python3.
"""
try:
para_dict, opti_dict = fluid.load_dygraph(model_path, keep_name_table)
return para_dict, opti_dict
except UnicodeDecodeError:
... | 1a3cf84ab2fbf48db61160fadf08628ebbc84045 | 46,085 |
import timeit
import wbia.plottool as pt
import wbia.plottool as pt
def timeit_grid(
stmt_list, setup='', iterations=10000, input_sizes=None, verbose=True, show=False
):
"""
Timeit:
>>> import utool as ut
>>> setup = ut.codeblock(
>>> '''
>>> import utool as ut
... | 6c8ac55f49ba259fe0b92658f7d138b44c1faade | 46,086 |
def get_profiles() -> dict:
"""Returns the profiles of all players.
Returns
-------
dict
profiles of the players
"""
with OpenJson(PLAYERS_DATA_PATH + "profiles.json") as profiles_file:
profiles = profiles_file.load()
return profiles | f57664ea1d4956b1e4cfd79a4a0b154d2ad02d4b | 46,087 |
def calculate_check_digit(data):
"""Calculate MRZ check digits for data.
:data data: Data to calculate the check digit of
:returns: check digit
"""
values = {
"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5,
"6": 6, "7": 7, "8": 8, "9": 9, "<": 0, "A": 10,
"B": 11, "C": 12, "... | f2ebef63d8ee0f050ecaec6aa338a0ca6c4af237 | 46,088 |
def flatten(root):
"""Flatten a hierarchical YAML dictionary into one with composite keys.
Args:
root: [dict] A hierarchical dictionary.
Returns:
Equivalent dictionary with '.'-delimited keys.
"""
result = {}
__flatten_into(root, '', result)
return result | 30a1ec62dd571973c70c6739e287c3e358c96907 | 46,089 |
def lookup(cubeWithData, cubeWithMap, sharedIndex):
"""
Returns the value of cubeWithData indexed by the index of cubeWithMap.
cubeWithData must be indexed by sharedIndex and cubeWithData values must correspond to elements of sharedIndex.
For example: Let's say you have a cube with an estimated inflati... | 979e4c3be85be484d1deb3ef48b78dae9f0527cf | 46,090 |
from re import X
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
# if someone has won the game, utility will be 1 or -1 according to who won
# X wins --> utility = 1
# O wins --> utility = -1
if is_over(board):
if winner(board) == X:
... | 028e42f32fae39fff2e4e291caf6d708cb7b891f | 46,091 |
def notimplemented(f):
"""Takes a function f with a docstring and replaces it with a function which
raises NotImplementedError(f.__doc__). Useful to avoid having to retype
docstrings on methods designed to be overridden elsewhere."""
def wrapper(self,*args,**kws):
raise NotImplementedErro... | eefdee57d0ebb0727e9238bc7f678d90b36100a6 | 46,092 |
import random
import pipes
def make_become_cmd(cmd, user, shell, method, flags=None, exe=None):
"""
helper function for connection plugins to create privilege escalation commands
"""
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
success_key = 'BECOME-SUCCESS-%s' ... | 1e71ac1f4596688e76723634c05e996aaea51194 | 46,093 |
def readFileBytes(path) -> bytes:
"""
读取文件字节数据
:param path: 文件路径
:return: 字节数组
"""
with openReadBytesFile(path) as f:
return f.read() | e923bcd27ef73ce7ce3620009bdeadefc33589e3 | 46,096 |
def check_if_list_and_matches_length(
param: "object", expected_length: int, name: str = "parameter"
) -> list:
"""
Checks, if the passed variable is a list. Otherwise creates a list of the variable of length expected_length.
Then checks if the length of the list is the expected length.
Arg... | 5579acc4ea82a60293da847b8d4e612246845808 | 46,097 |
def evaluatePortfolioRet(Rev_seq,t=12):
"""
@param Rev_seq:
@param t:天数 默认12(月) 252 日
@return:
"""
ret_mean=e**(Rev_seq.apply(lambda x:np.log(x+1)).mean()*t)-1
ret_sharpe=Rev_seq.mean()*t/Rev_seq.std()/t**0.5
ret_winrate=Rev_seq[Rev_seq>0].count()/Rev_seq.count()
ret_maxloss=maxDrawD... | f6072fade66b5abc4dff507adcc414672a559f35 | 46,098 |
def subs(exp, *s):
"""
Substitute the given subexpressions in the expression.
"""
if isinstance(exp, Expression):
return exp.subs(*s)
return exp | dfbb463ebb3a43355f6325de7a281951c74cc200 | 46,099 |
def guess_encoding(fname):
"""
Guesses the encoding of a file.
fname - the name of the file whose encoding to guess.
Returns the guessed encoding of the file (string).
"""
with open(fname, "rb") as file:
result = chardet.detect(file.read())
return result["encoding"] | 89fd77ab79d8bbf2c9879f836ef0a7373a8d2ea3 | 46,100 |
def buffer_filtering(buffer):
"""
Check whether "buffer" should be filtered.
"""
local = weechat.buffer_get_string(buffer, "localvar_%s" % SCRIPT_LOCALVAR)
return {"": None, "0": False, "1": True}[local] | a03fa0d5d2e75d9305ec9a9627e4ee68898df33a | 46,101 |
def parameter_count(funcsig):
"""Get the number of positional-or-keyword or position-only parameters in a
function signature.
Parameters
----------
funcsig : inspect.Signature
A UDF signature
Returns
-------
int
The number of parameters
"""
return sum(
p... | ff6e8ede23020d9d3c30333458e182f086e913c7 | 46,102 |
def sum_of_squares(v: Vector) -> float:
"""Uses dot_product function"""
return dot_product(v, v) | 44da95accc7444148b13a944f9a1fd85611238f1 | 46,103 |
def get_channel_index(image, label):
"""
Get the channel index of a specific channel
:param image: The image
:param label: The channel name
:return: The channel index (None if not found)
"""
labels = image.getChannelLabels()
if label in labels:
idx = labels.index(label)
... | 3980e83f61ac755f1fbcadef27964a405a0aaf31 | 46,104 |
def search_ignore_case(s, *keywords):
"""Convenience function to search a string for keywords. Case
insensitive version.
"""
acora = AcoraBuilder(keywords).build(ignore_case=True)
return acora.findall(s) | 5957e0c15a46743b43187203c5472442396d1bc1 | 46,105 |
def make_rgba(data_in: ArrayLike) -> ArrayLike:
"""Convert any array to an RGBA array.
RGBA arrays have 3 dimensions where the last represents the channels. If
an Alpha channel needs to be added it will be made completely opaque.
Returns
-------
3D RGBA unsigned 8-bit array
"""
max_va... | 52d57e95d1c7b7926ec8fa698d719da0c6b95aef | 46,106 |
def main(min_kmers, min_reads, slope, rank, longform_table, table_out):
"""Filter taxa according to the ratio of reads to kmers."""
long_taxa = pd.read_csv(longform_table)
long_taxa.columns = ['uuid', 'taxa', 'taxid', 'rank'] + long_taxa.columns.tolist()[4:]
long_taxa = long_taxa.query('rank == @rank')
... | 4a22e8fed4df65f16cd64a852750413269b4e6ff | 46,108 |
def error(v1, v2):
"""Returns the relative error with respect to the first value.
Positive error if program output is greater than AREMA table.
Negative error if program output is less than AREMA table.
"""
e = (v2 - v1)/v1
return e | c213751d1da06991f8cbef08c3c98b41f4fcc6af | 46,109 |
def read_meta(metafn=None):
"""
Read a [metadata] text file into a dictionary.
Function modified from https://github.com/JessicaS11/python_geotif_fns/blob/master/Landsat_TOARefl.py
"""
metadata = {}
# potential future improvement: strip quotation marks from strings, where applicable. Will then... | 834c2c8a0d1138b5c3ceb0ab6a7215a67c913acc | 46,110 |
def ODE_step_euler(x, y, h, derivs):
"""
Advances the solution y(x) from x to x+h using the Euler method.
derivs .... a python function f(x, (y1, y2, y3, ...)) returning
a tuple (y1', y2', y3', ...) where y1' is the derivative of y1 at x.
"""
X = derivs(y,x)
return vadd(y, smul(h, X)) | a696708e9aa854425c6af04395e401e48fb94490 | 46,111 |
def check_go(*args):
"""Check GO State. If all three panels are NOT a 'GO', ignitor state is set to 'Safe' mode.
Arguments
---------
args[0] : ucl --> UpperClass Instance
Nested Functions
----------------
getGOState() ... | 6c4a3c59991bcec5c6b25decc33ccca04b363e10 | 46,112 |
def max_abs_error_relative_to_mean_radius(standard_shape, test_shape):
"""
Compare test_shape to standard_shape, relative to mean radius of standard.
Returned value is a percentage.
standard_shape npy array
test_shape npy array
Must have the same shape. Either:
one-dimensional (s... | 5721eed0803cccec97370d54de544df7f7585497 | 46,113 |
def get_calendar(caldav_url):
"""
Get the calendar using credentials from `credentials.py`.
"""
url = caldav_url
client = caldav.DAVClient(url)
princ = caldav.Principal(client, url)
return princ.calendars()[0] | 19ea213c52a193034aed5be70b74bd4bd264d782 | 46,114 |
def batch_get_heuristic_mask_fetchpush_(s, a):
""" heuristic mask for disentangled fetch """
grip_poses = s[:, 0, :3]
obj_poses = s[:, 1, 10:13]
entangled = np.linalg.norm(grip_poses - obj_poses, axis=1, keepdims=True)[:, None] < 0.1
entangled_mask = np.ones((1, 3, 3))
disentangled_mask = np.array([[[1... | 1a511cb286f2054c2e8f12b80cbdbf0cbc31f902 | 46,115 |
from typing import Hashable
def is_hidden(tree: nx.DiGraph, node: Hashable, attr: str) -> bool:
"""Iterate on the node ancestors and determine if it is hidden along the chain"""
if tree is not None and node in tree:
if tree.nodes[node].get(attr, False):
return True
for ancestor in... | 703763188611f02fb1729e0d652f855a1207abc6 | 46,116 |
def parse_both_2(image_results):
""" parses the tags and repos from a image_results with the format:
{
'image': [{
'pluginImage': {
'ibmContainerRegistry': 'internalRepo/name'
'publicRegistry': 'repo/name'
},
'driverImage': {
'ibm... | 020cde41855d3bca26797cd9786e2733a50b6a00 | 46,117 |
from typing import Optional
from typing import cast
def decode_auth_token(token: str) -> Optional[LoginSessionDict]:
"""Decode an authorization token into a LoginSessionDict."""
decoded = None
try:
secret = get_secret_key()
decoded = jwt.decode(token, secret)
except InvalidSignatureE... | 153ae0f24470171ef75976d3f8a7ea8ef2729cc4 | 46,118 |
from numpy import NINF, PINF
from openravepy import AABB
import numpy
def ComputeEnabledAABB(kinbody):
"""
Returns the AABB of the enabled links of a KinBody.
@param kinbody: an OpenRAVE KinBody
@returns: AABB of the enabled links of the KinBody
"""
min_corner = numpy.array([PINF] * 3)
m... | 1390bb6b5199bbcd798848759724b0370d4356ce | 46,120 |
def find_last_version_pypi(package, delay):
"""Return the last version of a package
"""
url = 'https://pypi.org/project/{}/#history'.format(package)
page = requests_get_handler(url)
if page.status_code == 404:
print('{} not found'.format(package))
return ""
elements = pypi_parser... | 81ee46571ae555b0c445660079bb5d3da9c90476 | 46,121 |
def get_put_single_endpoint_schema(class_name, form_schema_model, response_schema):
"""
:param class_name:
:param form_schema_model:
:param response_schema:
"""
return {
"tags": [class_name],
"description": f"Create a {class_name}",
"requestBody": {
"descrip... | 1c073c02c025d563cba720e6e1334638c158e687 | 46,122 |
def get_bit(byte, bit_num):
""" Return bit number bit_num from right in byte.
@param int byte: a given byte
@param int bit_num: a specific bit number within the byte
@rtype: int
>>> get_bit(0b00000101, 2)
1
>>> get_bit(0b00000101, 1)
0
"""
return (byte & (1 << bit_num)) >> bit_... | 4f25c4ccdc4c3890fb4b80d42d90bfb94d6799c3 | 46,123 |
def dashboard(i):
"""
Input: {
(host) - Internal web server host
(port) - Internal web server port
(wfe_host) - External web server host
(wfe_port) - External web server port
(extra_url) - extra URL
}
... | e2a6990008c649cb3016845e5b60b41151327fc8 | 46,124 |
def create_translation_field(model, field_name, lang):
"""
Translation field factory. Returns a ``TranslationField`` based on a
fieldname and a language.
The list of supported fields can be extended by defining a tuple of field
names in the projects settings.py like this::
MODELTRANSLATION... | 9ba4783ab797634576abb52b5c4c3680f8f004f5 | 46,125 |
import logging
def ExtractPrompt(source, default):
"""Attempts to extract the prompt from the code cell.
Args:
source: The merged source string of the code cell.
default: The default prompt string.
Returns:
The source with prompt removed.
The first extracted prompt if pro... | 1142b7b546a174142d433a3123fba04d6c07b63e | 46,126 |
def find_dominant_axis(vertices):
"""
measures which axis has least variance and returns 0, 1, or 2 (x, y, z)
so the 3D coordinates can be reduced to 2D
"""
xArray = [x[0] for x in vertices]
yArray = [x[1] for x in vertices]
zArray = [x[2] for x in vertices]
xVariance = max(xArray) -... | f9a5adc52278a14e3a2a939bb0da57085a0bcb7a | 46,127 |
from datetime import datetime
def read_file(file_path):
"""
Read the given file path and its metadata. Returns a LoaderResult.
"""
with open(file_path, 'r') as f:
stats = fstat(f.fileno())
return LoaderResult(
buffer=f.read(),
successful=True,
metada... | c45e15653c451479e6c69d718b47072d766fef6d | 46,128 |
def generate_local_graph(N=N, n_divisions=4, mean_degree=MEAN_DEGREE):
"""Generates a graph with a much higher clustering coefficient.
Smaller n_divisions -> higher clustering.
"""
edges = genereate_local_edges(N, n_divisions, mean_degree)
H = edges2graph(edges, N)
# In Graph name, include the parameters.... | d119d70ad45a28b31fc58ad96beab958f7e9cec1 | 46,129 |
def GlyphCollection(mode="sdf", *args, **kwargs):
"""
mode: string
- "sdf" (speed: fast, size: small, output: decent)
- "agg" (speed: fasteest, size: big output: perfect)
"""
if mode == "agg":
return AggGlyphCollection(*args, **kwargs)
return SDFGlyphCollection(*arg... | faa401846c3fd9d94d81926efefb38e20ea79e31 | 46,130 |
def extract_dates_mp(raw_cert):
"""
Override SleekXMPP's TLS Certificte to handle all Valid TLS Date Formats
- Date prior to 1/1/2050:'%y%m%d%H%M%SZ'
- Date post after 1/1/2050: '%Y%m%d%H%M%SZ'
"""
slk_cert = sleekxmpp.xmlstream.cert
if not slk_cert.HAVE_PYASN1:
log.warning(... | c9dd000e88726745e1426d66f3876f4929800f0c | 46,131 |
def opt_pairwise(n_items, data, alpha=1e-6, method="Newton-CG",
initial_params=None, max_iter=None, tol=1e-5):
"""Compute the ML estimate of model parameters using ``scipy.optimize``.
This function computes the maximum-likelihood estimate of model parameters
given pairwise-comparison data (see :ref... | fb82e734aeedd9f4267698f873176f65251d463e | 46,132 |
def autocrop(img):
"""
Remove zero-valued rectangles at the border of the image.
Parameters
----------
img: ndarray
Image to be cropped
"""
slices = ndimage.find_objects(img > 0)[0]
return img[slices] | ebd6b90b0ee57ca779eb360d46f2b34cb3cef0e1 | 46,133 |
def authorize_payment(payment):
"""Activate client's payment authorization page from a PayPal Payment."""
for link in payment.links:
if link.rel == "approval_url":
# Convert to str to avoid Google App Engine Unicode issue
approval_url = str(link.href)
return approval_... | e489a1a2029535a8400f427a523665c49c872ef6 | 46,134 |
def import_sites_vcf(**kwargs) -> hl.Table:
"""Import site-level data from a VCF into a Hail Table."""
return hl.import_vcf(**kwargs).rows() | 82532ef35f882a8aa6794e3b5fca530c29892c50 | 46,135 |
def process_operator_filter(field, value):
""" Process a mongo operador attached to a field like name__in, pay__gte
Args:
field (str): The field name
value (str): The value
"""
params = field.split('__')
if len(params) is not 2:
return {}
field, operator = params
o... | 339fe67263edb318060abc5b122a6019148f031b | 46,136 |
def rref(mat, aug=0):
"""Performs Gauss-Jordan elimination to turn the matrix mat into RREF form in-place
and returns a string showing the working in LaTeX"""
row = 0
col = 0
n_rows = len(mat)
n_cols = len(mat[0])
ans = "\\begin{align*}\n"
while True:
if(row >= n_rows): # ran out of ... | bc2352ebda4a9e9834f7d17138aeed5d82663346 | 46,137 |
from typing import Pattern
import re
def _data_checks_pivot_longer(
df,
index,
column_names,
names_to,
values_to,
column_level,
names_sep,
names_pattern,
sort_by_appearance,
ignore_index,
):
"""
This function raises errors if the arguments have the wrong python type,
... | 0d1e6ed3d5a17d10edaf49b89e2a5bed922366ac | 46,138 |
def natsort_list(unsorted_list):
"""Basic function that organizes a list based on human (or natural) sorting
methodology.
Parameters
-----------
unsorted_list : list
List of strings.
Returns
-------
list
Sorted list of string.
"""
sorted_list = natsorted... | 4ee58867d2a2d3fa3e7a815826803facaf8e6d7a | 46,139 |
def getCatalogFiles(fname):
"""Return the files in an XML file catalog"""
print "Catalog content:"
print commands.getoutput("cat %s"%fname)
flist = []
xmldoc = minidom.parse(fname)
fileList = xmldoc.getElementsByTagName("File")
for thisfile in fileList:
fdict = {}
fdict['lfn'... | a5137b92ec07fed7580a6c0789acfbfb08294f37 | 46,140 |
def get_additional_features(eventlog_df):
"""
Transforms the initial eventlog dataset into a dataframe with trace vectors that describe
the Peformance Perspective of joruneys.
Input:
eventlog_df: [DataFrame] clean eventlog (one touchpoint per row)
Output:
A dataframe with t... | 1d77344d0067b3f8960788d726119d3938053e5d | 46,141 |
import hashlib
def CalcMD5(filepath):
"""generate a md5 code by a file path"""
with open(filepath,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
return md5obj.hexdigest() | fb339db0ec37dd46c9caeaf6ca74a114a9e85a87 | 46,143 |
def get_tf1(d):
"""
Returns the first order trend filtering matrix for d features.
Output
-------
D: array-like, shape (d -1, d)
The kth order difference matrix returned in a sparse matrix format.
"""
D = diags(diagonals=[-np.ones(d), np.ones(d - 1)], offsets=[0, 1])
D = D.tocsc... | 36cdfe6aec7f070df971542e3985b6e354b501ea | 46,144 |
def accepted_mimetypes(request, default='text/html'):
""" returns the accepted mimetypes of an HTTP/1.1 request
It returns a dictionary of the accepted mimetypes as
keys and their priorities as values.
"""
accepted_strings = request.requestHeaders.getRawHeaders(
'Accept', [default])
acc... | 785a53d43db807c903bff84e08e370ac26b71101 | 46,145 |
def num2hex(num, width=1):
"""将数字转换为指定长度的十六进制字符串
Args:
num (int): 输入数字
width (int, optional): 指定字符串长度. Defaults to 1.
Returns:
str: 输入数字的十六进制字符串表示
"""
return '{:0>{width}}'.format(hex(num)[2:].replace('L', ''), width=width) | 3a328ece233f32402fd9ff7db14e948d8a63c35f | 46,147 |
def count_locked():
"""
Count number of distinct locked tiles that could still be runing
on aws lambda
"""
tiles = db.SQL("""SELECT tile, subx, suby, filter, count(filter)
FROM mosaic_tiles_exposures t, exposure_files e
WHERE t.expid = e.eid AND t... | befa4894bbff2c6d19be81fe822f4fe6ba1b5490 | 46,148 |
def Title():
"""
Return a :class:`zope.schema.interfaces.IField` representing
the standard title of some object. This should be stored in the `title`
field.
"""
return PlainTextLine(
max_length=140, # twitter
required=False,
title=u"The human-readable title of this objec... | 2767a7f7bd126eb173c49d943a3be1ab0bc95149 | 46,149 |
import torch
def test_max_pool2d_memory():
"""Test the memory usage"""
# arguments and test data
N, H, W, CI, kernel_size, stride, padding, dilation = 128, 28, 28, 8, 3, 2, 1, 1
ceil_mode, return_indices = False, False
print("========== MaxPool2d Memory Test ==========")
for dtype in ['float3... | 30b6f58558f469d16e4813446074b436de1bad0a | 46,150 |
import ipaddress
def is_ip_address(ipaddr):
""" Simple helper to determine if given string is an ip address or subnet """
try:
ipaddress.ip_interface(ipaddr)
return True
except ValueError:
return False | 56abc5a1a82f6a2e0c7532182867fdfae76a3b89 | 46,151 |
def clear_team_text(data):
"""
Function clears table if rows are not valid (doesn't hold jumper data), for team and mixed competition only.
:param data: data pulled from team-pdfs
:return: list of jumpers rows
"""
data_to_skip = ['Assistant', '"ruhrgas"', 'Ski-Jumping', 'Official', 'Finish', 'J... | 779cf9c2ae8198cf980dd60221b56db17c75414d | 46,152 |
def _merge_retry_options(retry_options, overrides):
"""Helper for ``construct_settings()``.
Takes two retry options, and merges them into a single RetryOption instance.
Args:
retry_options (RetryOptions): The base RetryOptions.
overrides (RetryOptions): The RetryOptions used for overriding ``r... | ff2e06bef23f4792422d25202490836ae5f1a836 | 46,153 |
def tg_healthcheck_port(x):
"""
Property: TargetGroup.HealthCheckPort
"""
if isinstance(x, str) and x == "traffic-port":
return x
return network_port(x) | 19896f9a2287e632591c5e6bad27a3dfaf955ac4 | 46,154 |
import json
def isjson(value):
"""
Return whether or not given value is valid JSON.
If the value is valid JSON, this function returns ``True``, otherwise ``False``.
Examples::
>>> isjson('{"Key": {"Key": {"Key": 123}}}')
True
>>> isjson('{ key: "value" }')
False
... | 0527a07500337c8ce8e39a428c71556d6e91c5dd | 46,155 |
def IDTtoxyz(Inc, Dec, Btot):
"""Convert from Inclination, Declination,
Total intensity of earth field to x, y, z
"""
Bx = Btot * np.cos(Inc / 180.0 * np.pi) * np.sin(Dec / 180.0 * np.pi)
By = Btot * np.cos(Inc / 180.0 * np.pi) * np.cos(Dec / 180.0 * np.pi)
Bz = Btot * np.sin(Inc / 180.0 * np.pi... | 414fa08a2d99b229423808cf68c4937cb5966146 | 46,156 |
def conv_2d(x, n_filters: int, kernel_size: int, stride: int, max_pool: bool = False):
"""
Conv2D layer
:param x: input to the layer
:param n_filters: Number of filters for the layer
:param kernel_size: Size of the kernel
:param stride: Stride to apply
:param max_pool: Add a max pooling laye... | ab91b47c1f9f8e3c860421dd094e654579115f54 | 46,157 |
import pykwiki.jinja_filters as jinja_filters
def set_jinja_filters(env):
""" Used to add custom Jinja2 filters to the env """
env.filters['idsafe'] = jinja_filters.idsafe
return env | 00ec354b2e92bfab12c32166574c54b7343874f6 | 46,158 |
def get_dicom_data(path):
"""
Given dicom data file path,
return the corresponding dicom data.
"""
return pydicom.read_file(path) | 4a0906a4c212221c56c7993409f4a3f7be3f5fc2 | 46,160 |
def get_stats(data):
"""
Given a data set from get_data, the function returns an array where each row
contains the mean and standard deviation for a fixed system size.
Parameters
----------
data : ndarray
A 2-dimentional numpy array containing resulting approximation ratios.
Ea... | 665aacf2aba5287000c990d8da4535fdee6f9274 | 46,161 |
def concatenate_segments(segments, max_break='30m', max_heading_rate=5):
"""
Concatenate consecutive segments if they meet the requirements defined by
the maximum ship break allowed and the maximum heading deviation allowed.
Parameters
---------
segments : list of Datasets
The list of segments to compare betwe... | 4414eaa9edfde9aa861af0459c9675f28920a1ca | 46,162 |
import scipy
def _discount_cumsum(x: np.array, discount: float):
"""
magic from rllab for computing discounted cumulative sums of vectors.
input:
vector x,
[x0,
x1,
x2]
output:
[x0 + discount * x1 + discount^2 * x2,
x1 + discount * x2,
x2]
""... | ffe5cefef3995926ae3b8ba9f760c20b4f8bce61 | 46,163 |
def is_pythagorean_triplet(a, b, c):
"""Determine whether the provided numbers are a Pythagorean triplet.
Arguments:
a, b, c (int): Three integers.
Returns:
Boolean: True is the provided numbers are a Pythagorean triplet, False otherwise.
"""
return (a < b < c) and (a**2 + b**2 == ... | c879eb0f441f1b0f79fcfed7361d584954dcff3f | 46,164 |
def tune_search(train, test, fine_tune, project_name, verb, bayopt_trials):
"""Define the search space using keras-tuner and bayesian optimization"""
hypermodel = NASnet_transfer(input_shape=(331, 331, 3), fine_tune=fine_tune)
tuner = BayesianOptimization(
hypermodel,
max_trials=bayopt_tria... | a1634997b89ae3fff15f1ace02177dd1c2b4d9e4 | 46,166 |
def url_to_path(url: str):
"""Converts an incoming url into a path-slug."""
return slugify(url, max_length=199) | 8d48aaf6211c69b105f58a41129232f1f5e01230 | 46,167 |
import six
import time
def later_than(after, before):
""" True if then is later or equal to that """
if isinstance(after, six.string_types):
after = str_to_time(after)
elif isinstance(after, int):
after = time.gmtime(after)
if isinstance(before, six.string_types):
before = str... | e1ea29f35e315121f7b4e878fe86fa35a215c957 | 46,168 |
def make_adjacency_graph(frcs, bu_msg, max_dist=3):
"""Make a graph based on contour adjacency."""
preproc_pos = np.transpose(np.nonzero(bu_msg > 0))[:, 1:]
preproc_tree = cKDTree(preproc_pos)
# Assign each preproc to the closest F1
f1_bus_tree = cKDTree(frcs[:, 1:])
_, preproc_to_f1 = f1_bus_tr... | 6118c093d9c9342eaf6efa7157ccaab6b7906477 | 46,169 |
import torch
def drop_connect(inputs, p, training):
""" Drop connect. """
if not training: return inputs
batch_size = inputs.shape[0]
keep_prob = 1 - p
# random_tensor = keep_prob
random_tensor = torch.rand([batch_size, 1, 1, 1], dtype=inputs.dtype, device=inputs.device) + keep_prob
binary... | 10656b5050f1f2e90f3370d5392e7928f1c07ddc | 46,170 |
from datetime import datetime
def years_ago(years, from_date=None):
"""
Return datetime that was n years from some date (defaulting to right now)
:param years:
:param from_date: default `now`
:return:
"""
if from_date is None:
from_date = datetime.now()
return from_date - relat... | 8e503ddf3909b75566a6d7884a5583c2f03994fc | 46,171 |
def get_iters(mnist, batch_size):
"""Get MNIST iterators."""
train_iter = mx.io.NDArrayIter(mnist['train_data'],
mnist['train_label'],
batch_size,
shuffle=True)
val_iter = mx.io.NDArrayIter(mnist['test_d... | d63b99432f32b4735d84be6f9a8579e8e9e42b1b | 46,172 |
from typing import List
import logging
def _run_nary_op(op: str, kop: str,
stub: synthesis_service_pb2_grpc.SynthesisServiceStub,
num_inputs: int) -> List[delay_model_pb2.DataPoint]:
"""Characterizes an nary op."""
results = []
for bit_count in _bitwidth_sweep(0):
results.a... | 68e2b48a199ce9ae9018b2b9f4ba3173707df52c | 46,173 |
def list2words(l):
"""列表转换word对象列表"""
return [Word(i) for i in l] | 5bd4757004f114ac1db1e20bffd1a7cd91c99b0a | 46,175 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.