content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def script_method(f):
"""Create jedi.Script instance and apply f to it."""
@wraps(f)
def wrapper(source, line, column, path):
return f(Script(source, line, column, path))
return wrapper | 083805f3761f3f91015829f3f884252848d1bf6c | 79,468 |
def insertion_sort(nums):
"""Insertion Sort"""
if not nums:
return None
for i in range(1, len(nums)):
value = nums[i]
j = i - 1
while j >= 0:
if nums[j] > value:
nums[j + 1] = nums[j]
else:
break
j = j - 1
... | 60c0f89df9fcfcc4cc2bd683a903483cf7c1590f | 79,469 |
def _headers(source_parameters) -> dict:
"""Return the headers for the url-check."""
return {"Private-Token": source_parameters["private_token"]} if "private_token" in source_parameters else {} | 1aaae1e716871000d83c9610a71080dc7b5e550c | 79,471 |
def find_close_languages(lat1, lng1, languages, distance_cache):
"""Given latitude/longitude coordinates finds the nearest language."""
close_language_indices = []
for i, language in enumerate(languages):
lat2 = language["latitude"]
lng2 = language["longitude"]
loc1 = (float(lat1), float(lng1))
lo... | c4535c8cf16cf390d3d55fbb5bac9d0cad6ad24d | 79,472 |
from greattunes._best_response import _find_max_response_value
def tmp_Initializers_with_find_max_response_value_class():
"""
test version of Initializers to endow it with the property from _find_max_response_value, which is
otherwise defined as a static method in ._best_response
"""
class TmpCla... | 4024c65d258e310b7cdcb80354500bb4794f4ec9 | 79,473 |
from typing import Sequence
from re import T
from typing import Iterable
def chunks(seq: Sequence[T], chunk_size: int) -> Iterable[Sequence[T]]:
""" Split seq into chunk_size-sized chunks.
:param seq: A sequence to chunk.
:param chunk_size: The size of chunk.
"""
return (seq[i:i + chunk_s... | eb0b0e9dbd8abc28adcc44bfa77dd2c8c08ad9f2 | 79,474 |
def get_bprop_hswish(self):
"""Grad definition for `HSwish` operation."""
input_grad = G.HSwishGrad()
def bprop(x, out, dout):
dx = input_grad(dout, x)
return (dx,)
return bprop | baacbab93a6495359d65c0d2f862e487d8422708 | 79,475 |
from datetime import datetime
def get_daily_maximum(dates=None, data=None):
"""
Calculate daily maximum values using dates array and pandas
"""
# Use dataframe to hold dates and name column datetime
df = pd.DataFrame(np.array(dates))
df.columns = ['Datetime']
# Add column of index numbers... | 9f3274cb106792f1f8ac6e4dfad283bb93baf170 | 79,476 |
def vice_president_committee_assignments(request):
"""Renders Committee assignment update page for the Vice President"""
if not utils.verify_vice_president(request.user):
messages.error(request, "Vice President Access Denied!")
return HttpResponseRedirect(reverse('dashboard:home'))
form_lis... | 5cce27aa00db48ab61288b9879732a438cdaaed0 | 79,477 |
def table(data, xtitle=None, ytitle=None, size=100, plots=True, formstr=':8.3f',border=2) :
""" Returns HTML for a table of input figures
"""
p=np.array(data)
nx=p.shape[1]
ny=p.shape[0]
out='<TABLE BORDER={:d}>\n'.format(border)
if xtitle is not None :
out+='<TR>\n'
if ytitl... | d51fc8e0f31e784f8c6b6f011e7c176a21667e41 | 79,478 |
import functools
def cached_property(inputs=None):
"""Returns a cached proeprty that is calculated once.
If inputs are specified, then if those properties change the propery is
recalculated.
Usage is as follows; given a class, you can declare a cached property with
the `@cached_property` decorat... | 25c8291e4ba798727b6cf14161393085b269cc3f | 79,479 |
def split_data_with_pca(X, y, k_fold):
"""
We need to implement first MinMaxScaler and after PCA
:param data: The final dataframe
:param X: The features that we give to our model in order to be trained
:param y: The label we want to predict
:return: Splits the data in x_train, x_test, y_train, y... | d567e0062e7110e40ab1494a6323c7d9bac34d46 | 79,480 |
async def reverse_single_ip(ip: str, resolver: DNSResolver) -> str:
"""
Reverse a single IP and output the linked CNAME, if it exists.
Parameters
----------
:param ip: IP address to reverse
:param resolver: DNS server to use
Returns
-------
:return str: ... | ecdd34ddc17fcd3a1c75d25d09f794d5933dec4a | 79,481 |
def try_head(source: FrozenList[_TSource]) -> Option[_TSource]:
"""Try to get the first element from the list.
Returns the first element of the list, or None if the list is empty.
Args:
source: The input list.
Returns:
The first element of the list or `Nothing`.
"""
return sou... | 0dae1e1c81d5c9ef29d2fde210153efc4c133ea8 | 79,484 |
from typing import Counter
def get_train_test_split(X, y, is_categorical=False, log_counts=False):
"""
:param X:
:param y:
"""
label_counts = pd.Series(Counter(y)).sort_values(ascending=False)
if is_categorical and label_counts.values[1:].sum() > 5:
# we want to stratify the labels, b... | 7746e2f2f1898b1715742b43fee464a832f8e906 | 79,485 |
import requests
def extract_recovered(url):
"""Return the Recovered number from the Infobox."""
print(url)
page = requests.get(url)
if page.status_code != 200:
return None
return extract_recovered_from_html(page.text, url=url) | e098681a8e59fd12368f6571db33e1a197b50c96 | 79,486 |
def get_budget_id(budget_name):
""" Returns budget_id from arguments
Arguments:
:param budget_name: budget name
:returns: budget_id
:rtype: int
"""
budgets = BillingCode.all(detail='basic')
for budget in budgets:
if hasattr(budget, 'name') and budget.name == budget_name:
... | 396439cdafb76879c1acfbf5bafe91740cd3210c | 79,487 |
import scipy
def imread(path, c_dim=3):
"""
Read images
:param path: input image file path & name
:param c_dim: color dimensions, default = 3
:return: numpy images in uint8 format
"""
im = scipy.misc.imread(path).astype(np.float)
if c_dim == 1:
im = np.asarray(np.dstack((im, im... | 5de9c37889cd4b69c97a6f07f75fb260311cdaa4 | 79,488 |
def main_func(f):
"""
Wrap root command func in common opts and make it a command group
"""
f = globus_group("search-client", help="CLI Client to the Globus Search API")(f)
return f | ec06a581e004bcb382d21c49cc9c30e9038991ff | 79,489 |
def binarize(y, thres=3):
"""Given threshold, binarize the ratings.
"""
y[y< thres] = 0
y[y>=thres] = 1
return y | 385a10a652aa3a89874ee65520511f1554295ffe | 79,490 |
def parse_args(description=__doc__):
"""Parse command line arguments"""
parser = ArgumentParser(description=description)
parser.add_argument(
'--tdi-table', required=True,
help='''Path to TDI table or path to directory containing the file
`tdi_table.npy`'''
)
parser.add_argum... | 4cdc68f643b8c3dae9f7420a413470f71dd22772 | 79,492 |
def yolo_layer(inputs, n_classes, anchors, img_size, data_format):
"""
Creates Yolo final detection layer.
Detects boxes with respect to anchors.
Args:
inputs: Tensor input.
n_classes: Number of labels.
anchors: A list of anchor sizes.
img_si... | 297a371c8530122425995eebbdd4bd097230fdc8 | 79,493 |
def mod_cheb(N, mod_m, lbd):
""" compute the first N recurrence coefficients wrt d\mu
Params:
d\\mu: given measure,
mod_m: the first 2N-1 modified moments mod_m_1, ..., mod_m_{2N-2}
can be computed by quad.gq_modification_composite
lbd: known measure to be chosen s.t. d\\lbd ~ d\\mu in... | 1fc6e004bf4ae5d9758454a3cb019ab6f240f4dc | 79,494 |
def _get_fargs(func, no_self=False, no_varargs=False): # pragma: no cover
"""
Return function argument names.
The names are returned in a tuple in the order they are specified in the
function signature
:param func: Function
:type func: function object
:param no_self: Flag that indicates... | 2da480a4bd9da56bb7d62a588de8fb6e92fc096a | 79,495 |
def preserve_linefeeds(value):
"""Escape linefeeds.
To make templates work with both YAML and JSON, escape linefeeds instead of
allowing Jinja to render them.
"""
return value.replace("\n", "\\n").replace("\r", "") | ee8e4c33d81b0a31c8a0cbf99369235e34327a61 | 79,496 |
def get_test_data_yc(size: int = 1):
"""Generates a test dataset of the specified size"""
num_rows = len(y_cls)
test_df = y_cls.copy()
while num_rows < size:
test_df = np.append(test_df, test_df, axis=0)
num_rows = len(test_df)
return test_df[:size] | 27ed69b9df4708276829b04e3063c94afd502363 | 79,498 |
import re
def cnmr_parsing(text):
"""Parsing Carbon NMR data to detect solvent,temperature,reference,frequency and spectrum values.
param text:Carbon NMR data block
return:a dictionary that include all the information about solvent,temperature,reference,frequency and Carbon NMR
spectrum values
"""... | 31b8a9e04a7a918afe685482f5ffd833c8c0256c | 79,499 |
def rpexp(a,b):
"""Russian peasant exponention.
Exponention based on Russian peasant multiplication algorithm,
taken from "Ten Little Algorithms" by Jason Sachs.
Args:
a (int): the base,
b (int): the exponent.
Returns:
x (int): the b power of a, a**b.
"""
res... | 5e81e4a176ed4b6aa33747094452a9c622eb4969 | 79,500 |
def dt_method(inputfile, max_dis, process_num):
"""Generate DT method feature vectors.
:param inputfile: input sequence file in FASTA format.
:param max_dis: the maximum distance between top-1-gram pairs.
:param process_num: the number of processes used for multiprocessing.
"""
tng_list, seq_nam... | a6801f72faa730cbca3197c50c8d2a57f7a32df2 | 79,501 |
def update_tour_status(request):
"""Update User tour status."""
form = UserTourStatusForm(
request.POST,
instance=request.user.profile,
)
if not form.is_valid():
return HttpResponseBadRequest(form.errors.as_json())
form.save()
return HttpResponse('ok') | d48706707c69337b244439a0f8697d0c52e8e00c | 79,502 |
def worth_token_view():
"""返回仍然具备投资价值的token
@@@
### description
> finished
### args
None
### return
status code: **200**
```json
[
{
"Name": "btc"
},
{
"Name": "eth"
... | 57338b3c8e68a8b3a9f4034995aa1a056d3ca308 | 79,503 |
def get_data(afile, file_type=None, streaming=False, **keywords):
"""Get data from an excel file source
:param filename: actual file name, a file stream or actual content
:param sheet_name: the name of the sheet to be loaded
:param sheet_index: the index of the sheet to be loaded
:param file_type: ... | 3b87923b30a05b15801868a8536f673232d20305 | 79,504 |
from typing import List
from typing import Set
from typing import FrozenSet
def get_packed_items(weights: List[int], profits: List[float], solution: List[List[float]]) -> Set[FrozenSet[int]]:
"""
Returns the possible solution from a solved knapsack instance.
:param weights: Weights of items
:param pro... | 97f9142b49418918e483cae14675a38f16b24a7c | 79,505 |
def get_sequence_with_substitution(sequence):
"""Generate a sequence with mutations relative to the given mutation probability matrix
Parameters
----------
sequence : Bio.Seq.MutableSeq
Returns
-------
Bio.Seq.Seq
"""
read_length = len(sequence)
# create a set of draws
choi... | e7bbccc9060b98bbf7b2bacb1b49f31cd189ccbf | 79,507 |
import yaml
from typing import OrderedDict
def __ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
"""
Loads yaml into an OrderedDict.
From:
https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts
"""
class OrderedLoader(Lo... | d27d61cbad0489f8497d998d74dd77286c30aa67 | 79,508 |
from datetime import datetime
def new_request():
"""
This function receives a request from the PAM script and
returns a request ID used for later checking.
"""
user = request.values.get('user')
server = request.values.get('server')
remote = request.values.get('remote')
now = datetime.n... | 890666db465de47470204216e5c8ec3bff980a23 | 79,509 |
def _first_unvisited(graph, visited):
"""
Return first unvisited node.
@type graph: graph
@param graph: Graph.
@type visited: list
@param visited: List of nodes.
@rtype: node
@return: First unvisited node.
"""
for each in graph:
if (each not in visited):
... | fe7dfb3b6d11958367fc435b0fdbfecb732a2471 | 79,511 |
def test_thread_crew_mode(count):
"""
thread_crew_mode() can be any of '1:1', '1:m', 'm:m'. In 1:1 mode, the
worker function is simply called with a value read off one Channel, and
returns a value to be written to the other. In '1:m' mode, it is passed a
value plus the output Channel, and writes as ... | 6fdeb11a7d6e7a8e8fe65281804afc02ddfba67f | 79,512 |
def get_cdd_country(
t_base_cooling,
regions,
temp_data,
crit_temp_min_max=False
):
"""Calculate total number of cooling degree days in a
region for the base year
Arguments
----------
t_base_cooling : float
Base temperature assumption
regions : dict
... | 7b557f62449bdb98c714ec3117eee2308c751994 | 79,513 |
def calculate_surface_curvature(derivatives, order=False):
"""Calculates surface curvature quantities.
If "order" parameter is set to True, then it will be guaranteed, that C1
value is always less than C2.
Note
----
This is copied from https://github.com/nortikin/sverchok
"""
fu = deri... | 782132235a2f31001934cd3a777ab74350612ca0 | 79,514 |
import json
def has_service_account(service_account):
""" Returns `True` if a service account with a given name already exists.
This method uses `dcos security org` command and assumes that `dcos-enterprise-cli`
package is installed.
:param service_account: service account name
:typ... | 854f4985bd22590e516c1d76fa484c5c5266b641 | 79,515 |
def _dynamic_constraint_50(problem):
"""constraint on z, y"""
A_iq_row = []
A_iq_col = []
A_iq_data = []
frontier_nodes = filter(
lambda v: "frontiers" in problem.graph.nodes[v]
and problem.graph.nodes[v]["frontiers"] != 0,
problem.graph.nodes,
)
constraint_idx = 0... | fcaae7739490447fca79d0184cdde094e7fb0790 | 79,516 |
def get_filenames_in_directory(dir_path, file_ext):
"""
A Utility function to get the filenames of files in a given folder
with/without extension given a path
:param dir_path: A directory path
:param with_extension: Include extension into filename
:return: Filename with or without extension
... | 976046c56ea42e0d16eb3d7380656d0400e05a86 | 79,517 |
import numpy
def make_extension(ext):
"""generate an Extension object from its dotted name
"""
name = (ext[0])[2:-4]
name = name.replace("/", ".")
name = name.replace("\\", ".")
sources = ext[0:]
return Extension(
name,
sources=sources,
include_dirs=[numpy.get_inclu... | fcccb8a99f24c5894b91a3c8b11f27a1f186e0b8 | 79,518 |
def _preprocess_conv1d_input(x, data_format):
"""Transpose and cast the input before the conv1d.
# Arguments
x: input tensor.
data_format: string, `"channels_last"` or `"channels_first"`.
# Returns
A tensor.
"""
# tensorflow doesn't support float64 for conv layer before 1.8.0... | 162d1b7e3590600898df6656ad35403448548e3c | 79,519 |
def _ratio_bound(numerator_expression, denominator_expression, lower_bound,
upper_bound):
"""Creates an `Expression` for a bound on a ratio.
The result of this function is an `Expression` representing:
numerator / denominator_bound
where denominator_bound is a newly-created slack variable pr... | d62b2ce6d679f1c3d0c200248c35bacb1fcf0cdc | 79,520 |
def relaxed_caveman_graph(l, k, p, seed=None):
"""Returns a relaxed caveman graph.
A relaxed caveman graph starts with `l` cliques of size `k`. Edges are
then randomly rewired with probability `p` to link different cliques.
Parameters
----------
l : int
Number of groups
k : int
... | 0d33fc3df2e0583800f13f46c958f7ac11470d9b | 79,521 |
def test_peak_overflow(records,
gap_factor,
right_extension,
gap_threshold,
max_duration,
):
"""
Test that we handle dt overflows in peaks correctly. To this end, we
just create some sets ... | 19a8ffceffddba06a74b95023e798a30d2c6a07e | 79,522 |
def get_structure(structure_name:str, **kwargs):
""" Get model structure from name and args.
Args:
structure_name: name of structure in modeling.structures
"""
structs = getmembers(structures, isfunction)
for s in structs:
if s[0] == structure_name:
return s[1](**kwargs... | 56007ecb28fd35456de938cbe4bcf2cd809f34e0 | 79,523 |
import numpy
def solution(resources, args):
"""Problem 2 - Version 3
Calculate each Fibonacci number using matrix math and sum only the
even ones. Skip the even check to reduce branching.
Parameters:
args.number The upper limit of the range of numbers over
which th... | e91b5daabe89e61c6bc8827b2c35f4416fc0f038 | 79,524 |
def removeDup(head):
"""
方法功能:对带头结点的无序单链表删除重复的结点
输入参数:head: 链表头结点
"""
if head is None:
return
head.next = removeDupRecursion(head.next)
return None | 878b23cbc1e2714ea7f8044a25ec1dbbce4345ab | 79,525 |
def _get_updated_scaled_labels(labels_og, idxs=None, vals=None):
"""Helper function for interpolate_xd functions."""
if labels_og is not None:
if len(labels_og.shape) == 4:
# 2d scaled labels
tmp = np.copy(labels_og)
t, y, x = np.where(tmp[0] == 1)
label... | 94498f0dd7d25944934ebb7ca14ec6d374824071 | 79,526 |
def parse_mkdocs(content, section, url): # pylint: disable=unused-argument
"""Get the embed content for the section."""
ret = []
headers = []
if not content or not content.get('content'):
return (None, None, section)
body = content['content']
for element in PQ(body)('h2'):
hea... | 1ebb45b633e22ee76fa7e5fb13ec630e83934a42 | 79,527 |
def count_1(a: int) -> int:
"""
计算数值的二进制表示的1的数量
:param a:
:return:
"""
count = 0
while (a):
a = a & a - 1
count += 1
return count | 7217b3501cee8fff8eb6cf5887e982c879f95880 | 79,528 |
def time_type(value):
"""Helper for argparse"""
return convert_to_seconds(value) | cdad9147a6658f843955b0741c49f961a9b25c9b | 79,530 |
def group(lst, n):
"""group([0,3,4,10,2,3], 2) => iterator
Group an iterable into an n-tuples iterable. Incomplete tuples
are padded with Nones e.g.
>>> list(group(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
"""
iters = tee(lst, n)
iters = [iters[0]] + [ch... | f2e53f180946c3fdafec0ec6881a301928c4dd58 | 79,531 |
import types
from typing import List
from typing import Tuple
def benchmark_metrics(func: types.FunctionType) -> List[Tuple[str, str]]:
"""Returns the list of available metrics."""
return [(metric.__name__, metric.__doc__)
for metric in getattr(func, BENCHMARK_METRICS)] | d13602c9e47d4d19842bd5805b7f06a0af215ab7 | 79,533 |
def get_ave_cases():
"""
Weekly rolling average
"""
table = "cases"
values = [
"reporting_date",
"hospitalized_currently",
"positive_increase",
"death_increase",
"hospitalized_increase",
"tested_increase",
]
formatted_data = get_formatted_avera... | 90e47584e890644d7c4edaa869dcc4f34a210ab1 | 79,534 |
def ob_executions(ob_id):
"""
Retrieves the list of execution attempts for a specific OB.
:param ob_id: observation block id
:type ob_id: str
:rtype: List[str]
"""
ob = utils.get_by_id(ob_id, 'obCollect', cln_oid=False)
if "status" not in ob or "executions" not in ob["status"]:
... | e5a6a2924a23cd8d4f2a43d4c9cab80f7eabf529 | 79,535 |
def getCellsHPgeneration(cell):
""" Calculate the complete thermal power generated by a cells heatpumps
(Buildings) over a complete simulation run, for each time step.
If the hist-Size of heatpump differ, the data must be handled with caution
Args:
cell {Cell} -- Cell for which the heatpump po... | 093c5a11771958e85032f7f2a0fa2e76bde39607 | 79,536 |
def MCMC_Ising(beta, num, l_local, l_total):
"""
Parameters:
beta The temperature $\beta=1/(kT)$
num The number of equilibrium configuration data
Returns:
res The euqilibrium Ising spin configuration data
Z The partition function of the Ising spin model.
"""
... | 7ce36d5668bd5db62b29e6779ec7bb3ed3cc1a27 | 79,539 |
from typing import Optional
def load_stored_model(
max_age: Optional[float] = 12*3600
) -> MountModel:
"""Loads the model parameter set from disk and returns a MountModel instance.
Args:
max_age: Max allowed age of the model parameters in seconds. If the parameter set is older
... | d4d7e55cde6d876c1a1120aba937149066bc6026 | 79,540 |
def _AddMountedDisksToManifest(container_mount_disk, volumes, volume_mounts,
used_names=None, disks=None):
"""Add volume specs from --container-mount-disk."""
used_names = used_names or []
disks = disks or []
idx = 0
for mount_disk in container_mount_disk:
while _GetPersiste... | 1347540fd973f987786c69f14c2a1bf57cb47ebd | 79,541 |
def handler_stock(data_frame, board="M"):
"""
:param data_frame:
:param board:
:return:
"""
stocks = []
for index, row in data_frame.iterrows():
if index != 0:
code = row[0]
name = row[1]
lot = row[2]
# shortable = 1 when remark has H
... | a9b0c8b5435572e749e879998a405a7e50d0fbf0 | 79,542 |
import json
def is_json(data):
"""
Test, if a data set can be expressed as JSON.
"""
try:
json.dumps(data)
return True
except:
return False | a0e1da7dc341b2f8867fa1721cb0fe0cc0bcfa24 | 79,544 |
from typing import List
def _make_array(parts: List[str]) -> str:
"""
Utility to format an array of strings for passing to command line.
:param parts: List of strings.
:return: Formatted string.
"""
return "\"" + ",".join(parts) + "\"" | 3c364ee9b483274c2aad1f8df6afcebaabd09ed1 | 79,545 |
import requests
import re
def image(search, unsafe=False):
"""given a search string, return a image URL via google search"""
searchb = quote(search.encode("utf8"))
safe = "&safe=" if unsafe else "&safe=active"
searchurl = "https://www.google.com/search?tbm=isch&q={0}{1}".format(searchb, safe)
# ... | 80ea44e59516374140d3b22a8f51b826277a0040 | 79,546 |
import codecs
import re
def read_targets(corpus_inpath, target_opening_tag_pattern, target_closing_tag, target_class, target_variables,
extraction_function, corpus_encoding="utf-8", formatting_function=None):
"""
Read articles from corpus.
:param corpus_inpath: Path to corpus file.
... | 9fa6b5d6fbae6346e1366102fcecb4c32c372d04 | 79,547 |
def gethostbyname(hostname):
"""Translate a host name to IPv4 address format. The IPv4 address
is returned as a string.
:param str hostname: Desired hostname.
"""
addr = _the_interface.get_host_by_name(hostname)
addr = "{}.{}.{}.{}".format(addr[0], addr[1], addr[2], addr[3])
return addr | f94c8edd1bd84cb7602864fc4810109d9318e58f | 79,548 |
from .cluster import kmeans
import logging
def create_clusters(logr_matrix, min_cluster_size, sample_ids):
"""Extract and summarize clusters of samples in logr_matrix.
1. Calculate correlation coefficients between all samples (columns).
2. Cluster the correlation matrix.
3. For each resulting sample ... | 030c450b15ff182b334a22084e01a066847f0809 | 79,550 |
import tqdm
def process_width(img_matrix, dw):
"""
Removes the columns with the least energy
NOTE: As done in the paper, this only REDUCES the scale of the image. Doesn't increase
it, like Seam-carving algorithm
"""
processed_img_matrix = img_matrix.copy()
for _ in tqdm.tqdm(range(a... | 9a55c8ef3ef6e1ec8a3a1b1c1f68cf4c029b42ae | 79,551 |
import uuid
def generate_status(
request_time, status, succeeded, failed, pending,
successes=None, failures=None, pendings=None,
):
"""Generate Status Resource as defined in TAXII 2.1 section (4.3.1) <link here>`__."""
status = {
"id": str(uuid.uuid4()),
"status": status,
"requ... | 26f812edd27503acf6a86f2b4afa8193bc2e311d | 79,552 |
def parse_V1A_fname(fname):
"""
Note: See http://info.geonet.org.nz/display/appdata/Accelerogram+Data+Filenames+and+Formats
The file name can take three forms:
XNNSITEJJ, where X is the instrument code1, NN is the two-digit year
of acquisition, SITE is the 4 character site code, and JJ is the site'... | 7fb355c395cdc9b45f3cb0350c1df9469a471fb4 | 79,553 |
import re
def validate_format_email(email):
"""Return if a given string is email or not."""
try:
return bool(
re.search(r'^.*?@([\w\-]+\.)+[\w\-]+$', email, flags=re.IGNORECASE)
)
except TypeError:
raise TypeError('Email should be string, not {0}'.format(type(email))) | 5c413fb77658c3c438dc5abd41697863305b2ef5 | 79,554 |
def get_io_tensor_by_node_name(graph: tf.Graph, input_nodes, output_nodes,
input_indices=None, output_indices=None):
"""
Get graph input and output tensors by their corresponding operation names
Args:
graph: A tf.Graph object.
input_nodes: A list of the names o... | 762af9bdab34d9336b7fe512a1a0dce83ce7c006 | 79,555 |
from typing import Concatenate
def create_model(img_size=img_size, mel_step_size=mel_step_size):
"""
function to create the model
Parts:
face encoder, audio encoder, decoder
Args:
img_size -> input for face encoder: (img_size x img_size)
mel_step_size -> input for audio encoder... | c729728e38b553312a839d73d7e646f85f9ccb21 | 79,556 |
def on_interest_change(origin_matrix, changes_on_interest, interest_payment_type, grace_period_balloon):
"""
Recalculate the interest column based on user changes on insurance
Args:
origin_matrix: the updated origin matrix
changes_on_insurance: user changes on insurance, got from user chang... | e32c030ca42ee05ebec0954c9fbcc73954520460 | 79,557 |
def from_path(path, features, n_features=None):
"""Transformation using a saved decomposition object
Args:
path - the path to the saved decomposition object
features - the input feature data to transform
n_features - the number of features to keep after transformation
"""
... | 25316dbb0468da81362eb410dee675a32c8c08af | 79,559 |
import multiprocessing
def read_examples(input_files, batch_size, shuffle, num_epochs=None):
"""Creates readers and queues for reading example protos."""
files = []
for e in input_files:
for path in e.split(','):
files.extend(file_io.get_matching_files(path))
thread_count = multiprocessing.cpu_count... | 37d597e3fc1f98ffdb2182ded3ba6f8cffa1c2c2 | 79,560 |
import types
def get_input_peer(entity, allow_self=True, check_hash=True):
"""
Gets the input peer for the given "entity" (user, chat or channel).
A ``TypeError`` is raised if the given entity isn't a supported type
or if ``check_hash is True`` but the entity's ``access_hash is None``
*or* the en... | 91c478a1d232f2f1b9e80dacaad395bbf3bb037d | 79,561 |
import random
def generate_random_nhs_number() -> int:
"""
Returns a random valid NHS number, as an ``int``.
"""
check_digit = 10 # NHS numbers with this check digit are all invalid
while check_digit == 10:
digits = [random.randint(1, 9)] # don't start with a zero
digits.extend([... | 71e60bf37fee57344baf44864c4648414014f3b4 | 79,563 |
def make_snake_case(text: str) -> str:
"""
A very basic way to converts some text into snake case.
Strips out any non a-z, 0-9 characters.
:param text:
:return: a string which snake cases the text provided
"""
chars = 'abcdefghijklmnopqrstuvwxyz1234567890_'
unclean = text.lower().strip()... | cd4c46918da543f3f537020cf1e084c54182229e | 79,565 |
import uuid
def scramble_uploaded_filename(instance, filename):
"""
Scramble / uglify the filename of the uploaded file, but keep the files extension (e.g., .jpg or .png)
:param instance:
:param filename:
:return:
"""
extension = filename.split(".")[-1]
return '/'.join(['image', str(uu... | 5a7d2f5d99996ea4a991e9d47e7f107117bfb5fb | 79,566 |
from typing import TextIO
from typing import Sequence
from typing import Dict
import csv
def find_meta(exp_id: int, fh: TextIO) -> Sequence[Dict[str, str]]:
"""Find metadata info"""
reader = csv.DictReader(fh, delimiter=',')
if not 'experiment_id' in reader.fieldnames:
raise Exception(f'"{fh.name... | d3e6d6c47a0be736dcdd9b37eb4fa0f656222e83 | 79,567 |
import torch
def instance_aware_loss(solo_masks, instance_map, pred_param, k_inv_dot_xy1,
valid_region, gt_depth, return_loss=True):
"""
calculate loss of parameters
first we combine sample segmentation with sample params to get K plane parameters
then we used this parameter to... | 2c5c15aab5c12d147d5670b9b6ba249befbbc6c9 | 79,568 |
def add_department():
"""
Add a department to the database
"""
check_admin()
add_department = True
form = DepartmentForm()
if form.validate_on_submit():
department = Department(
deptname=form.deptname.data,
description=form.description.data
)
try:
# add department to the database
db.session.... | f443e394f94872128d4056c4e0d0b8cf109ddb3c | 79,569 |
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth... | b43f8d2358641dabe4ff33543619a3b2ad2ba29d | 79,570 |
def get_batches(dataloader):
"""
Args: Pytorch Dataloader object
returns a list of samples from the dataloader
"""
batch_list = []
count = 0
for fname, fobj in dataloader:
fname = [x.split("/")[-1] for x in fname]
batch_list.append(list(zip(fname, fobj)))
count += 1
... | 11970ec2f74112d9d7cf56ec26eefc585328c04c | 79,573 |
def is_vowel(c, lang):
"""
Is the character a vowel
"""
o = get_offset(c, lang)
return (o >= 0x04 and o <= 0x14) | e120950a36e02b15f437d1f058f850e2c79996db | 79,574 |
def annalistuser_create_values(
coll_id="testcoll", user_id="testuser",
user_name="Test User",
user_uri="mailto:testuser@example.org",
user_permissions=["VIEW", "CREATE", "UPDATE", "DELETE", "CONFIG", "ADMIN"]
):
"""
Values used when creating a user record
"""
d ... | e28b27e0d716123efd4738d976385ef5f703154e | 79,575 |
def _get_log_bounds(bounds, upper_default, decimal_precision,
zero_value_log_substitute):
"""Calculate the bound values in logspace and return them.
Warnings
--------
This method is intended for internal use only.
"""
# Set defaults for None values
bounds = [b if b is n... | c60d211edb15ab4eef1e235d49714bf8e37ce11b | 79,576 |
import math
def unitParser(unit, joint_value, relative_):
""" Argument unit """
global currentJointCommand
if unit == 'degree':
joint_degree_command = joint_value
# get absolute value
if relative_:
joint_degree_absolute_ = [joint_degree_command[i] + currentJointCommand... | 3061c359441aac6cc62cc04cd5e29eb86d02a955 | 79,577 |
def is_ipV4(addrstring):
""" checks that a dotted decomial IP address string can be correctly
parsed by the OS's inet_pton - quick way to verify formatting
takes addrstring which is "10.64.1.1" or something like it.
"""
try:
socket.inet_aton(addrstring)
ip = True
except socket.error:
pr... | c51f4739006009eaa2e05457de336d1e719d8fe9 | 79,578 |
import importlib
def can_contact_customer_support(botengine):
"""
Leverages the com.domain.YourBot/domain.py file or organization properties to determine if customer support is available for this bot
:return:
"""
try:
properties = importlib.import_module('properties')
except ImportErro... | 5916b9346d7853d1cd838f50ba67d2871b233772 | 79,579 |
import plistlib
import xml
def get_sus_install_report():
"""Return installed apple updates from softwareupdate"""
try:
history = plistlib.readPlist('/Library/Receipts/InstallHistory.plist')
except (IOError, xml.parsers.expat.ExpatError):
history = []
return {
i['displayName']: ... | 70907ffe260fc94cd0ca6339eebee93d56758fc0 | 79,580 |
import requests
from bs4 import BeautifulSoup
import re
def identify_work_in_ao3_series(link, number):
"""Do something.
link should be a link to a series, number is an int for which fic
Returns the link to that number fic in the series, or else None
"""
r = requests.get(link, headers=HEADERS)
... | 7023b8229fb2b7c30121fd394322b8dd42b28484 | 79,581 |
def _preclean_affiliation(aff):
"""
Performs basic cleaning operations on an affiliation string.
"""
aff = aff.decode('utf8')
aff = SPACES_REGEX.sub(' ', aff).strip()
aff = UNICODE_HANDLER.ent2u(aff)
return aff | c83ad84b9411db721413210af7893d4aa62b304c | 79,582 |
from typing import Union
from pathlib import Path
from typing import Any
import pickle
def pickle_load(path: Union[Path, str]) -> Any:
"""Pickle-load using the given path."""
with Path(path).open("rb") as f:
return pickle.load(f) | e035dfc554670a597c2edc8b98b3863750f05a23 | 79,583 |
import random
def set_folders_cv5(users_items_dict):
"""set_folders_cv5 function distributes items per each user randomly for different cross-validation splits
Args:
users_items_dict (dictionary): dictionary which was generated by fill_users_items_dict function
Returns:
... | c3bfe53c55866ed0c7593ff0873f4fe2e6272067 | 79,584 |
from luigi.interface import run as luigi_run
import six
import shlex
def law_run(argv, **kwargs):
"""
Runs a task with certain parameters as defined in *argv*, which can be a string or a list of
strings. It must start with the family of the task to run, followed by the desired parameters.
All *kwargs*... | 5a2364d92432919c52d1f30a6ab5f9cf928d7168 | 79,585 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.