content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def channel_is_size(channel):
"""Checks if a channel is of set size (see: /setsize handler)"""
channel_number = bot.get_chat_members_count(channel)
if channel_number >= min_channel_size:
return True
else:
return False | 33b0e71bbc24b400a5ef759efb1e783707deacfc | 3,612,400 |
def factorial(n):
"""
Calculate n!
Args:
n(int): factorial to be computed
Returns:
n!
"""
if n == 0:
return 1 # by definition of 0!
return n * factorial(n-1) | a0e8e6edbf03bb1fb1e6a11d7ace41e37992b54f | 3,612,401 |
def discover(scan_attempts=10, scan_interval=1):
"""Creates a Harmony client and initializes session.
Args:
scan_attempts (int): Number of times to scan the network
scan_interval (int): Seconds between running each network scan
Returns:
A list of Hub devices found and their configs... | 1b8fd49732260f942e5008b696cfd173f3469d2e | 3,612,402 |
import array
def get_nodal_averaged_stress(model, eid_to_nid_map, isubcase, options=None):
"""
Supports:
- plateStress
- solidStress
- compositePlateStress (NA)
options = {
'mode': 'derive/avg', # derive/avg, avg/derive
'layers' : 'max', # max, min, avg
#'ilayers'... | 8c197733169851c6e634cd9d69213746721f43fe | 3,612,403 |
import re
def getMonetaryQuantityQuantUnit(words):
"""
from training data:
count perc cum_sum cum_perc
kind_c
dollar 133 60.454545 133 60.454545
yuan 36 16.363636 169 76.818182
euro 23 10.454545 192 87.27... | 406a21ea1fb7617a93fbc656b3cb85ac449efba7 | 3,612,404 |
import os
def filter_python_model_benchmark_suite(device_info,
root_build_dir,
verbose=False):
"""Filters Python model benchmark suite for the given CPU/GPU target.
Args:
- device_info: an AndroidDeviceInfo object.
- root_build_d... | faecda77ba7e4844f84b22cbc41a194a0eacbdf0 | 3,612,405 |
def get_env_config(config_type: str, config_set: str, dist_name: str = None) -> dict:
"""Function for drawing some built-in configuration dictionaries
:param config_type: Type of configuration to draw.
:param config_set: Which set to draw from.
:param dist_name: Name of the distribution within a set.
... | b8f1c52b089543e1b02b534ef5ab60d1fb050753 | 3,612,406 |
from twisted.internet import defer, reactor
from invoke.tasks import Task, task as task_decoracor
def task_on_callbacks(*task_args, **task_kwargs):
"""
A proxy for ``invoke.tasks.task`` parameterized decorator.
"""
def decorator(function):
"""
A decorator which wraps original Deferred... | 181b64245cb9e4c6c8bcdad40e4e40b2e448d91d | 3,612,407 |
from typing import Sequence
from typing import Optional
from typing import Tuple
def traj_loss_antithetic_es(
p_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
n_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
vec_pos: MetaParams,
std: float,
loss_type: str,
clip_loss_diff: Optio... | c662848702066ec6f6f95d9e0e67317d9e6fd435 | 3,612,408 |
import numpy
def compareMentorsAndTeams(mentor_sch, team_sch):
"""
Teams can only meet with the mentors when the mentors are available, so
for each mentor multiply the 0..1 mentor value against the team team
availability count to use the mentor schedule as a mask over the team
schedule.
We co... | cd500c6354af616523e5842770e256be9638e19e | 3,612,409 |
def get_word_count(text, keywords):
"""
Args:
text (str):
keywords (list):
Returns:
"""
count_dict = {}
for keyword in keywords:
count_dict[keyword] = text.count(keyword)
return count_dict | eaf5258b07cb861c2cce8c55ede2342aaf141f8d | 3,612,410 |
import re
def handle_special_operator(formula, operator):
"""
如果有 "*-", "-*", "/-", "-/" 这些运算符,
提取负号,去掉重复的运算符
:param formula:
:param operator:
:return:
"""
temp = ""
regex = "\d*[.]?\d+"
opera = operator.replace("*", "[*]")
ret = re.compile(opera.join([regex, reg... | c9e4795d4ccb07549d12e13d2f7050036f018e45 | 3,612,411 |
import copy
def cosmicmed(data, sigma=1.5):
"""
Precise cosmic ray elimination for measurements of the same point or very
similar spectras.
:type data: list[float]
:param data: List of spectras to remove cosmic rays.
:type sigma: float
:param sigma: Factor to modify the criteria to i... | b9212779a49d01c2c2168bb3a421b14c1d3a7504 | 3,612,412 |
import subprocess
def ditto(src, dest, norsrc=False):
""" Copies a file or directory tree from src path to dest path
src: source path as string
dest: destination path as string
norsrc: (bool) if True, uses --norsrc flag with ditto so it will not copy
resource fork or exte... | 7a1fa06c87b3a1692cacd1d2a274bbaa83331e17 | 3,612,413 |
from typing import Any
def schema(
var_name: str,
data_type: Any,
) -> str:
"""Returns a YAML-like string for our data type; these are used for
pretty-printing and comparison between the OpenAPI type
definitions and these Python data types, as part of
schema is a glorified repr of a data type... | 20fc1a642c4543e9b520aa08d0312deca5349377 | 3,612,414 |
def get_user(username=None, email=None, apikey=None):
"""Return the user for the given username, email or apikey.
Return None if no such user.
"""
if username:
rows = flask.g.db.view("users", "username",
key=username.lower(), include_docs=True)
elif email:
... | 7ef19acf5f4274c51d7966756add31049ef154a5 | 3,612,415 |
def resolveVarStrDashMuts(varStr):
"""If there is a sequence of mutations like T28144- followed by -28144C, get rid of the T>-
and replace the ->C with T>C. Get rid of solo basePos- because they can occur in very long
lists when samples have long stretches of Ns, not helpful."""
if (not varStr):
... | 3ee09c6191f6ae361d6b309395292bb09447f0dd | 3,612,416 |
import re
def get_urls(text):
"""Extract urls from text.
Parameters
----------
text : text that contains url(s)
Returns
-------
links : a list of Links of urls in the text.
"""
# URL
URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|m... | 14ac292ca6d4cabc515201152051734bc66e852e | 3,612,417 |
def get_fund_id():
"""
Use this function when you want to find the fund_id using the fund name.
Returns
-------
fund_id: string
The CNPJ of the fund, that is the brazilian tax id and used in this
script as fund_id.
"""
funds = pd.read_sql("SELECT DISTINCT denom_social FROM... | b38214d2ab2bb7c740c8d365cd9420d9487ebe91 | 3,612,418 |
import json
def readJson(filename):
"""
Returns a list of all the objects in the .json set
"""
with open(filename, 'r') as f:
data = json.load(f)
info = str(data)
info.split(":")
keys = []
for i in data:
keys.append(i)
obj = []
for i in keys:
obj.append(... | 79e8f1ce74594ca215c490a7447fea9974c296a0 | 3,612,419 |
from typing import Any
async def game_over(_: models.User = Depends(dependencies.get_current_user)) -> Any:
"""
User completed answering all questions.
"""
await LOGGER.info("User completed answering all questions")
return {"message": "Congratulations, you have answered all questions!"} | bb723f684a727536e3118366ec85b932385066c4 | 3,612,420 |
def convert_categorical(categorical):
"""
"""
cat = categorical.copy()
is_gridslice = '{' in cat.name
if is_gridslice:
resp_prefix = cat.name.split('[{')[0] + 'a'
else:
resp_prefix = categorical.name + 'a'
if not cat.dtype == 'object':
cat = cat.apply(lambda x:
... | c227b3822f69dbc8cb64fee8f1a2eaa15370748c | 3,612,421 |
import copy
def make(model):
"""Create a new model to avoid overwriting the global variable."""
return copy.copy(model) if isinstance(model, Forward) else Backward(model) | d4cdb6b4eef38de843e6d928dec47b767b3e2493 | 3,612,422 |
import torch
def aggregate_mean(h):
"""mean aggregation"""
return torch.mean(h, dim=1) | c897e4c36f2ba6fc9719cc8d7437086970886085 | 3,612,423 |
def rm2v(r):
"""
Wrapper for ERFA function ``eraRm2v``.
Parameters
----------
r : double array
Returns
-------
w : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - -
e r a R m 2 v
- - - - - - - -
Express an r-matrix as an r-vector.... | 1506fa459f61241094ca86a42ce25b2e9d737d94 | 3,612,424 |
from re import T
def get_conv_torch(mask):
""" Get 2d torch convolution with mask """
in_chan, out_chan = 1, 1
shape = mask.shape
l = T.nn.Conv3d(in_chan, out_chan, shape
, stride=shape
, padding=0
, bias = False
... | f3a646041b8f403cee0f5dbb2a9726f29b00f150 | 3,612,425 |
from typing import List
def prepare_electrodes_positions(
configuration: str, n_sites: int = 384
) -> List[ActiveElectrode]:
"""
Defines the position along the probe (in coordinates from the first electrode)
of each active electrode
"""
if configuration == "b0":
Y = 20 * np.rep... | 8bb4b4d29d8e751e205ce05598f7d0a9eda9faae | 3,612,426 |
def player_exists(selected_id: str, already_taken_ids: list = []):
"""Verifies if the player selected by the user exists.
Args:
selected_id (str): Player chosen by the user.
already_taken_ids (list, optional): List of ids the user cannot choose from. Defaults to [].
Returns:
bool: ... | df7cde112742db1a20ca3f325f848eef41367bac | 3,612,427 |
def subspace(P, k, precision, mode):
"""
Computes isometries `V1` and `V2` respectively mapping into the column and
null space of a rank-`k` projection matrix `P`.
Args:
P: The input matrix, expected to be a projector as described in the
docstring.
k: The rank of `P`.
precision: The matmul p... | eb63ec26f15d5d8d6be785093c35ad4aba23f9b9 | 3,612,428 |
def combine_results(partitions, destination_dict):
"""
Combines partitioned results into single csv file
:param partitions: list containing aws partition addresses
:param destination_dict: folder where results are saved
"""
df = pd.DataFrame()
for part_id in partitions:
partial_df = ... | 472e033480011ef0ecd29e59843e9303aa84599f | 3,612,429 |
import os
def dev_tree65432(runid, config, dir, dir2, dir3, dir4, dir5, dir6):
"""
recursive list the file structure of the working directory
"""
wd = os.path.abspath(get_wd(runid))
dir = os.path.abspath(_join(wd, dir, dir2, dir3, dir4, dir5, dir6))
assert dir.startswith(wd)
return browse_... | e349f69bee3e4a97af8c6daa7e3cf81abf7cd3d3 | 3,612,430 |
def make_prediction(*, input_data: t.Union[pd.DataFrame, dict],) -> dict:
"""Make prediction using a saved model pipeline."""
# load trained model from local storage
pipeline_file_name = f'{config.PIPELINE_SAVE_FILE}{_version}.pkl'
_price_pipe = load_pipeline(file_name=pipeline_file_name)
# valida... | 7bf0c52635525b35cb43295e5e632b5d4d1beb54 | 3,612,431 |
def getdaydate(Occurrence: str = 'Second', DayOfWeek: str = 'Tuesday', Month: int = date.today().month, Year: int = date.today().year):
"""
Overivew:
return the date for occurrence of a day of the week
Description:
function returns the date for a giving day of the week and occurrence of givi... | 75a1b4ed52b46a3f5414d5ff04166c45e0b206c0 | 3,612,432 |
from typing import Match
def equalsOp(template, rule, propertyList):
""" Process EQUALS operators """
matches = []
for prop in propertyList:
actualValue = getProperty(prop, rule)
if actualValue.strip() != str(rule.value).strip():
path = prop['Path']
path = path + r... | 659b55db4a12ab362afae13b7c895ee2830ad528 | 3,612,433 |
def scaling_factor(context, ruler, rulerWidth):
"""
:type context: HackedContext
"""
rulerElement = context.driver.simple_find(ruler)
rulerPixels = rulerElement.size['width']
scaleFactor = float(rulerPixels) / float(rulerWidth)
return scaleFactor | 5af9410879566b36a7a4d734c633d62cdcbddb7e | 3,612,434 |
import argparse
def parse_args(args):
"""Parse command line parameters"""
parser = argparse.ArgumentParser(
description="Test utility for the command line",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-v",
"--version",
action... | 18f8340815d091c5d9ab38a8b6fd47f64c0e8359 | 3,612,435 |
def to_bytes(string, encoding="utf-8"):
"""
Converts the given object to binary object, bytes (Py3) or str (Py2).
:param string: The string like object to convert to bytes
:type string: ``object``
:param encoding: The encoding to encode the string with.
:type encoding: ``str``
:returns: The... | 0285af78a56997994d3613322897be728f17ec0d | 3,612,436 |
def makeVBClass(cls, init=None):
"""Returns the text of a VB class file wrapping the specified class
If provided, then the init parameter is used as the initializer for the class
so that you can link to the real Python object
"""
vb = [] # Build up as list and then .join it later
#
# Get t... | a773665ebe2a5d67e350ecd2a90cbe5a93bfe514 | 3,612,437 |
from ooiservices.app.uframe.status_tools import get_uid_digests, uid_digests_cache_update
def new_compile_assets(data, compile_all=False):
""" Process list of asset dictionaries from uframe; transform into (ooi-ui-services) list of asset dictionaries.
"""
info = False # Log missing vocab it... | 6540b1ba7568fc72c65d124cf0c03c01b21f0d8f | 3,612,438 |
def quat_delta(dalpha):
""" Form quaternion from small angle rotation vector dalpha """
half_norm = 0.5 * norm(dalpha)
scalar = cos(half_norm)
vector = sinc(half_norm) * 0.5 * dalpha
dqw = scalar
dqx, dqy, dqz = vector
dq = np.array([dqw, dqx, dqy, dqz])
return dq | 37c09c6a141db169f479ed9f98e8537ba72d3bf9 | 3,612,439 |
def cluster_main_stats(sparkdf, src="src", dst="dst", cluster_id_colname="cluster_id"):
"""calculate diameter / transitivity(GCC) / triangle clustering coefficient LCC / square clustering coeff
Args:
sparkdf: imput edgelist Spark DataFrame
src: src column name
dst: dst c... | 60d006d6a9a58442dd072dea67e853b98d0f2a18 | 3,612,440 |
def markers(
image: Image,
*,
kernel_length: int = 5,
blur_kernel_size: int = 9,
threshold_value: float = 150,
num_iterations: int = 4,
debug: bool = False
) -> tp.List[np.ndarray]:
"""Return the contours of the black square markers."""
# cv2.imwrite("foo.png", image.image)
# as... | a6d96f8b9a23274edabfa71c60bb6b918cdaf36a | 3,612,441 |
import os
def clone_remote_db(conn):
"""
Copy remote data (JSON dump), download it locally and recreate a local
SQLite database with those data.
"""
local = Context()
db_name = settings.DATABASES['default']['NAME']
is_sqlite = 'sqlite' in settings.DATABASES['default']['ENGINE']
def ex... | 0ffda37296ff09f478aaf2b9817be33449656e1c | 3,612,442 |
from tensorflow.keras.models import load_model, Model
def build_keras_model_front_v2(path_to_keras_model, idx_to_target_w = -1):
"""
idx_to_target_w = to which layer (default = -1 (the last one)) - 1
"""
idx = 0
loaded_model = load_model(path_to_keras_model)
front_layers = loaded_model.layers[:idx_to_target_w... | 195339116ae3137fbd26f52d3adf48ea857e030e | 3,612,443 |
def center_margin_bb(bb, img_bounds, margin=0.25):
"""create new bounding box with input margin"""
bb_size = ([bb[0, 2] - bb[0, 0], bb[0, 3] - bb[0, 1]])
margins = (np.max(bb_size) * (1 + margin) - bb_size) / 2
bb_new = np.zeros_like(bb)
bb_new[0, 0] = np.maximum(bb[0, 0] - margins[0], 0)
bb_ne... | 03c1f1fe5200bc0a57ee777acc9a065ccb73a5dd | 3,612,444 |
def multi_fidelity_optimize(
vocs, evaluate_f, budget=1, processes=1, base_cost=1.0, **kwargs
):
"""
Multi-fidelity optimization using Bayesian optimization
This optimization algorithm attempts to reduce the computational cost of
optimizing a scalar function through the use of many low-cost approxi... | ce431c258204ebcf916f65218c5b0c9c1cbe0707 | 3,612,445 |
import sys
import os
import yaml
from datetime import datetime
def downloadDatabase(database_name, alignment_choice, output_dir, reference_dir = "."):
"""
Automatically downloads a peptide database for use with EUKulele and
stores the name of the resulting FASTA file and taxonomy table.
"""
print... | dd6699c8284606e72b8b6ea0c7f8f4465562a88a | 3,612,446 |
def finalize_columns(points):
"""Finalize column names and contents."""
# Calculate how many people each point represents.
count_by_zip_crid = points.groupby('ZIP_CRID').count()['TOT_CNT']
points['max_points_by_zip_crid'] = points['ZIP_CRID'].apply(
lambda x: count_by_zip_crid.loc[x]
)
... | bef2af609fc57c064c4ad016f0c9df33cdefeea1 | 3,612,447 |
def unique_filename(filename, upload_id):
"""Replace filename with upload_id, preserving file extension if any.
Args:
filename (str): Original filename
upload_id (str): Unique upload ID
Returns:
str: An upload_id based filename
"""
if "." in filename:
return "."... | 04602532627d8557436c27f2e7d8165f638ed155 | 3,612,448 |
def parse_object(*args):
"""
将查询到的结果转换为需要的结构
:param args:
:return:
"""
results = []
for cond in args:
result = {'OPEN_ID': cond.OPEN_ID,
'OBJECT_ID': cond.OBJECT_ID,
'OBJECT_NAME': cond.OBJECT_NAME,
'OBJECT_CLASS': cond.OBJECT_CLA... | be4bd26cca7dd50ed7ba66d814c0d3326d42ab73 | 3,612,449 |
def filter_ec2(tagName, ec2Name, env):
"""Filter EC2 Instances by Tag"""
ec2_list = []
ec2 = boto3.client('ec2', region_name=env.get('region'))
instances = ec2.describe_instances(
Filters=[
{
'Name': tagName,
'Values': [ec2Name]
}
]... | 17f084b8c65b1ed0844cce939e2356e377c880a2 | 3,612,450 |
def do_roll(u):
""" Actually do a 'roll' and updating global (secret) z """
global z
z = [update(val) for val in z]
r = [(((z[i] - 1) * x_coe[i] + u[i]) % 14) + 1 for i in range(NUM_CARDS)]
return r | 0ba2e23befc99efc1d9ca1a0337e868800d3b857 | 3,612,451 |
def pseudo_nm_tmatrix(markovian_tmatrix, stateA, stateB):
"""Obtain a pseudo non-Markovian transition matrix from a Markovian transiton matrix
The pseudo Markovian matrix has a shape of (2 n_states, 2 n_states)
"""
check_tmatrix(markovian_tmatrix)
n_states = len(markovian_tmatrix)
# pseudo no... | 4ac69b686694b822127d2a989b47e1d993f35122 | 3,612,452 |
def translate(img, x, y):
"""
Translates the given image.
:param x: distance to translate in the positive x-direction
:param y: distance to translate in the positive y-direction
:returns: the translated image as an numpy array
"""
M = np.float32([[1, 0, x], [0, 1, y]])
return cv2.warpAffine(img.reshape(28,28),... | 4209839032d8b0b2dce9557c0ad1b1a5b9317df2 | 3,612,453 |
def get_parent(graph, loc=None, exp=None, attr=None):
"""
Query syntax at start of expression: ..
Selects the parent of the current node
:param graph: (sub)graph instance to search
:param loc: path location identifier
:type loc: :py:str
:param exp: expression to query for in... | 3ab6ed2775feec96c9a14c7036609a10e3c59bd1 | 3,612,454 |
import time
def took(func):
"""
A decorator that will print how long a function was running
to the debug output. This is useful for measuring performance
in production.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
... | 954ae84a84c7c945cbf4fafc7162c05d629dce25 | 3,612,455 |
def htmlstriptags(*args):
"""
.. function:: htmlstriptags(str, default_tag_conversion)
Strips the html tags of input. It also converts "<br>" tags to new lines. If a default_tag_conversion is provided
then tags that would have been erased are converted to *default_tag_conversion*.
Examples:
>... | ed38d269f53a4665ab2f8983958f5ba5b787a87f | 3,612,456 |
def rtc_runner(rtc):
"""
:type rtc: pbcommand.models.ResolvedToolContract
:return:
"""
return gather_run_main(chunk_json=rtc.task.input_files[0],
chunk_key=Constants.CHUNK_KEY,
gathered_fn=rtc.task.output_files[0],
ln_n... | 04aacffbabf99befd67ff80c0e27e531dacb50ae | 3,612,457 |
from typing import Iterable
def check_and_prepare_sources(source):
"""
Check source type and return source(s) as a list
:param source:
single source or list of sources
:return:
list of sources based on provided source(s)
"""
source_ok = True
if isinstance(source, Iterable)... | c7f2a104c2eca06040a0d67304170b9433247655 | 3,612,458 |
import ctypes
def streamBurst(handle, numAddresses, aScanList, scanRate, numScans):
"""Initializes a stream burst and collects data. This function
combines eStreamStart, eStreamRead, and eStreamStop, as well as
some other device initialization.
Args:
handle: A valid handle to an open device.
... | 495f34a89a54b5e69e428b29169f96f005f0740f | 3,612,459 |
import traceback
import requests
def get_server_logs(hostname, instance_id):
"""
Get server logs for specified host and instance.
"""
host = get_host_by_hostname(hostname)
if not host:
return None
if host['uri']:
try:
r = requests.get("%s/servers/%s/logs" % (host['... | b76777d90d01963bc8c67885cf9411a12428648a | 3,612,460 |
def __to_pplot(p):
"""
Change Particle to pplot so that crossing 0-degree line can be plotted.
Parameters
----------
p: Particle
A given Lagrangian particle.
Returns
-------
re: tuple of particle and cross0
Particle after LON being modified and whether it crosses 0-degr... | ad343758e137cf6e6b3bd9ec8264c4833857807f | 3,612,461 |
def ror (endv, iv):
""" This capital budgeting function computes the rate of
return on an investment for one period only.
iv = initial investment value
endv = total value at the end of the period
Example: ror(100000, 129,500)
"""
return (endv - iv)/iv | 43a1339d45725a5e04fd809a6cfb708b6b49b829 | 3,612,462 |
import torch
def cov(x):
"""
https://en.wikipedia.org/wiki/Covariance_matrix
"""
E_x = x.mean(dim=1)
x = x - E_x[:, None]
return torch.mm(x, x.T) / (x.size(1) - 1) | ff4c5d3f90569f8c1a2d9a1ea9679079fb72b681 | 3,612,463 |
def ParseOptions(argv,
docstring,
extra_opts="", extra_long_opts=(),
extra_option_handler=None):
"""Parse the options in argv and return any arguments that aren't
flags. docstring is the calling module's docstring, to be displayed
for errors and -h. extra_opts ... | dc0f5574f2ba4d442cbbaca702f14b3ca1d90668 | 3,612,464 |
import os
import sys
import re
from datetime import datetime
import requests
def get_exportlog(site, save_dir=os.getcwd(), only_if_newer=False, country_code='GRC'):
""" Download the latest available M3G igs log file for a given station.
The input 'site' parameter should be the site's 9-char-id (aka the
... | 9d20ea6fcec7e6d81bfa176a693f7de9e2c1abdd | 3,612,465 |
import os
def load_housing_data(housing_path=HOUSING_PATH):
"""
使用pandas加载数据
"""
csv_path = os.path.join(housing_path,"housing.csv")
return pd.read_csv(csv_path) | 466eaad6f90c2b251c85c93bb2aa379b88feb748 | 3,612,466 |
def one_configuration_row():
"""
ConfigurationRow
"""
return [
ConfigurationRow(
id=100,
name="Product 1: Feature 1",
product="testproduct1",
features='{"feature1": 1}',
license_servers=["flexlm:127.0.0.1:2345"],
license_ser... | ddb8af6adc76cca4954d75fffe2b45b8f7a69140 | 3,612,467 |
def atan(x, f=None):
"""
Computes trigonometric inverse tangent, element-wise.
The inverse of tan, so that if y = tan(x) then x = arctan(y).
:param x: Input array.
:type x: array
:param f: Machine learning framework. Inferred from inputs if None.
:type f: ml_framework, optional
:return:... | d1ced7d17c22fc5a60e7db71d9e0fab81be3bfb1 | 3,612,468 |
def butter(cutoff, fs, btype="low", order=4):
"""Return Butterworth filter coefficients. See scipy.signal.butter for a
more thorough documentation.
Parameters
----------
cutoff : array
Cutoff frequency, e.g. roughly speaking, the frequency at which the
filter acts. Units should be s... | febbdf7ecf7146c265d773edb1c4c9fbf39afef7 | 3,612,469 |
def is_dimensionless(quantity_or_unit: QuantityOrUnit) -> bool:
""" Check wheter a quantity or unit is dimensionless.
Parameters
----------
quantity_or_unit : QuantityOrUnit
A quantity or a unit
Returns
-------
bool
Whether the quanti... | eebc6c2edf02d370b3b14b7c936b223b1aa70dcb | 3,612,470 |
def count_lines(filename):
"""Returns the number of lines of the file :obj:`filename`."""
with tf.io.gfile.GFile(filename, mode="rb") as f:
i = 0
for i, _ in enumerate(f):
pass
return i + 1 | 5dea14a967299c8343756093588bd46d3e186207 | 3,612,471 |
def _build_transformer(gin_function):
"""
Makes a session and a default graph, loads the simple graph into it, and then calls
gin_function(session) to build the :py:obj:`TFInputGraph` object.
Return the :py:obj:`TFTransformer` created from it.
"""
graph = tf.Graph()
with tf.Session(graph=gra... | a0b98c5d6b00206cc683e4a8e8405421f047d18e | 3,612,472 |
def forecast_starter(seq, past, dim_in):
"""prepares the staring vector for RNN forecast
:param seq: the sequence from which the beggining is used as the forcast starter
:param past: the number of considered steps in the past
:param dim_in: the dimensionality of the data fed to the network
:returns: starter inpu... | 8cd572afead804d1900cedcb5dcecbe2e468ee7a | 3,612,473 |
def _get_single_osc(centers, powers, bws, osc_low, osc_high):
""" Searches for an oscillations of specified frequency band.
Returns a single oscillation in that band.
Helper function for osc_per_vertex in MegSubj.
Parameters
----------
centers : 1d array
Vector of oscillation centers.
... | 04691f21ca1721b9008d312f1283c0885f147564 | 3,612,474 |
def list_property_flags(flags):
"""Return list of PROPERTY_FLAG strings from flag number."""
return [k for k, v in Lucam.PROP_FLAG.items() if v & flags] | 13b42c94aace2d678ff524fea5587fd12526f079 | 3,612,475 |
from typing import List
from typing import Type
import re
def union_func_name(prefix: str, union_args: List[Type]) -> str:
"""
Generate a function name that contains all union types
* `prefix` prefix to distinguish between serializing and deserializing
* `union_args`: type arguments of a Union
>... | a8f1201bccee0cdc35db5e9861538fb6c7210f0d | 3,612,476 |
def create_line(data):
""" Convenience function to create a new line chart with the right args """
return Line(data, x='year', y=countries,
legend=True, width=1400, height=300, ylabel='Energy use per capita',
palette=['purple', 'green', 'blue', 'pink']) | 930b52784a00aacd3d0e2fa981801821358af49f | 3,612,477 |
import time
def slow_subtractor(a, b):
"""Return a minus b."""
time.sleep(5)
return a - b | 6420ad990ef3d7ebbe6f43832ae306a49a65f971 | 3,612,478 |
def _convert_image(data, mask=None):
"""
Convert the input data to a float64 (double) `numpy.ndarray`,
required for input to `skimage.measure.moments` and
`skimage.measure.moments_central`.
The input ``data`` is copied unless it already has that
`numpy.dtype`.
If ``mask`` is input, then ma... | 1f472dcb697bb6936445ebefd31ae6813731a433 | 3,612,479 |
import torch
def concatenate_list_of_dict(list_of_dict) -> dict:
"""
Concatenate dictionary with the same set of keys
Args:
list_of_dict: list of dictionary to concatenate
Returns:
output_dict: the concatenated dictionary
"""
# check that all dictionaries have the same set of... | e38837d9e55cc17715bf988b585c3f4f371f7398 | 3,612,480 |
def get_task(request):
"""
取出所有任务类型信息
:param request:
:return:
"""
try:
res = Task.objects.get_task(1) # 调用search_host接口
return res # 返回json数据
except Exception as e:
return_dic = {
"result": F... | 64000dd312dd428fd03c665e6317339891eab9c6 | 3,612,481 |
import math
def degrees(input):
"""Convertir a grados
Función para convertir una entrada en radianes a grados.
Args:
input(Number): valor real
Returns:
Number
"""
return (180*input)/math.pi | 30377bb8c135dcc8fab2d23ee3703c89f5d772cb | 3,612,482 |
from matplotlib import cm
def plot_3d_clustering(x, y, z, idx, elev=45, azim=-45, x_label=None, y_label=None, z_label=None, color_map='viridis', alphas=None, first_cluster_index_zero=True, s=None, markerscale=None, legend=True, figure_size=(7,7), title=None, save_filename=None):
"""
Plots a three-dimensional ... | 95fbc612656e1999a8fbab4f9146b7ea3243d571 | 3,612,483 |
import random
async def getrolenamed(role: str, guild: discord.Guild, create: bool = False, exact: bool = True):
"""
Returns a role inside a Guild based on a given name.
:param role: The role to be gathered. -> str
:param guild: The guild to retrieve the role from. -> discord.Guild
:param create: ... | 6744b0857f0bd4ea91d65e897c748d07aecacb76 | 3,612,484 |
def get_head_commit(current_branch=None):
"""Gets the commit hash of HEAD in the given branch.
Args:
current_branch: String; containing the name of a branch. Defaults to
None and in this case is replaced by a call to get_current_branch.
Returns:
40 hexadecimal characters contai... | c369d8be82e32bce5f5c0f14094078c50b75e6c2 | 3,612,485 |
from typing import Set
from typing import OrderedDict
def _collect_format_strings(zones_map: ZonesMap) -> IndexMap:
"""Collect the 'formats' field and return a map of indexes."""
short_formats: Set[str] = set()
for zone_name, eras in zones_map.items():
for era in eras:
format = era['fo... | 9be77be17e8b0fea4e9be9610f81173cd7b63858 | 3,612,486 |
def lognormal(a, f):
"""
A lognormal distribution
Parameters
----------
a : ndarray(3)
* a[0] : the natural logarithm of the Gaussian amplitude
* a[1] : the natural logarithm of the center of the Gaussian
* a[2] : the width of the Gaussian in units of natural logarithm o... | ff64280e6e3a6955b9c80528eda127517f2e4ab9 | 3,612,487 |
def init_pose(pred_Rs, init_pose, weights=None):
"""
Should stay close to initial weights
pred_Rs is N x 24 x 3 x 3
init_pose is 72D, need to conver to Rodrigues
"""
init_Rs = batch_rodrigues(tf.reshape(init_pose, [-1, 3]))
init_Rs = tf.reshape(init_Rs, [-1, 24, 3, 3])
RRt = tf.matmul(in... | f63a2c78d40416d19e4caa95c54f4a1bceccbd48 | 3,612,488 |
def get_volume_breakdown(model: BDF, property_ids=None, stop_if_no_volume=True):
"""
Gets a breakdown of the volume by property region.
Parameters
----------
property_ids : List[int] / int
list of property ID
stop_if_no_volume : bool; default=True
prevents crashing if there are ... | 99af776c10deb180edac8539582a66633331e5ab | 3,612,489 |
import os
def convert_file(file_info):
"""Convert MATLAB *.mat file to Pandas HDF5 format."""
# If the file exists, load and convert
print('Converting: {}'.format(file_info['file_name']))
# If running in dry-run mode, do not attempt to convert
if file_info['dry_run']:
return
# Load d... | 9ead877aab848608463fae67c42a5ee071b55da9 | 3,612,490 |
import os
import shutil
def clone_case(casedir,
template_dir,
copy_polymesh=True,
copy_zero=True,
copy_scripts=True,
extra_patterns=None):
"""Clone a Caelus case directory.
Args:
casedir (path): Absolute path to new case direc... | 08e1e904cf6a032fb0d21ce82a438ec9b8c30186 | 3,612,491 |
from typing import List
import glob
def get_manifest_list(manifests_dir: str) -> List[str]:
"""Get a list of manifest files from the manifest directory."""
yml_endings = ["yml", "yaml"]
manifest_list = []
for yml_ending in yml_endings:
manifest_list += glob.glob(f"{manifests_dir}/**/*.{yml_en... | 0dc951cf08870c639735e24b048a41fb7ab6ea52 | 3,612,492 |
from typing import Callable
import concurrent
from re import T
from typing import Coroutine
from typing import Any
from typing import Optional
import threading
import asyncio
def run_in_background(coroutine: Callable[[concurrent.futures.Future[T]], Coroutine[Any, Any, None]], *, name: Optional[str] = None, debug: boo... | ce17b8d938d7703d39f93fd061c7b159c4c50ff3 | 3,612,493 |
def render(root: MdastNode) -> str:
"""Convert MDAST to CommonMark compliant HTML."""
return MdastToHtmlTransform()(root) | 37a0859b1ac6a7d9e984c4c3f9fe5a466dae38cf | 3,612,494 |
def interpolateNDMinTimeLinear(x0, x1, vmax, amax):
"""interpolateNDMinTimeLinear(doubleVector x0, doubleVector x1, doubleVector vmax, doubleVector amax)"""
return _motionplanning.interpolateNDMinTimeLinear(x0, x1, vmax, amax) | 7ee459f1f55be0d0c9db2cbdeb7a4fbf919aadc2 | 3,612,495 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up config entry."""
def get_sensor_description(type_string: str):
if (description := SENSOR_TYPES_DICT.get(type_string)) is None:
return Binary... | c274bf74f58d3a403bfaf5876e13b4b915addf29 | 3,612,496 |
def slack_channel_lookup_error(err):
"""'None' or 'Multiple' results were found during a ``one()`` query for
:class:`jackalope.database.models.SlackChannel``.
"""
current_app.logger.exception(err)
return err.message, 404 | 03ee30a9f6bfb0124fcb9a8a587d14921f7b4032 | 3,612,497 |
def actor_lookup_email(api_user, email):
""" Lookup an actor based on an email address,
useful for determining if an email address is available
PARAMETERS:
email - email alias
RETURNS: actor_ref
"""
query = Relation.gql("WHERE target = :1 AND relation = 'email'",
email)
for rel_... | 3984d4eb18147b163ed1aa8702c84fc13f3a2474 | 3,612,498 |
def load_user(user_id):
"""
Loads current user data
---
"""
return User.query.filter_by(id=user_id).first() | 9427193ac8fae1554a10d89356959bb20ccafbf4 | 3,612,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.