content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
def _get_port_v1(port_name, depth=0, selector=None, **kwargs):
"""
Perform a GET call to retrieve data for a Port table entry
:param port_name: Alphanumeric name of the port
:param kwargs:
keyword s: requests.session object with loaded cookie jar
keyword url: URL in mai... | e6db99eda520016dd4b67f620a99a6970633eadc | 3,610,910 |
import random
def sample_with_replacement(population,len,choose=random.choice):
"""Sample from a population with replacement
Taken from Python Cookbook, 2nd ed, recipe 18.3
"""
s = []
for i in xrange(len):
s.append(choose(population))
return s | 3fe59998c19c501a5eeb26f0cc65e15ff3c1af7e | 3,610,911 |
def power_mod(val, power, m_value):
"""
Calculate power mod the efficent way
"""
if power <= 100:
return (val ** power) % m_value
if power % 2 == 0:
return (power_mod(val, power // 2, m_value) ** 2) % m_value
return (power_mod(val, power // 2, m_value) * power_mod(val, power ... | 59bb407db88e344b33571d74eef75ae0f7baa54e | 3,610,912 |
def stokes_right_circular():
"""Stokes vector for right circular polarized light."""
return np.array([1, 0, 0, 1]) | 65f1b90e9b3799026a8ec4b79543efc1ea6a472c | 3,610,913 |
def hello_http(request):
"""HTTP Cloud Function.
Args:
request (flask.Request): The request object.
<http://flask.pocoo.org/docs/0.12/api/#flask.Request>
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
<... | 60353b0d7d54a3f95bb0b8ad1b641aabbc64f03b | 3,610,914 |
def search_objects(params: dict, results: dict, meta: dict):
"""
Convert Elasticsearch results into the RPC results conforming to the
"search_objects" method
"""
post_processing = _get_post_processing(params)
objects = _get_object_data_from_search_results(results, post_processing)
ret = {
... | 9e0a7eafcd9442fc88994cbf48ce088cb249cb69 | 3,610,915 |
def encode_raw(objs):
"""
Encode a list of raw data and types to binary wire format
Useful for analyzing Protobuf messages with unknown schema
"""
return RawWire().encode(objs) | 91680c2a5fbfab11292b58d976602a56d1934d70 | 3,610,916 |
def inv_income_weighted_utility(coin_endowments, utilities):
"""Social welfare, as weighted average utility (weighted by inverse endowment).
Args:
coin_endowments (ndarray): The array of coin endowments for each of the
agents in the simulated economy.
utilities (ndarray): The array ... | 0cca315fc52b5a90867300d595a0d1c7bf6cf11c | 3,610,917 |
from datetime import datetime
def new_post():
"""
Display and handle form for creating a new blog post.
"""
form = PostForm()
if form.validate_on_submit():
post = Post(pub_date=datetime.date.today())
post.title = form.title.data
post.content = form.content.data
post... | d9f54039cce68fc850d0225c43c9593da7d4735d | 3,610,919 |
from typing import List
def _inv_shift_rows(s: List[List[bytes]]) -> List[List[bytes]]:
"""
Performs the inverted shift rows transformation as described in the standard
:param s: the state matrix
:return: the new state matrix with shifted rows
"""
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], ... | bdb593e912275bfdf387334916123830e081ed50 | 3,610,920 |
def create(dtype, key_len=None, val_len=None):
"""
Input : Example input dtype=i32:i32 will create an i32_i32 instance.
"""
k_ty, v_type = None, None
try:
splitted_words = dtype.split(':')
except AttributeError as e:
raise TypeError("dtype must be a string")
if len(splitted_words) != 2:
raise ValueErr... | a44b78f797030625252da5f48b0ebe0a31b48809 | 3,610,921 |
import io
def read(*filenames, **kwargs):
""" Read specified filenames and return contents """
enc = kwargs.get('enc', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
with io.open(filename, encoding=enc) as f:
buf.append(f.read())
return sep.join... | 9261a976cfdc1775888220001cba52aefb45efb3 | 3,610,922 |
def tile_context_feature(feat, max_sequence_size):
"""
Tile context features to max_sequence_size. Do nothing if sequence feature
Parameters
----------
feat: Tensor
Feature tensor to be tiled
Shape: [batch_size, max_len] or [batch_size, sequence_size, max_len]
max_sequence_size:... | c0eb6e12770116773e073f6d6a9f42ba0a67569c | 3,610,923 |
def conv_transpose(num_filters, kernel_size=3, activation='relu', conv_order='conv_first', use_batch_norm=True,
name=None, **conv_kwargs):
"""A composite layer for deconvolution with BatchNormalization."""
assert conv_order in ['conv_first', 'conv_last']
def inner(x):
conv_first... | 0c08edb87107b7246d3938458b96487f51045cf4 | 3,610,925 |
def get_id_character_mapping(data, columns):
"""Creating a mapping between characters and ids given dataframe.
Args:
data: dataframe that contains characters that need to be converted to ids
column: a column of the dataframe that contains characters that need to be converted to ids
columns:
... | 904a9dde05c26d2d669d16e466317379acbdeec5 | 3,610,926 |
def estimate_dimension(X, n_neighbors='auto', neighbors_estimator=None):
"""Estimate intrinsic dimensionality.
Based on "Manifold-Adaptive Dimension Estimation"
Farahmand, Szepavari, Audibert ICML 2007.
Parameters
----------
X : nd-array, shape (n_samples, n_features)
Input data.
... | bdeb2631b22f443378746f0728a8e0062e55b962 | 3,610,928 |
def start(subj, body):
"""
parse Twitter message
"""
lines = body.splitlines()
for index, line in enumerate(lines):
if line in SUBJECTS:
text = '\n'.join(lines[index + 1:])
return TITLE + line + '\n' + cut_text(text)
if DELIMETER in body:
return convert_p... | f36cfc5a6b6c1e01abc2d4077a7f6eece94cd04e | 3,610,929 |
import torch
def img_collate(imgs):
"""
Args:
imgs:
Returns:
torch.tensor, (B, 3, H, W)
"""
w = imgs[0].width
h = imgs[0].height
tensor = torch.zeros(
(len(imgs), 3, h, w), dtype=torch.uint8).contiguous()
for i, img in enumerate(imgs):
nump_array = np.a... | c6d8cc0434f4db6d70f388b99037448587b2784f | 3,610,931 |
def __args_to_weka_options(args):
"""
Function that creates list with options (args) in format
approperiate for weka.
:param args: dictionery with command line input
:return: list of command line arguments
"""
result = []
for k,v in args.items():
if v:
result.append(... | 1d480ffaf840ae67d805d7845684eef24d3da583 | 3,610,932 |
import json
def execute(
context: cli.CommandContext,
verbose: bool = False,
as_json: bool = False
) -> Response:
"""
:return:
"""
response = context.response
settings = environ.package_settings
if verbose:
data = environ.systems.get_system_data()
dat... | fee4e55b52902ccc62339687d298db2d2c635c70 | 3,610,933 |
import torch
def generate_response(tokenizer, model, chat_round, chat_history_ids, question):
"""
Generate a response to some user input.
"""
# Encode user input and End-of-String (EOS) token
new_input_ids = tokenizer.encode(">> You: "+ question + tokenizer.eos_token, return_tensors='pt')
... | 138299247b6b5b46b8999489e44676a6819e3e10 | 3,610,935 |
def gamma_closures(expressions, could_not_close=None):
"""
Try to compute gamma closure for each of expressions.
:param expressions: list of moment expressions, where each expression is a product of
powers of moments
:param could_not_close: a list that will be filled with expressions that c... | f84351a4fd0361b2f7de02707c9e3c13877d0974 | 3,610,936 |
def find_by_history(view: kvstore.View, storage: bool, key: bytes, block_number: int) -> (bytes, bytes):
"""find_by_history"""
if storage:
bucket = tables.STORAGE_HISTORY_LABEL
else:
bucket = tables.ACCOUNTS_HISTORY_LABEL
index_chunck_key = history_index.index_chunck_key(key, block_numb... | 973fe9d02ffaac30d19fbc8df83b2d98f3013dad | 3,610,937 |
def linear_coeff(x, y):
"""
This function returns the inclination coeffecient and
y axis interception coeffecient m and b.
----------
Parameters
----------
x : Output of the split vector function.
y : Output of the split vector function.
-------
Returns
-------
float numb... | d38669165af0752837a32ee0df11a4e56e57abdf | 3,610,938 |
import struct
def _package_contents_metadata(origin_label, grouping_label):
"""Named construct for helping to identify conflicting packaged contents"""
return struct(
origin = origin_label if origin_label else "<UNKNOWN>",
group = grouping_label,
) | 505776bf36740e91e1eb25470b22527af89309e2 | 3,610,939 |
import math
def str_to_feet(value="0'-0"):
"""
Returns string converted into decimal feet.
Acceptible formats include:
1. 5'-7"
5'-7 1/2"
5'-7 1/2''
5'-7
5'-7 1/2
2. 7 3/4
-8
The trailing quotation mark can b... | 3d9e17f3a900d4962ab65e5fdac3dcd44fa49399 | 3,610,940 |
from typing import Tuple
from typing import List
def deconstruct_answer(
answer_sentence: T5_SENTENCE = ''
) -> Tuple[List[T5_SENTENCE], List[str]]:
"""Gets individual answer subsentences from the compound answer sentence.
Args:
answer sentence: a T5 output sentence.
Examples:
>>> se... | c6aa7402382e71828d2146166b20ab50430416a6 | 3,610,941 |
def distance_modulus(distance):
"""Given a distance in parsecs, returns the value :math:`m - M`, a characteristic value used to convert
from apparent magnitude :math:`m` to absolute magnitude, :math:`M`.
Uses the formula from Carroll and Ostlie, where :math:`d` is in parsecs
.. math:: m - M = 5 \log_{... | 4d09231ea999a8ddaabf587cfba219b264da6442 | 3,610,942 |
def _serialize_data_asset(asset: DataAsset) -> JSON:
"""Serialize a DataAsset to JSON."""
return _serialize_asset(asset) | d1ed7dd410e9de0f70ef84ebc2da0f5afe492dea | 3,610,943 |
def behroozi10_model_dictionary(redshift=sim_defaults.default_redshift, **kwargs):
"""
Dictionary that can be passed to the `~halotools.empirical_models.SubhaloModelFactory`
to build a subhalo-based composite model using the stellar-to-halo-mass relation
published in Behroozi et al. (2010),
`arXiv:1... | c45219b650ca9e69c9a157c6b84023da92f81479 | 3,610,944 |
def detects(label=None, frac=None):
"""list of outlier detection algorithms to select from"""
algo = {'isoForest': IsolationForest(contamination=frac, random_state=42),
'MCD': EllipticEnvelope(contamination=frac),
'LOF': LocalOutlierFactor(n_neighbors=20, contamination=frac)}
return ... | aa1cad7376b25ede814df9d3f1522666a6364865 | 3,610,945 |
def zpadlist(values: list, inputtype: str, minval: int, maxval: int) -> list:
"""Return a list of zero padded strings and perform input checks.
Returns a list of zero padded strings of day numbers from a list of
input days. Invalid month numbers (e.g. outside of 1-31) will raise
an exception.
Para... | bcc06dfb36b93af69d031b44f64dfd3ee7d082c3 | 3,610,946 |
def find_backend(txt):
"""
Determine the needed background based on a text string
Parameters
----------
txt : str
name to find in the list
Returns
-------
b : :class:`~beast.physicsmodel.helpers.gridbackends.GridBackend` subclass
corresponding backend class
"""
... | 34de08e646aa1ed78eeaa666fd0926eb5cff9dcc | 3,610,947 |
def _set_health_check_defaults(health_check):
"""Sets default values for any missing attributes in HealthCheck.
These defaults need to be kept up to date with the production values in
health_check.cc
Args:
health_check: An instance of appinfo.HealthCheck or None.
Returns:
An instance of appinfo.Hea... | cb6cfb86722912cb10b316c5750a4b09601aec2e | 3,610,949 |
import math
def singular_values_plot(syslist, omega=None,
plot=True, omega_limits=None, omega_num=None,
*args, **kwargs):
"""Singular value plot for a system
Plots a Singular Value plot for the system over a (optional) frequency range.
Parameters
---... | 26db379b0f7b598d05d345edb6110f4e35485747 | 3,610,950 |
def find_spike_from_templates(recording, waveform_extractor, method='simple',
method_kwargs={}, **job_kwargs):
"""Find spike from a recording from given templates.
Parameters
----------
recording: RecordingExtractor
The recording extractor object.
waveform_extr... | a02e61d9c7ff668e0264cd50d1fe4294394cb58e | 3,610,953 |
def model_outputs() -> str:
"""
Parses the model outputs in a human readable format. It also gets the
boathouses by reach, so the user knows what boathouses are associated with
each reach.
Returns:
Rendering of the model outputs via the `model_outputs.html` template.
"""
df = latest... | 848dba8f8b29c4176bce827c2e5c831c3f534b73 | 3,610,955 |
import itertools
import copy
import logging
def check_process(process, evaluator, quick, options):
"""Check the helas calls for a process by generating the process
using all different permutations of the process legs (or, if
quick, use a subset of permutations), and check that the matrix
element is in... | a4cb209596353ebc873aab0fecc7bbc4de42fa3e | 3,610,956 |
def getFileState(fileName, workDir, jobId, ftype="output"):
""" Return the current state of a given file """
# create a temporary file state object
FS = FileState(workDir=workDir, jobId=jobId, ftype=ftype)
# update this file
state = FS.getFileState(fileName)
# cleanup
del FS
return s... | b19f193deb0a2a0268589d1f87f1f0906a778c07 | 3,610,957 |
def to_minimal_subject_jobject(subdomain, minimal_subject):
"""Converts the given MinimalSubject of Subject into an object that
can be passed to to_json()."""
subject_types = cache.SUBJECT_TYPES[subdomain]
attributes = get_attributes_to_render(subject_types)
attribute_jobjects, attribute_is = make_j... | 8d229cebf859ec26b1f4c879e20bcb7f4d841e96 | 3,610,958 |
def left_ascending_super_operator(hamiltonian, isometry, unitary):
"""
binary mera left ascending super operator
Args:
hamiltonian (tf.Tensor): hamiltonian
isometry (tf.Tensor): isometry of the binary mera
unitary (tf.Tensor): disentanlger of the mera
Returns:
tf.Tensor... | 2833b9cad67f3889c1d04a47af33544fca10170d | 3,610,959 |
def TASK_JUMP_FWD(step=1):
"""Jumps to the next task - eng.jumpCallForward()
example: A, B, TASK_JUMP_FWD(2), C, D, ...
will produce: A, B, D
@var step: int
"""
def _x(obj, eng):
eng.jumpCallForward(step)
_x.__name__ = 'TASK_JUMP_FWD'
return _x | de2bb5e71d54ea8cfcef61fa3ba687695b00315c | 3,610,960 |
from pathlib import Path
import jinja2
from functools import reduce
def __save__(
script_name: str, benchbuild: BoundCommand, experiment: 'Experiment',
projects: tp.Iterable[str]
) -> str:
"""
Dump a bash script that can be given to SLURM.
Args:
script_name (str): name of the bash script.... | c7f0628fbf293626e42a7c6b1ce288a6b1b0e577 | 3,610,961 |
def fib_iterative(n):
"""Calcualte n-th element of Fibonacci sequence. Assumes n >= 2
Returns: Fibonacci sequence up to element n, and n-th element of the seq.
"""
fibSeq = [0, 1] # base case
for ii in range(2,n): # note: list(range(2,2)) is an empty list []
fibSeq.append(fibSeq[ii-2... | f28c44bc277c8f5e97e507461f3321bc0aa0510e | 3,610,962 |
from typing import Union
from pathlib import Path
from typing import Iterable
from typing import Type
from typing import Callable
from typing import List
from typing import Any
def discover_functions(
source: Union[Path, str, Module, Iterable[Module], type],
signature: Type[Callable] = Callable, # ty... | 3169e7979cf6e138e4116e9512f5fd4583acbeee | 3,610,963 |
def bytescale(im):
"""
The input should be between [0,1]
output is [0,255] in a unsigned byte array
"""
imout = (im*255).astype('u1')
return imout | d3de7ebeb7601235c91d2ea345925ae0e11351ad | 3,610,966 |
import hashlib
def gen_md5(src_byte):
""" gen md5
:param src_byte:
:return:
"""
m2 = hashlib.md5()
m2.update(src_byte.encode("utf-8"))
return m2.hexdigest() | 3243606076735065c87c28eed473d47c6166b0b0 | 3,610,967 |
import json
def workout_map_shot(context, request):
"""
Ask for the screenshot of a map, creating one if it does not exist.
A json object is returned, containing the info for the needed screenshot
"""
if context.map_screenshot is None:
save_map_screenshot(context, request)
info = {'ur... | efd560ce96545262aa01f774a62a3352caa91f2e | 3,610,968 |
def to_string(opt):
"""Encodes the option into a string"""
entry = opt.entry
if not tosave(entry):
return False
line = ''
for key, val in entry.items():
if key in ['kid']:
continue
val = '{!r}'.format(val)
val = val.replace(assign_sym,
... | dffa69ffb4468da9704db04728fcf144fab25c21 | 3,610,970 |
from typing import List
from typing import Union
from typing import Optional
from typing import Match
import re
def search_in_comments(
comments: List[Union[str, Comment]], filter_regex: str
) -> Optional[Match[str]]:
"""
Find match in pull request description or comments.
Args:
comments: Lis... | 488723975d8d91a2796c25bd6bed12e562194c38 | 3,610,971 |
def create_local_adapter_access(mmu_access, adapter_description, adapter):
"""
Creates a local adapter access.
Parameters
------------
mmu_access : MMUAccess
The mmu access the adapters are connected to
adapter_descriptions : AdapterDescription
The adapter description
ad... | 4151336f814daad1c0357eafd6426357f0638285 | 3,610,973 |
def avro_artifacts(version = "1.8.2"):
"""
version: str = "1.8.2" - the version of avro to fetch
"""
return [
maven.artifact(
group = group_id,
artifact = artifact_id,
version = version,
)
for [group_id, artifact_id] in [AVRO, AVRO_TOOLS]
] | 0f5120fc73fa060bd3ea0291e99222fd714a3a32 | 3,610,974 |
import re
def parse(docs):
"""Parse __docs__ text into markdown. Will parse directives like `:param name:` etc"""
# strip leading tabs
if not docs:
return ""
docs = strip_leading_tabs(docs)
if ":param" in docs:
out, title_set = [], False
for line in docs.splitlines():
if ":param" in line:
if not t... | d78f2e1cac80134f65c492b7a48109c745b1ea81 | 3,610,977 |
def mergersort(arr):
"""Sort function."""
def split(arr):
if len(arr) <= 1:
return lst
mid = len(arr) // 2
left = arr[:middle]
right = arr[middle:]
left = split(left)
right = split(right)
return merge(left, right)
def merge(left, right):... | a592c75d6903c0d82feff4eda21d9136e13fe452 | 3,610,978 |
def default_interface():
"""
Return just the default interface device dictionary.
"""
parser = get_parser()
return parser.default_interface | b0e8c296e43b00d224db4e243b033957e8b380b2 | 3,610,979 |
def ape(y, p):
"""Absolute Percentage Error (APE).
Args:
y (float): target
p (float): prediction
Returns:
e (float): APE
"""
assert np.abs(y) > EPS
return np.abs(1 - p / y) | 0093cb2474b42a2dddc00577afbcc5b920bf1964 | 3,610,980 |
def new_record(score):
"""Verifie si le score peu entrer dans le top ten"""
topten = load_json('topten.json')
for index, player in enumerate(topten):
if score > player["score"]:
return index
return None | 2ea1ca763d2f60ccc668377f0c694815eb9a1e84 | 3,610,981 |
def _mean_of_cycle(data, setup_time=30, data_dict={}):
"""
Calculates mean of raw and reference signal during a zero cycle
setup_time in seconds
"""
row_selection = (data.zerocycle_runtime >= setup_time) & (data.State_Zero == 1)
cycle = data.loc[row_selection].agg(
{
"times... | 789cce42efebfa4b46b19e7be991cb1fa433ddae | 3,610,982 |
def proteinnet_tf_dataset(pn_map, batch_size, prefetch=0,
shuffle_buffer=0, repeat=True):
"""
Initiate a TensorFlow Dataset from a ProteinNetMap.
Create a TensorFlow Dataset from a ProteinNetMap, taking the output of the map and adding batching, shuffling and repeating in additio... | c277a591793e9618d3bd8ffc29b21533250ec3a1 | 3,610,983 |
import json
import requests
def post_gist(content, description="", filename="file", auth=False):
"""Post some text to a Gist, and return the URL."""
post_data = json.dumps(
{
"description": description,
"public": True,
"files": {filename: {"content": content}},
... | eddeada0d9bf04f10bc94e290a0f57912573f95b | 3,610,984 |
import functools
def lru_cache(protected: bool = False, maxsize: int = 128, typed: bool = False):
"""
Wrapped version of the functools.lru_cache decorator which
keeps track of all decorated functions to allow clearing all caches.
:param protected: if set to True, the cache for this function will only... | 2ba9ddc450d78f74d509718d6493c6aa8a5a42a5 | 3,610,985 |
def mask2rle(mask):
"""
Efficient implementation of mask2rle, from @paulorzp
img: numpy array, 1 - mask, 0 - background
Returns run length as string formated
Source: https://www.kaggle.com/xhlulu/efficient-mask2rle
"""
pixels = mask.T.flatten()
pixels = np.pad(pixels, ((1, 1), ))
ru... | 8b5feabbb73d88e7055be3cc973f6d4f517aa673 | 3,610,986 |
def CreateUniformBuffer(program, uniform_type, uniform_name, default_data=None):
""" create uniform buffer from .mat(shader) file """
uniform_classes = [
UniformBool, UniformInt, UniformUint, UniformFloat,
UniformVector2, UniformVector3, UniformVector4,
UniformBoolVector2, UniformBoolVec... | 83f5b54ec44a6a8f9100ecb1d4f390d65dea7302 | 3,610,987 |
def root():
"""Base view."""
over10 = Record.query.filter(Record.value >= 10).all()
return str(over10) | 040f7d39311c525b8356065e7cad0a4c65deb920 | 3,610,988 |
def tr_to_final_ph(stage, tr_to_ph, wind_final_perf, final_ph):
""" Computes the number of trials required to reach the final phase.
"""
time = np.where(stage == final_ph)[0] # find those trials in phase 4
reached = False
if len(time) != 0:
first_tr = np.min(time) # min trial is first tria... | 985ef980475450b62815d5daf200250bcf944798 | 3,610,990 |
def get_shannon_entropy(sequence):
"""Given a sequence, compute the Shannon Entropy, defined in
https://ijssst.info/Vol-16/No-4/data/8258a127.pdf
Args:
sequence (np.array, [t, ]): sequence over which to compute.
Returns:
float: shannon entropy.
"""
# Remove zero entries in sequ... | 9b7a66ef8c0b0d3a05c58e36f1a038471af60f59 | 3,610,991 |
def interpolate_df(x, name, fp):
"""Interpolate a dataframe
:param x: the x-coordinates at which to evaluate the interpolated values
:type x: array
:param name: the name of the column to use in the dataframe for the x-coordinate
:type name: str
:param fp: the dataframe containing the y-coordina... | a48231f4557053082658fe67c479bf31ad5b249d | 3,610,992 |
def geocoder_to_place(result):
"""Convert a result object from geocoder to a Place object"""
return Place(
name=result.address,
country=result.country,
country_code=result.country_code,
state=result.state,
description=result.description + " - " + result.class_description,... | bf0a3d5772dbbdb85c25fdd206b0b8e5c4483bfa | 3,610,993 |
def query_session_job_status(session, status, user=None):
"""
:type session: Session
:type user: User
"""
session = Session.objects.with_id(session)
if not session:
return None, HTTPStatus.NOT_FOUND
if status not in ['success', 'started', 'dispatched', 'ready', 'failure', 'created']... | 3ccc3de65dc834e837c46bea3c6465b8df45c4b6 | 3,610,994 |
def replace_string_newline(str_start: str, str_end: str, text: str) -> str:
"""
re.sub function stops at newline characters, but this function moves past these
params: str_start, the start character of the string to be delted
str_end, the end character of the string to be deleted
te... | c2f4888ed285dc6a48b6a839ff62dbe50865472c | 3,610,995 |
def convert_cell(ase_cell):
"""
Convert a parallelepiped (forming right hand basis)
to lower triangular matrix LAMMPS can accept. This
function transposes cell matrix so the bases are column vectors
"""
cell = ase_cell.T
if not is_upper_triangular(cell):
tri_mat = np.zeros((3, 3))
... | e3272d91517979cfb0be1be0a158f359c88c278e | 3,610,996 |
def header_required(response, name, callback=do_nothing):
"""Checks that a specific header is in a headers dictionary.
Args:
response (object): An HTTP response object, expected to have a
``headers`` attribute that is a ``Mapping[str, str]``.
name (str): The name of a required heade... | 6454b2e201114051a85da5e3142030d46ec88130 | 3,610,997 |
def test_node_catchup_when_3_not_primary_node_restarted(
looper, txnPoolNodeSet, tdir, tconf,
allPluginsPath, steward1, stewardWallet):
"""
Test case:
1. Create pool of 4 nodes
2. Stop not primary node
3. Send some txns
4. Start stopped node
5. Ensure, that restarted node go... | ea3eb0a7ce7ec9dd81c753193a12d572fe03aeb6 | 3,610,998 |
def get_model(point_cloud, is_training, num_class, bn_decay=None):
""" Semantic segmentation PointNet, input is BxNx3, output Bxnum_class """
if isinstance(num_class, int):
num_class = [num_class]
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_... | 751d27dddab1948a0cba2bf9bcf89ad7a13f4b2e | 3,610,999 |
def get_internal_weights(model):
"""Get all weights of a model without Wrapper specific weights.
Args:
model (keras.models.Model): wrapped model
Returns:
internal layer weights
"""
weights = []
for layer in model.layers:
if isinstance(layer, PruningWrapper):
weig... | c95f25221a93b26b03bc34e42f7da624a50650c1 | 3,611,000 |
from datetime import datetime
def get_visit_date(fecha_inicio):
"""
:param fecha_inicio:
:return: date string YYYY-mm-dd
"""
if not fecha_inicio.strip():
return ""
try:
date_obj = datetime.strptime(fecha_inicio, "%m/%d/%y %H:%M %p")
except ValueError:
try:
... | a64f739b471e5c7d4f9bd20812e7670c6b679845 | 3,611,001 |
import re
def text_normalize(text):
"""
Normalize Vietnamese accents
"""
text = re.sub(r"òa", "oà", text)
text = re.sub(r"óa", "oá", text)
text = re.sub(r"ỏa", "oả", text)
text = re.sub(r"õa", "oã", text)
text = re.sub(r"ọa", "oạ", text)
text = re.sub(r"òe", "oè", text)
text = ... | 840aef0f8412d52b71a89c7803f46488883d45b9 | 3,611,002 |
from datetime import datetime
def from_iso8601(s):
""" convert iso8601 string to datetime object.
refer to http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
for details.
:param str s: time in ISO-8601
:rtype: datetime.datetime
"""
m = _iso8601_fmt.match(s)
if not m:
... | ff3357035bb4eab0111febcf02a438a0e965a8c4 | 3,611,003 |
def _ExtStorageEnvironment(unique_id, ext_params,
size=None, grow=None, metadata=None,
name=None, uuid=None,
snap_name=None, snap_size=None,
exclusive=None):
"""Calculate the environment for an External Storage... | 323c9fae9e6cbc1c1a107dd018bbe5f95520a8fe | 3,611,004 |
import types
async def process_invoise_invalid(message: types.Message):
"""
If invoise is invalid
"""
return await message.reply("Номер заказа должен быть цифровой.\nВведите последние 5 цифр заказа:") | a72758c137ceaceb17db7114c231ef5d98f63850 | 3,611,005 |
def g(i, k, l):
"""
Stage cost. Please check page 384 and page 385 of [1].
:param i: state
:param k: control
:param l: switching
:return: the cost
"""
n = 9
m = 4
X = inverse_map(i, n)
U = inverse_map(k, m)
A = [-28, -12, 12, 16, 0, 0, 0, 20, 16]
B = [-8, 40, 20, 40]... | a0f58aea9bc8b2722ee7973d4bb57e260367dd8f | 3,611,006 |
import tqdm
import scipy
def fit_predict_update(clf, X_train, X_tests,
y_train, y_tests, t_train, t_tests,
fit_function=None, predict_function=None,
rebalancers=(), rejectors=(), selectors=()):
"""Sliding window classification of a timestamp par... | 5170a800d289342909e1aec56e8139534229c06d | 3,611,007 |
import time
def is_expired(epoch_time):
"""True if current time has passed the provided epoch_time"""
return time.time() > epoch_time | b264fd1d73fe7f9c97592e6bffc27c81574d6bde | 3,611,008 |
import scipy
def _assembleInit(xdata, ydata, bounds=None):
"""assemble the initial values based on the spectrum"""
#INTITIALIZE VARIABLES
init = scipy.zeros((3*len(semiEmperical)+1,))
output = scipy.zeros((len(init), 2))
ones = scipy.ones(semiEmperical.shape)
#set baseline
init[0] = ... | 64989a0df41a7d29028674b8e7663944769ae8a0 | 3,611,009 |
def strtobool(val: str) -> bool:
"""Convert a string representation of truth to True or False.
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
if not isinstance(val, str):
... | edf32dd502abe2058ad43deff91cd722509bb1d0 | 3,611,010 |
from statsmodels.stats.multitest import multipletests
def programs2go(program2gene_dict,organism="hsapiens",fdr=0.1):
"""Get GO terms for programs.
... | 16a23c80216539848b5f87b2e3e1a5bddeef2a88 | 3,611,012 |
import hashlib
import re
import regex
def api_string_search_choices(request, slug):
"""Return valid choices for a string search given other search criteria.
This is a PRIVATE API.
Return all valid choices for a given string search slug given the partial
search value entered for that slug, its q-type... | f94136660e8bd3f57044b2d0c985b48e3453e3bd | 3,611,013 |
def get_screensaver_running_status():
""" Get the status of the running screensaver. """
screensaver = {
'name': 'screensaver_status'
}
is_screensaver_running = False
try:
is_screensaver_running = checkPidRunning(int(get_pid("xautolock")))
except:
screensaver['full_text'... | 5012403025e1b4c5ebbc076f9792eecc11c3a889 | 3,611,014 |
def position_extrapolate(dist_1_coords, dist_2_coords, delta_heading, delta_distance):
"""
update pdr predictions based on extrapolating last SfM position and direction
:param dist_1_coords: sfm point immediately preceding or following (distance = 1)
:param dist_2_coords: sfm point next to dist_1_coord... | de4ed0e788a14204c993aaeee01978ff8e6453f4 | 3,611,015 |
def detect_nose(cv_image):
"""Detects nose based on haar. Returns ponts"""
return NOSE_HAAR.detectMultiScale(cvimage_grayscale(cv_image)) | 0b3c8fa78a9897374b06f89c5479982a9105db04 | 3,611,016 |
import token
def cvt_try_stmt(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base:
"""
try_stmt: ('try' ':' suite
((except_clause ':' suite)+
['else' ':' suite]
['finally' ':' suite] |
'finally' ':' suite))
"""
#-# Try(stmt* body, excepthandler... | d7cd6998d3014d3c001ae5b995b88632c562f1e5 | 3,611,017 |
from datetime import datetime
def get_date_tag(date_format: str = DATE_FORMAT) -> str:
"""Returns a date string tag according to the DATE_FORMAT specifier,
e.g. '2019-04-01'"""
return datetime.now().strftime(date_format) | cff2c9131323ef7458754b7a67caa99acc435c03 | 3,611,018 |
def translate(image, dx, dy, **kwargs):
"""
Shift image horizontally and vertically
>>> image = np.eye(3, dtype='uint8') * 255
>>> translate(image, 2, 1)
array([[ 0, 0, 0],
[ 0, 0, 255],
[ 0, 0, 0]], dtype=uint8)
:param numpy array image: Numpy array with ran... | f7abec87f1bb656e256485c2198891f0c967c2b5 | 3,611,019 |
def stations_by_river(stations, river):
"""Takes a list of stations and returns a list of all the station names
on a specific river in alphabetic order"""
station_names = []
for station in stations:
if station.river == river:
station_names.append(station.name)
station_names = sor... | 078e83affc54b90f2a58ad46cefdd895d9f8c1e6 | 3,611,020 |
def read_career_info(carrera_id, test=False):
"""Consulta la información de una carrera según su código."""
query = 'SELECT * FROM carrera WHERE id = %s'
return execute_sql(query, args=[carrera_id], rows=1, test=test) | 6a89cd194a65d22b647313836b20d9a8db3e4f39 | 3,611,021 |
def get_atomic_species_card(name, **kwargs):
"""
Convert XML data to ATOMIC_SPECIES card
:param name: Card name
:param kwargs: Dictionary with converted data from XML file
:return: List of strings
"""
try:
atomic_species = kwargs['atomic_species']
species = atomic_species['s... | d10950bb03d1ef5a26b065eb5f8cb928b52bda32 | 3,611,022 |
from typing import Tuple
import requests
import json
import logging
def _get_document_pdf(data: dict, data_key: str, token: str, config: BaseConfig) -> Tuple[bytes, HTTPStatus]:
"""Retrieve the document pdf from the Reports API.
Args:
data: The data to send to the API.
token: The token to acc... | 4d7315bf8177e40644e1be1c5fc7feec7d9f23d3 | 3,611,023 |
def is_url(arg):
"""输入是一个字符串,且值是一个合法的url"""
if not isinstance(arg, str): return False
try:
result = urlparse(arg)
return all([result.scheme, result.netloc])
except ValueError:
return False | e5800b46116de8f7a9cd742ad448ecdc9d72eb84 | 3,611,024 |
def run_hybrid(wf, selector, workers):
"""
Returns the result of evaluating the workflow; runs through several
supplied workers in as many threads.
:param wf:
Workflow to compute
:type wf: :py:class:`Workflow` or :py:class:`PromisedObject`
:param selector:
A function selecting ... | b18d7a74fda52fb625680eb178de11f023878c25 | 3,611,025 |
def getCompartment(rxn):
"""
This function is used to obtain the compartment information from reaction of yeastGEM
:param rxn: example acetyl-CoA[m] + L-glutamate[m] -> coenzyme A[m] + H+[m] + N-acetyl-L-glutamate[m]'
:return:
"""
cp1 = ['[c]','[ce]','[e]','[er]','[erm]','[g]','[gm]','[lp]','[... | 2bb34ca20df1a82c6cffcf0c46728fc1687e6db9 | 3,611,026 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.