content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Any
async def craete(*args: Any, **kwargs: Any) -> Page:
"""[Deprecated] miss-spelled function.
This function is undocumented and will be removed in future release.
"""
logger.warning(
'`craete` function is deprecated and will be removed in future. '
'Use `Page.crea... | f88267f1e7ca717b37b2bb95cbaf4a621b786ba2 | 3,625,929 |
def __get_candidate_set(previous: int, candidates: np.ndarray, visited: np.ndarray) -> int:
""" Рандомный из кандидатов """
candidates = np.array([idx for idx in candidates[previous] if idx != -1 and not visited[idx]])
if len(candidates) != 0:
return np.random.choice(candidates)
return -1 | 1087a3e4b9fd1d7eb9395a747bf3acce8d45b9c9 | 3,625,930 |
def trim_jumps(sweep, jump_size, trim=1, x_column=None):
"""
Clean up jumps in the data by removing several data points around them.
Remove `trim` datapoints on both sides of jumps if at least `jump_size`.
For multi-column data, `x_column` specifies the columns of interest.
"""
if not isinstanc... | 3901bda9c4b68ea86629bf8aea385ab316fc1bfd | 3,625,932 |
def _left_to_right_overlap(biluov, sentence):
"""
LEFTMOST TAG MUST BE 'V'
>>> _left_to_right_overlap(['V', 'V', 'O', 'V', 'I', 'L', 'O', 'I', 'L'], range(9))
[[0, 1, 3, 4, 5], [0, 1, 3, 7, 8]]
>>> _left_to_right_overlap(['V', 'O', 'V', 'O'], range(4))
[]
>>> _left_to_right_overlap(['V', 'O... | efadec066b9bd7654ebbefc8d8988eecfa4642d7 | 3,625,934 |
def terminal_values(rets):
"""
Computes the terminal values from a set of returns supplied as a T x N DataFrame
Return a Series of length N indexed by the columns of rets
"""
return (rets+1).prod() | bea1f2a668deac3e915f7531ab68aea207e57d91 | 3,625,935 |
def stretch_mat_creation(refcc, str_range=0.01, nstr=1001):
""" Matrix of stretched instance of a reference trace.
From the MIIC Development Team (eraldo.pomponi@uni-leipzig.de)
The reference trace is stretched using a cubic spline interpolation
algorithm form ``-str_range`` to ``str_range`` (in %) for... | ddc78aa83b2444517b564fb9cbd1d073cbfff33b | 3,625,937 |
import numpy
def clip_matrix(left, right, bottom, top, near, far, perspective=False):
"""Return matrix to obtain normalized device coordinates from frustrum.
"""
if left >= right or bottom >= top or near >= far:
raise ValueError("invalid frustrum")
if perspective:
if near <= _EPS:
... | 7de5ba1522bbe3ecd46f9bc2ddcbadf452dead6c | 3,625,938 |
def flip_horizontal(old_img):
""" flip the image over the y axis """
rows = old_img.shape[0]
cols = old_img.shape[1]
new_img = np.zeros((rows, cols), np.uint8) # create a black grayscale image having same size as original
for c in range(1, cols + 1): # iterate over the image columns (+1 because ra... | 0fb9beda2dded322ac639e41e05521467ccb017b | 3,625,939 |
def position_delta(trades, price_currency=None, volume_currency='BTC'):
"""
This function calculates our position across a list of trades for both the price
and volume currencies. This is equivalent to calculating the total amount our
balance in the two currencies have changed, and to the difference bet... | 5a3491848321cf38bb050de5863703e5fd19ffe7 | 3,625,940 |
def is_grammar_correct(grammar):
"""
This function checks if the grammar "grammar" is correct
Input:
- "grammar" is a grammar
"""
allrules = set(grammar.keys())
for rule_key in grammar:
if isinstance(grammar[rule_key], ConstructorRule):
for parameter in grammar[rule_key].... | 4e06efaf9350b608ae984c0d0482227b9e02fbbf | 3,625,941 |
def countTransactions(Transaction_list):
""" A list like the following
[
[1,1,1],
[0,0,0],
[1,1,1],
[1,1,0],
[1,1,1]
]
should be converted to a list without any duplicates and
count of each list should be appended to the list items
[
[1, 1, 0, 1],
[0, 0, 0, 1],
[1, 1, 1... | cc5814009b610d0869912cf1ee4b58c6f102579e | 3,625,942 |
def flatten_tree_depth_first(tree, exclude=None, exclude_children=False, return_only_run_id=False, return_trace=False):
"""
Flatten a run tree in a depth-first manner. May return a list of run ids or runs.
:param tree: dict
The tree to flatten
:param exclude:
A function to exclude nodes... | 0f30d2903e1cdbe4b838deebcd747d009919c632 | 3,625,943 |
def check_stitching(stitch_file):
"""
Take a stitch log file from MIPWrangler output, return summary datframe.
"""
with open(stitch_file) as infile:
stitch = []
for line in infile:
newline = line.strip()
stitch.append(newline)
sti_sum = []
for l in stitch:... | 6c6b68ec910ad0dd63504eff9fe0d644bdaa2df3 | 3,625,945 |
def levelConditions(state,stage):
"""
This is specifically created for purpose of the game plot. It sets the conditions for when
the game level changes and the plot moves forward. It also updates what music is playing and
can come with a noise as the level changes. If the music is updates it returns Tru... | 8f84b1ca0d8083e90c730d47ebbd34d86d346462 | 3,625,946 |
import re
def parse_vehicle_type(vehicle, include_number=False):
"""
Takes a vehicle string (BE.NMBS.IC504)
and returns a human-readable
version of its type (e.g. IC, L)
"""
matches = re.match(r'(?:BE.NMBS.)?([A-Z]{1,3})(\d{1,4})', vehicle)
try:
train_type = matches.group(1)
ex... | de1d184406b55a8c44ee3d104ba3f9882c95b4da | 3,625,947 |
import torch
def make_train_step(model, optimizer):
"""
Builds function that performs a step in the train loop.
Extracted from:
https://towardsdatascience.com/understanding-pytorch-with-an-example-a-step-by-step-tutorial-81fc5f8c4e8e#58f2
"""
def train_step(xdata, ydata):
# Zeroes gra... | 946e499586494acbdedcc94594b625896569b7b5 | 3,625,948 |
def get_writer(settings):
"""
Get a :py:class:`gnsq.Nsqd` instance configured to connect to the nsqd
writer address configured in settings. The writer communicates over the
nsq HTTP API and does not hold a connection open to the nsq instance.
"""
ns = settings.get('nsq.namespace')
addr = set... | de3eaab55756ebe5790e0275e6ce5aeb67803169 | 3,625,949 |
def sequence_conv(num_filters,
filter_size=3,
filter_stride=1,
padding=None,
bias_attr=None,
param_attr=None,
act=None,
name=None):
"""
Return a function that creates a paddle.fluid.laye... | a6e39fe0e01ce676234df94a004021f2b688d124 | 3,625,953 |
def getColumnNames(hdu):
"""Get names of columns in HDU."""
return [d.name for d in hdu.get_coldefs()] | 9ac8fefe6fcf0e7aed10699f19b849c14b022d47 | 3,625,955 |
def read_bed(bed_path):
"""Reads bed file into a DataFrame."""
bed_cols = [
'chrom', 'chromStart', 'chromEnd', 'name', 'score', 'strand',
'thickStart', 'thickEnd', 'itemRgb', 'blockCount', 'blockSizes',
'blockStarts'
]
data = pd.read_csv(bed_path, sep='\t', header=None)
dat... | 08dd42808f6e089e9fe65a5c6e68fb28b47afcd6 | 3,625,956 |
import torch
def embedding_to_probability(embedding: torch.Tensor, centroids: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
"""
Vectorizing this is slower than the loop!!!
# / (e_ix - C_kx)^2 (e_iy - C_ky)^2 (e_iz - C_kz)^2 \
# prob_k(e_i) = exp |-1 * ----... | 133b7b81bb00db2110b6ec9709ab89924dee2dc4 | 3,625,957 |
def check_if_session_accepted(data):
"""
Check if the session can be accepted given the criteria in config
Note: qualification and setup are skipped as they are checked in JS. Workers cannot continue if they do not pass.
:param data:
:return:
"""
msg = "Make sure you follow the instruction:... | f392a28e8e9805adfac8459e054a909c4c4905f3 | 3,625,958 |
def _get_fingerprint(arg, controller):
"""
Resolves user input into a relay fingerprint. This accepts...
* Fingerprints
* Nicknames
* IPv4 addresses, either with or without an ORPort
* Empty input, which is resolved to ourselves if we're a relay
:param str arg: input to be resolved to a relay fi... | 106a482dc9e33b158e466c736f82aea24e40e345 | 3,625,959 |
import decimal
def versions_rank_algorithm(quality, popularity):
"""
Generate a score for this version of an ebook.
The quality score and the popularity score are ratioed together 70:30
Since popularity is a scalar and can grow indefinitely, it's divided by
the number of total system users.
... | 830138290357b4978513b74453e78e8379f4b153 | 3,625,960 |
def get_colors(colormap, ncol, alpha=1.0, hide_traceback=True):
"""
Get a list of rgb values for a matplotlib colormap
Parameters
----------
colormap : str, default "WORM"
Name of the colormap to color the scatterpoints. Accepts "WORM",
"colorblind", or matplotlib colormaps.
... | 2f5c99d8e5b99c32103e169da90571ddf7e1cd68 | 3,625,961 |
def get_url(server_name, listen_port):
"""
Generating URL to get the information
from namenode/namenode
:param server_name:
:param listen_port:
:return:
"""
if listen_port < 0:
print ("Invalid Port")
exit()
if not server_name:
print("Pass valid Host... | 097e347a75eb581ae97734552fa6f9e7d3b11ce6 | 3,625,962 |
def alpha_shape(points, alpha, only_outer=True):
"""
Compute the alpha shape (concave hull) of a set of points.
:param points: np.array of shape (n,2) points.
:param alpha: alpha value.
:param only_outer: boolean value to specify if we keep only the outer border
or also inner edges.
:return: set of (i,j) pairs r... | e93a899a643b2a4be426a31c0dc0de27cbaea42d | 3,625,963 |
def _botocore_resolver():
"""Get the DNS suffix for the given region.
Args:
region (str): AWS region name
Returns:
str: the DNS suffix
"""
loader = botocore.loaders.create_loader()
return botocore.regions.EndpointResolver(loader.load_data("endpoints")) | 02d025b75d99daaefe1b37874be3404572ba10ed | 3,625,964 |
def euler97():
"""Solution for problem 97."""
mod = 10 ** 10
return (1 + 28433 * pow(2, 7830457, mod)) % mod | ab04cf67431a434f147f3615bee5a211b58ccbde | 3,625,965 |
import math
def getBoundaryBoxes(uint64Img):
"""Extracts boundary boxes from a labelled image.
Args:
uint64Img (1-chan uint64 numpy array): A grayscale image, which contains a specific label for each region.
Returns:
anchors (integer tuple list): A list which contains the anchor points... | cb50c59a877597af7d4167672e0a3006465b0a10 | 3,625,966 |
def reddening(wave, a_v, r_v=3.1, model='od94'):
"""Inverse of flux transmission fraction at given wavelength(s).
Parameters
----------
wave : float or list_like
Wavelength(s) in angstroms at which to evaluate the reddening.
a_v : float
Total V band extinction, in magnitudes. A(V) =... | 75aed1ec5371f0ec99d97e904a173ff2cf8eb455 | 3,625,967 |
import requests
import json
def callJenkinsApi(jenkinsApi, jenkinsFolders):
"""
Call the Jenkins API and fetch the JSON response
List jobs: api/json?tree=jobs[name]
"""
targetUrl = ""
folderUrl = ""
responseValue = ""
# Create proper url for folders
if len(jenkins... | 72423664211205b5b4409a308c6821b5602d8da3 | 3,625,968 |
def frame_shift(array, shift_y, shift_x, lib='opencv', interpolation='bicubic'):
""" Shifts an 2d array by shift_y, shift_x. Boundaries are filled with zeros.
Parameters
----------
array : array_like
Input 2d array.
shift_y, shift_x: float
Shifts in x and y directions.
lib : {'... | bf2614c58c5be61c7697cea32c804d0a6579b892 | 3,625,969 |
import base64
import email
def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to create a MIME Message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID... | f59c67ed90b47ec30d69f4c61ca47b656fa5ec2b | 3,625,970 |
import string
def is_palindrome_recursive(text, left=None, right=None):
"""
is_palindrome_recursive() checks to see if a given text is a palindrome
meaning its characters flipped would be the same word from the beginning.
Args: text (string)
Returns: is_palindrome (bool)
... | 9385b5cb468594e7eead38e18803dab1c4d4959c | 3,625,971 |
def latex_code(size):
"""
Get LaTeX code for size
"""
return "\\" + size + " " | 03478f8f62bb2b70ab5ca6ece66d4cdca3595dd6 | 3,625,972 |
def create_inner_out_logp(value_map):
"""Create a log-likelihood inner-output.
This is intended to be use with `get_random_outer_outputs`.
"""
res = []
for old_inner_out_var, new_inner_in_var in value_map.items():
logp = logprob(old_inner_out_var, new_inner_in_var)
if new_inner_in_... | 0a448fda87f8abc2e4ad9eba4d0a45f67aa9f527 | 3,625,973 |
def GRUCell(input_size: int, hidden_size: int, bias: bool = False):
"""
Simple wrapper for GRUCell that handles initialization
Args:
input_size – The number of expected features in the input x
hidden_size – The number of features in the hidden state h
bias – If False, then the layer ... | ffa7b26a3f2c79efae02854839a5dcbc009c6ce5 | 3,625,974 |
def embedding(x,
vocab_size,
dense_size,
name=None,
reuse=None,
multiplier=1.0,
symbol_dropout_rate=0.0,
embedding_var=None,
dtype=tf.float32):
"""Embed x of type int64 into dense vectors, reducing to max 4... | 0bcac81be1d314637662cd82efc6c9ae91dfe868 | 3,625,975 |
def has_cycle_visit(visiting, parents, adjacency_list, s):
"""
Check if there is a cycle in a graph starting
at the node s
"""
visiting[s] = True
for u in adjacency_list[s]:
if u in visiting:
return True
if u in parents:
continue
parents[u] = s
if has_cycle_visit(visiting, paren... | 5f87f6f39d88cbae93e7e461590002ca6a94aa20 | 3,625,976 |
def _show_interactive_menu(test_session):
"""Display an interactive menu based on the current test session state.
This will return when the user invokes one of the exit menu items.
"""
# A menu item for all menus, so that test_session.state is checked again
refresh_test_session_state = FunctionItem... | ffcb8ebef18b7030d5d8b459c8a4f01c7f5d37a0 | 3,625,977 |
def create_lock(objects, lock_name):
"""Create locks for list of objects"""
locks_list = list()
for obj in objects:
if isinstance(obj, dict):
lock = distributedlock(lock_name % obj['id'])
else:
lock = distributedlock(lock_name % obj)
lock.__enter__()
... | 27cdc21e76a03e4a87845b1a34a557b536e8db66 | 3,625,978 |
def get_trans_func():
"""
Returns the next status (modifier) based on the current status,
the event on the new modifier (pressed or released) and the new modifier typed.
next_status = f(event, modifier, curr_status)
event can be {'press', release}; modifier is one of the possible modifier in m... | 43cfb73f3cb4c5dabb43a47dcae5cfa53aa0cc1f | 3,625,980 |
def remove_trailing_whitespace(line):
"""Removes trailing whitespace, but preserves the newline if present.
"""
if line.endswith("\n"):
return "{}\n".format(remove_trailing_whitespace(line[:-1]))
return line.rstrip() | 2c5f7b3a35152b89cda6645911569c9d2815f47e | 3,625,981 |
def process_settings(pelicanobj):
"""Sets user specified Katex settings"""
katex_settings = {}
katex_settings['auto_insert'] = True
katex_settings['process_summary'] = True
return katex_settings | 9799d9ea6bf17fabd1640c4e69ca3b1da5406829 | 3,625,982 |
def install(**kwargs):
"""setup entry point"""
return setup(
name="pysachi",
version=__pkginfo__["version"],
packages=[
'pysachi',
'pysachi/rules',
'pysachi/checkers'
],
entry_points={'pysachi.renderers': [
"html = pysachi.r... | 3df42d5aa342e08bceaa79e8e3ea206f7d7454a3 | 3,625,983 |
def total_infection_rate_60():
"""
Real Name: b'total infection rate 60'
Original Eqn: b'infection rate asymptomatic self 60+infection rate quarantined self 60+infection rate symptomatic self 60 +infection rate asymptomatic 80x60+infection rate symptomatic 80x60 +infection rate asymptomatic 70x60+infection ... | 6a231ae069437002dfe610db654fd51c7a5d69a6 | 3,625,984 |
from typing import AnyStr
from typing import Dict
def get_source(source_string: AnyStr) -> Dict:
"""
This method finds the rss feed object based on source string
:param source_string: String acting as key to find RSS feed source
:return:
"""
source = "_".join([word.lower() for word in source_s... | 7454234b864675e68d8329f71c2c14557ae136ff | 3,625,985 |
import time
def run_epoch(session, model, data, is_train=False, verbose=False, sv=None, epoch=None):
"""Runs the model on the given data."""
epoch_size = ((len(data[0]) // model.batch_size) - 1) // model.num_steps
start_time = time.time()
costs = 0.0
iters = 0
state = session.run(model.initial... | b146c75caf6f750b64072070fb65784107b760d6 | 3,625,987 |
def gconnect():
"""Log users into their Google accounts and the Web app.
Log users into Google and the Web app if their login
details are correct, and their session state and server states
match (indicating the no 3rd party is attempting to hi-jack
the session). Create new user in the User table of... | e8ebd71de91e01435d9872a0633ba4b1f9f49dd1 | 3,625,988 |
import re
def _collect_models(container, json_reference, models, swagger_spec):
"""
Callback used during the swagger spec ingestion to collect all the
tagged models and create appropriate python types for them.
NOTE: this callback creates the model python type only if the container
represents a v... | 3cf1898333b309642258d99e19926553d8f6a073 | 3,625,989 |
def non_usd_ois(asset: Asset, tenor: str = None, *, source: str = None, real_time: bool = False) -> Series:
"""
GS end-of-day non domestic USD ois rate curve for G10 cross currencies.
:param asset: asset object loaded from security master
:param tenor: relative date representation of expiration date e.... | bb61c9f5d4ebd9dc6dc265ce4d4f1518fc60d49d | 3,625,990 |
import networkx
def make_cross(length=20, width=2) -> networkx.Graph:
"""Builds graph which looks like a cross.
Result graph has (2*length-width)*width vertices.
For example, this is a cross of width 3:
...
+++
+++
...+++++++++++...
...+++++++++++...
...+++++... | f0be683fd8971ea8b3cc0b40977a939c117e9906 | 3,625,991 |
def _send_cmd(obj_session, **kwargs):
"""method to send command based on the type of object """
if isinstance(obj_session, WNetwork.warrior_cli_class.WarriorCli):
result, response = obj_session._send_cmd(**kwargs)
elif isinstance(obj_session, pexpect.spawn):
wc_obj = WNetwork.warrior_cli_cl... | dc438e42180ac406aa85c73a9c303db05e9d895d | 3,625,992 |
def get_all_versions(appdir,include_partial_installs=False):
"""Get a list of all usable version directories inside the given appdir.
The list will be in order from most-recent to least-recent. The head
of the list will be the same directory as returned by get_best_version.
"""
# Find all potenti... | 2e3565a9f09734794c5e33cd379359ea07651f53 | 3,625,993 |
import itertools
def noise(nblock=None, state=None, color='white', ntaps=None):
"""Generate white noise with standard Gaussian distribution.
:param nblock: Amount of samples per block.
:param state: State of PRNG.
:type state: :class:`np.random.RandomState`
:returns: When `nblock=None`, individua... | 2186639de56646ca5ef118d4821090ce660c9612 | 3,625,994 |
def euler2SO3_left(pitch, yaw, roll):
""" Convert euler angles in degrees to a rotation matrix using XYZ order (valid)"""
cos_pitch = np.cos(pitch*np.pi/180)
sin_pitch = np.sin(pitch*np.pi/180)
cos_yaw = np.cos(yaw*np.pi/180)
sin_yaw = np.sin(yaw*np.pi/180)
cos_roll = np.cos(roll*np.pi/180)
... | 5c57836698ade9445186d88fc0009f0ea4877ed0 | 3,625,995 |
def clear_cache(query=None):
"""
clears cache in redis by query string
:param query:
:return:
"""
def search_key(q):
def wrapper(key):
if query in key:
return 1
return 0
return wrapper
is_low_cache_mem = False
is_redise = False
... | dedb0a66d7f7ba14248bf664a29a0f79566f61ab | 3,625,996 |
def get_pc_topk_shift(tensor, sparsity):
"""Input tensor must be batch of vectors.
Returns a vector per batch sample of the shift required to make Hopfield converge.
Assumes knowledge of Hopfield fixed sparsity."""
# Intuition: The output distribution must straddle the zero point to make hopfield work.
# The... | 3d4d98a36dec4294c4a0c0537794e960d690056d | 3,625,997 |
def monthly_network_triplets_per_mno_indices():
"""Index metadata for monthly_network_triplets_per_mno partitions."""
return [
IndexMetadatum(idx_cols=cols, is_unique=is_uniq, partial_sql=partial)
for cols, is_uniq, partial in [
(['triplet_hash'], True, None),
(['imei_nor... | 72a68e586d4383b7bb6c73e30cf1b5f0e245697e | 3,625,998 |
def print_table(input_dict, title='', header=('Key', 'Value'), style=('', '-')):
"""Print the dict in a table form"""
assert input_dict.__class__ is dict, "Only accept class='dict'"
if input_dict is None:
return None
max_string = 110
key_list = list(input_dict.keys())
val_list = list(ma... | 47844b6526723fbf63bc347ed1487442fc497904 | 3,625,999 |
def policy_compare(sen_a, sen_b, voting_dict):
"""
Input: last names of sen_a and sen_b, and a voting dictionary mapping senator
names to lists representing their voting records.
Output: the dot-product (as a number) representing the degree of similarity
between two senators' voting p... | d90c3c584f27979ca41bd8bff939da47a8656601 | 3,626,000 |
def _py2java(sc, obj):
""" Convert Python object into Java """
if isinstance(obj, RDD):
obj = _to_java_object_rdd(obj)
elif isinstance(obj, DataFrame):
obj = obj._jdf
elif isinstance(obj, SparkContext):
obj = obj._jsc
elif isinstance(obj, (list, tuple)):
obj = ListCon... | 4889a4ce782ee00172ee29c7ff2ac98f3fa15d8d | 3,626,001 |
def docopt_attr(doc, argv=None, help=True, version=None, options_first=False):
"""docopt with options in attributes rather than dictionary elements
args['--verbose'] => args.verbose
args['<file>'] => arg.file
All else remains the same. Attributes are single values or lists
... | 9e7d28032f5634e4a5eaa8226ca33dba2827ecbd | 3,626,002 |
def must_be_known(in_limit, out_limit):
"""
Logical combinatino of limits enforcing a known state
The logic determines that we know that the device is fully inserted or
removed, alerting the MPS if the device is stuck in an unknown state or
broken
Parameters
----------
in_limit : ``boo... | 241b66b359643d069aa4066965879bb6ac76f2ae | 3,626,004 |
def delete_item(category_id, item_id):
""" Deletes Item
:param category_id:
:param item_id:
:return: render_template
"""
if 'username' not in login_session:
return redirect('/login')
category = session.query(Category).filter_by(id=category_id).one()
item = session.query(Item).f... | 13df75535eb7dde90764baa6540caa0b18ba0c64 | 3,626,005 |
import urllib
from bs4 import BeautifulSoup
import regex
def download_floras():
"""Get the floras from the main page."""
url = SITE
path = FAMILY_DIR / 'home_page.html'
urllib.request.urlretrieve(url, path)
with open(path) as in_file:
page = in_file.read()
floras = {}
soup = Bea... | 665d5afdbd5caf2ba2a61de915a4c97228433027 | 3,626,006 |
def scale(x):
"""Scales values to [-1, 1].
**Parameters**
:x: array-like, shape = arbitrary; unscaled data
**Returns**
:x_scaled: array-like, shape = x.shape; scaled data
"""
minimum = x.min()
return 2.0 * (x - minimum) / (x.max() - minimum) - 1.0 | e5c40a4a840a1fa178a2902378a51bfefc83b368 | 3,626,007 |
def group_data_by_columns(datasets, columns):
"""
:param datasets: [CxNxSxF]
:param columns: F
:return: CxNxFxS
"""
new_dataset = []
for i in range(len(datasets)):
datalist = []
for row in range(len(datasets[i][0][0])):
row_data = []
for column_idx in ... | 8a73c959501f422c26fe358c05ddc6a574123009 | 3,626,008 |
def create_er_html(relations):
"""This function create entity-relationship html.
Args:
relations (list): List of (:class:`FieldPath` :class:`FieldPath`)
Returns:
Html str.
A way might be used is
>>> print create_structure_ers_from_relations([(FieldPath('db', 'ac', 'id'), FieldPath... | bb2392b811226c849dc9a08a596a337ea855a28d | 3,626,009 |
def plotlimit(ul, alpha=0.05, CLs=True, ax=None):
"""
plot pvalue scan for different values of a parameter of interest (observed, expected and +/- sigma bands)
Args:
ul: UpperLimit instance
alpha (float, default=0.05): significance level
CLs (bool, optional): if `True` uses pvalues ... | f1ac8459ee417dd93c219073fbc2815e7e9a5362 | 3,626,010 |
def rand_dm(N, density=0.75, pure=False, dims=None):
"""Creates a random NxN density matrix.
Parameters
----------
N : int, ndarray, list
If int, then shape of output operator. If list/ndarray then eigenvalues
of generated density matrix.
density : float
Density between [0,1... | ef91b913e4eb62f2bd7b80c27f2deabd62756c7d | 3,626,012 |
def GetStaticPipelineOptions(options_list):
"""
Takes the dictionary loaded from the yaml configuration file and returns it
in a form consistent with the others in GenerateAllPipelineOptions: a list of
(pipeline_option_name, pipeline_option_value) tuples.
The options in the options_list are a dict:
Key i... | d49effbdeb687ec62a2e2296330f66521023944c | 3,626,013 |
def ExtractNLargestBlobsn(binaryImage, numberToExtract=1):
"""Extract N largest blobs from binary image.
Arguments:
binaryImage: boolean numpy array one or several contours.
numberToExtract: number of blobs to extract (integer).
Returns:
binaryImage: boolean numpy are containing on... | 84c9643d2ed9007b346b20be3fef8bfd6103d687 | 3,626,016 |
import json
import collections
def awx_manage_check_license_data_datasource(broker):
"""
This datasource provides the not-sensitive information collected
from ``/usr/bin/awx-manage check_license --data``.
Typical content of ``/usr/bin/awx-manage check_license --data`` file is::
{"contact_ema... | 329a8de2848772b35e3a52e069912fd17a3e73ca | 3,626,017 |
def create_addresses(account_id):
"""
Create an Address on an Account
This endpoint will add an address to an account
"""
app.logger.info("Request to add an address to an account")
check_content_type("application/json")
account = Account.find_or_404(account_id)
address = Address()
a... | 07fa9df9708bf9d5fddd050cb65c3effcf2ca1b3 | 3,626,018 |
import torch
def anderson(
f, x0, m=5, max_iter=50, tol=1e-4, stop_mode='rel', lam=1e-4, beta=1.0, **kwargs
):
"""
Anderson acceleration for fixed point iteration.
Args:
f (`Callable` or `nn.Module`):
Function to be minimized.
x0 (`torch.Tensor`):
A batch of ve... | e731635b9e557f8a53f423842a956d0e33874290 | 3,626,019 |
def flip_axis(x, axis):
"""flip tensor中的对应轴
# Args
x: nd array
axis: int, axis of x
"""
x = np.asarray(x)
x = np.flip(x, axis=axis)
return x | d0085a6b1d1d3db7bd60fd953b640a380b8f70d4 | 3,626,020 |
from datetime import datetime
def beginning_of_day_utc(day_offset: int) -> datetime:
"""Return Local Midnight time of today +/- day_offset days in UTC time."""
return _apply_day_offset(
datetime.now().replace(hour=0, minute=0, second=0, microsecond=0), day_offset
).astimezone(timezone.utc) | e46a88edaff5619b6cf0d85cf3bfe8882f3ee1ca | 3,626,021 |
def fit_austourists_with_R_params(model, results_R, set_state=False):
"""
Fit the model with params as found by R's forecast package
"""
params = get_params_from_R(results_R)
with model.fix_params(dict(zip(model.param_names, params))):
fit = model.fit(disp=False)
if set_state:
s... | 4135e702ef27ec0c975d611852a0924db2493e6c | 3,626,022 |
from typing import Callable
from typing import Optional
from typing import Any
from typing import Dict
async def execute(
schema: "GraphQLSchema",
document: "DocumentNode",
response_builder: Callable,
root_value: Optional[Any],
context: Optional[Any],
variables: Optional[Dict[str, Any]],
o... | 13d63f943901d5895d4b0dd7e2f0590c7595d1c4 | 3,626,023 |
def validate_ip_addr(addr, version):
"""
Validates that an IP address is valid. Returns true if valid, false if
not. Version can be "4", "6", None for "IPv4", "IPv6", or "either"
respectively.
"""
try:
ip = netaddr.IPAddress(addr, version=version)
return True
except (netaddr.... | 938de99ed978887619463c55ce6128c1eabee0ba | 3,626,024 |
from datetime import datetime
def create_localized_datetime(*args, timezone='UTC', **kwargs):
""" Creates an aware time in the given timezone.
The intuitive way of doing this will give you the wrong answer:
https://stackoverflow.com/questions/24856643/unexpected-results-converting-timezones-in-python... | 0750455d8203ebf01699876c31bdd6993989f394 | 3,626,025 |
def resnet18(resnet_cls, **kwargs):
"""Construct a ResNet-18 model."""
return resnet_cls(block=BasicBlock, layers=[2, 2, 2, 2], **kwargs) | b66cece9f691b252d67b7547dd3c077ea3eefaf0 | 3,626,026 |
def post(host, path, data):
"""Sends POST request using HttpClient and the data from GUI form.
:param host: host ip addr
:param path: resource endpoint path
:param data: data to be sent as body of the POST request
:return: HTTP response body
"""
cover = open(data, 'rb').read()
print('Sen... | 82a11497e8d2052eea32efa946616042fb1cb997 | 3,626,029 |
import pytest
from typing import Optional
def round_trip_pathlib(writer, reader, path: Optional[str] = None):
"""
Write an object to file specified by a pathlib.Path and read it back
Parameters
----------
writer : callable bound to pandas object
IO writing function (e.g. DataFrame.to_csv ... | 742201b375f5e85a7adc485e60ca95d36e4c37e1 | 3,626,030 |
def conv_junc_to_exon():
""" Converting sorted junctions to exons here """
def overlap(start, end, start2, end2):
return not (start > end2 or end < start2)
cons_exons = []
overlaps = 0
prev_astart, prev_aend = juncs[0][-2], juncs[0][-1]
prev_jstart, prev_jend = juncs[0][2], juncs[0][3]
... | 1e98de11fa14cd0271abd6e1937e4f8bd7eb203e | 3,626,031 |
import json
from datetime import datetime
def check_temperature (device, root_dir):
"""Check the temperature status and generates files with the tests result.
Required EOS command: show system environment temperature | json
Test failure conditions: A sensor test fails if a sensor HW status is not OK or i... | 14951c63080e5d8d97eb5544b1d306d4cca39728 | 3,626,032 |
def create_folder_hierarchy(item, user, folder):
"""
Create a folder hierarchy that matches the original if the original is
under a project folder.
:param item: the item that will be moved or copied.
:param user: the user that will own the created folders.
:param folder: the destination project... | b5a7f0069fbdcd28ace8787c52963a6ae199f5e8 | 3,626,033 |
def compute_eval_metrics(gt_mask, pred_mask):
"""
Evaluate a mask w.r.t a GT mask
:param gt_mask: m x n grid of 0s and 1s
:param pred_mask: m x n grid of 0s and 1s
:return:
"""
assert (gt_mask.size == pred_mask.size)
tp = float(np.sum(np.logical_and(pred_mask == 1, gt_mask == 1)))
fp... | bce074a18835fde4532b24b8568d6b7c382bdfac | 3,626,034 |
import pickle
def load_current_test_data(collection_name="current_test_data"):
"""loads the current test data and converts it back to normal
Args:
collection_name (str, optional): name of the collection. Defaults to "current_test_data".
Returns:
List of DataFrames: List of the current te... | f929d399b75ea6ab5d2723add3eefb4b8d50c743 | 3,626,035 |
def convolutional_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)):
"""A block that has a conv layer at shortcut.
Arguments:
input_tensor: input tensor
kernel_size: default 3, the kernel size of middle conv layer at main path
filters: list of integers, the filters... | 7fafe41621aa155b8c9cb6dbccb92a09b780bc4b | 3,626,036 |
def check_type_data(data, data_type=np.ndarray, dim=2):
""" Some basic type checking on data """
# Code assumes that we have a matrix, so force it for single samples
if len(data.shape)==1:
data = data.reshape((data.size,1))
if type(data) != data_type:
raise TypeError('data is n... | 0eb9b2d958ce7b142133ecc68022b77783a418c3 | 3,626,037 |
from malaya_speech.utils import describe_availability
def available_model():
"""
List available speaker change deep models.
"""
return describe_availability(
_availability,
text='last accuracy during training session before early stopping.',
) | bbcea119f0a888720928c6c583f6652e65946d73 | 3,626,038 |
def is_date_field(field, field_schema):
""" Helper method that determines if field_schema is """
return determine_if_is_date_field(field, field_schema) | d8ffcfedcfeb1a2ca8d636be2e462522cca40acd | 3,626,039 |
def generate_script_pick_and_place_block(tcp, frames, ur_ip, ur_port, velocity = 0.05, radius = 0, vacuum_on=2, vacuum_off=5):
"""Generate multiple linear movements and Airpick on/off commands.
Parameters
----------
tcp : sequence of float
Tool center point in a form of list.
tcp = [x, ... | bfe81dd48691c44b7e42a6feaa71a766bcadc088 | 3,626,040 |
def get_ds003_downsampled(data_dir=None, url=None, resume=True, verbose=1):
"""Download and load the BIDS-fied ds003_downsampled
:param str data_dir: path of the data directory. Used to force data storage
in a non-standard location.
:param str url: download URL of the dataset. Overwrite the defaul... | d55870e661abc040bad993303c8ee60614e58371 | 3,626,042 |
def open_clean_bands(band_path,
valid_range=None,):
"""Open/mask single landsat band using a valid reflectance value range.
Parameters
-----------
band_path : string
A path to the array to be opened
valid_range : tuple (optional)
A tuple of min and max values of... | e91a8b358558d5e2f7781525a7a637e4a2b74c75 | 3,626,043 |
def _field_object_metadata(field_object):
"""Return mapping of field metadata key to value.
Args:
field_object (arcpy.Field): ArcPy field object.
Returns:
dict.
"""
meta = {"object": field_object}
key_attribute_name = {
"alias_name": "aliasName",
"base_name": "b... | 1e653737f1dee41c7ce786735368e55f4908b116 | 3,626,045 |
def svn_utf_initialize2(*args):
"""svn_utf_initialize2(svn_boolean_t assume_native_utf8, apr_pool_t pool)"""
return _core.svn_utf_initialize2(*args) | da0c3296fa6477e3a9d20669fdfd61ed5207a76d | 3,626,047 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.