content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
async def conversation_steps(month: int = Query(default=1, ge=2, le=6), current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Fetches the number of conversation steps that took place in the chat between the users and the agent
"""
return Utility.trigger_history_server_request(
... | 9845cf39290f056395351953e3d7accbcb14ae06 | 9,600 |
def off(app: str) -> dict:
"""
Switches the app offline, if it isn't already.
:param app: The name of the Heroku app in which you want formation
:return: dictionary containing information about the app
"""
return Herokron(app).off() | 8aa6cef16d8924ce682fa9a7b886cee87d4e02c5 | 9,601 |
import io
import csv
def parse_csv_from_response(response):
"""
Convenience function for working with CSV responses.
Parses the CSV rows and returns a list of dicts, using the
keys as columns
"""
file_from_string = io.StringIO(response.content.decode("utf-8"))
parsed_rows = []
reader =... | 9a2bf99e810c7b4b9ac947ad3ba53e016deb836a | 9,602 |
def count_weekday(start, stop, wd_target=0):
"""
Returns the number of days between start and stop inclusive which is the
first day of the month and is the specified weekday, with 0 being Monday.
"""
counter = 0
while start != stop + timedelta(days=1):
if start.weekday() == wd_target and... | 27dd8ce6493ac1c24c65c92208767159a6406348 | 9,603 |
import collections
def _get_ngrams(segment, max_order):
"""Extracts all n-grams upto a given maximum order from an input segment.
Args:
segment: text segment from which n-grams will be extracted.
max_order: maximum length in tokens of the n-grams returned by this
methods.
Returns:
... | c4b388d71b2c16e6c324718b8a07db8531c83413 | 9,604 |
def pkg_topics_list(data_dict):
"""
Get a list of topics
"""
pkg = model.Package.get(data_dict['id'])
vocabulary = model.Vocabulary.get('Topics')
topics = []
if vocabulary:
topics = pkg.get_tags(vocab=vocabulary)
return topics | 7594ea421ade2a530d8e08490b542bbd05d1a962 | 9,605 |
import re
import os
def get_adrill_cdbs(adrill_user_cfg, adrill_shared_cfg=None):
"""Return the names and locatinos of all user defined MSC Adams Drill databases (cdbs)
Parameters
----------
adrill_user_cfg : str
Full path to an Adams Drill user configuration file. This hould be in the u... | 08ea6fee48bb06627168bb2eefe2cc0f1ef0cb5d | 9,606 |
def five_five(n):
"""
This checks if n is a power of 2 (or 0).
This is because the only way that n and (n-1) have none of the same bits (the
& check) is when n is a power of 2, or 0.
"""
return ((n & (n-1)) == 0) | 0b1cc310b5d8bd6dab6299b6a999a5dd0720ea80 | 9,607 |
from main import bot
from typing import Optional
import asyncio
async def send_message(user_id: int,
text: str,
buttons: Optional[list[dict[str, str]]] = None,
disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param... | e2cb9879a1eea95d639f6ff3c7b7bf7c5b19ef68 | 9,608 |
def convert_bytes_to_size(some_bytes):
"""
Convert number of bytes to appropriate form for display.
:param some_bytes: A string or integer
:return: A string
"""
some_bytes = int(some_bytes)
suffix_dict = {
'0': 'B',
'1': 'KiB',
'2': 'MiB',
'3': 'GiB',
... | d1579e0fc0850a98145910c056b3fac8be7c66f1 | 9,609 |
def create_bbregister_func_to_anat(fieldmap_distortion=False,
name='bbregister_func_to_anat'):
"""
Registers a functional scan in native space to structural. This is meant to be used
after create_nonlinear_register() has been run and relies on some of it's outputs.
... | 0598cef86fdebe697bfdc1627554c4340303a86b | 9,610 |
def pointShiftFromRange(dataSize, x = all, y = all, z = all, **args):
"""Calculate shift of points given a specific range restriction
Arguments:
dataSize (str): data size of the full image
x,y,z (tuples or all): range specifications
Returns:
tuple: shift of points from orig... | dbe5c2049c5b76bfdbb839faa2a3e6cb942c8249 | 9,611 |
def callparser():
"""Parses a group of expressions."""
def cull_seps(tokens):
return tokens[0] or tokens[1]
return RepeatParser(exprparser() + OptionParser(dlmparser(',')) ^ cull_seps) | af8fbf81044b90d6a1a9ea769a513109237692d4 | 9,612 |
def write_section(section_name, section, keys, writer) -> bool:
"""
Saves the specified section to the specified writer starting at the current
point in the writer. It will not throw an exception. On error (IO exception
or not being able to write the section) it will return false. WARNING: It can
no... | 368f0cac04d392b9ea8946d30538a3fb0265c593 | 9,613 |
def _rotation_270(image):
"""Rotate an image with 270 degrees (clockwise).
Parameters
----------
image : np.ndarray
Image to rotate with shape (y, x, channels).
Returns
-------
image_rotated : np.ndarray
Image rotated with shape (y, x, channels).
"""
image_rotated ... | 3cd291c9283a32d0bc66902bff7861db855f4420 | 9,614 |
def classification_id_for_objs(object_id: str, url: str, token: str):
"""
Get classification id for a given object
Arguments
----------
object_id : str
Object id to get classification id for
url : str
Skyportal url
token : str
Skyportal token
... | b03bb7ff18235cafd1b171e5042d64c65c19cffc | 9,615 |
import math
def ciede2000(Lab_1, Lab_2):
"""Calculates CIEDE2000 color distance between two CIE L*a*b* colors."""
C_25_7 = 6103515625 # 25**7
L1, a1, b1 = Lab_1[0], Lab_1[1], Lab_1[2]
L2, a2, b2 = Lab_2[0], Lab_2[1], Lab_2[2]
C1 = math.sqrt(a1**2 + b1**2)
C2 = math.sqrt(a2**2 + b2**2)
C_a... | f95bc8338fbabe09f2038cea34e7a8fcad87f3bf | 9,616 |
import torch
def ifft2c_new(data: torch.Tensor) -> torch.Tensor:
"""
Apply centered 2-dimensional Inverse Fast Fourier Transform.
Args:
data: Complex valued input data containing at least 3 dimensions:
dimensions -3 & -2 are spatial dimensions and dimension -1 has size
2. A... | 6752dd94c690d8a8d3d0d625a693cd711c12c9c0 | 9,617 |
def _make_options(context, base):
"""Return pyld options for given context and base."""
options = {}
if context is None:
context = default_context()
options['expandContext'] = context
if base is not None:
options['base'] = base
return options | 8fcd514d9b0d11020ea197a29af6e76a53201306 | 9,618 |
def datatable(table_config: DatatableConfig, table_id: str, class_name: str = ''):
"""
Deprecated, use instead
<table id="{table_id}" data-datatable-url="{url}" class="{class_name}"></table>
"""
return {
"rich_columns": table_config.enabled_columns,
"search_box_enabled": table_config... | 777d19f0eaa6f1adbb53cc1fa6042fbec3df4398 | 9,619 |
def npelpt(point, ellipse):
"""npelpt(ConstSpiceDouble [3] point, ConstSpiceDouble [NELLIPSE] ellipse)"""
return _cspyce0.npelpt(point, ellipse) | f81ff9a993f0166ed4899338c66b58e5329382ce | 9,620 |
def register_module():
"""Registers this module in the registry."""
# provide parser to verify
verify.parse_content = content.parse_string_in_scope
# setup routes
courses_routes = [('/faq', utils_faq.FaqHandler),('/allresources', utils_allresources.AllResourcesHandler)]
global custom_module
... | e4fe1ae4d3b05a4c396155ae3b471e941de56f7d | 9,621 |
def degreeList(s):
"""Convert degrees given on command line to a list.
For example, the string '1,2-5,7' is converted to [1,2,3,4,5,7]."""
l = []
for r in s.split(','):
t = r.split('-')
if len(t) == 1:
l.append(int(t[0]))
else:
a = int(t[0])
... | 3b517831ddab47da5cd0e36fa5913d6d59e73715 | 9,622 |
import os
def _gen_simple_while_loop(base_dir):
"""Generates a saved model with a while loop."""
class Module(module.Module):
"""A module with a while loop."""
@def_function.function(
input_signature=[tensor_spec.TensorSpec((), dtypes.float32)])
def compute(self, value):
acc, _ = contr... | 1b782d14a0a0613a756f7dbf046c01d8a3338d61 | 9,623 |
def _get_corrected_msm(msm: pd.DataFrame, elevation: float, ele_target: float):
"""MSMデータフレーム内の気温、気圧、重量絶対湿度を標高補正
Args:
df_msm(pd.DataFrame): MSMデータフレーム
ele(float): 平均標高 [m]
elevation(float): 目標地点の標高 [m]
Returns:
pd.DataFrame: 補正後のMSMデータフレーム
"""
TMP = msm['TMP'].values
P... | 5cbfafa077c02ff5b7b74e47eff30c99e6201ff8 | 9,624 |
def get_answers_by_qname(sim_reads_sam_file):
"""Get a dictionary of Direction Start CIGAR MDtag by ReadID (qname)."""
answers_by_qname = {}
reads_file = open(sim_reads_sam_file)
reads_file.next() #skip header line
for line in reads_file:
id, dir, start, cigar, mdtag = line.strip().split('\t... | eae27387f4ac0e20b16392ca699fad7e6489c6e9 | 9,625 |
def post_times(post: Post) -> html_tag:
"""Display time user created post.
If user has edited their post show the timestamp for that as well.
:param post: Post ORM object.
:return: Rendered paragraph tag with post's timestamp information.
"""
p = tags.p(cls="small")
p.add(f"{_('Posted')}: ... | 8e64d6f49ed5bcf8f9a9ea1f3a5350880bbe7b39 | 9,626 |
def read_articles_stat(path):
"""
读取articles_stat文件,生成可以读取法条正负样本数量的字典列表
:param path: articles_stat文件位置
:return: ret: [{'第一条': (负样本数量, 正样本数量), ...}, {...}, ..., {...}]
"""
df = pd.read_csv(path, header=0, index_col=0)
ret = [{} for i in range(4)]
for index, row in df.iterrows():
r... | be35e11a508e22241188b4719dc6fa0db14f4395 | 9,627 |
def get_bounding_box(font):
""" Returns max and min bbox of given truetype font """
ymin = 0
ymax = 0
if font.sfntVersion == 'OTTO':
ymin = font['head'].yMin
ymax = font['head'].yMax
else:
for g in font['glyf'].glyphs:
char = font['glyf'][g]
if hasattr... | 98161ef3426c2bb9b6dc4079c69f5c1f9d4e93a2 | 9,628 |
def create_user(client, profile, user, resend=False):
""" Creates a new user in the specified user pool """
try:
if resend:
# Resend confirmation email for get back password
response = client.admin_create_user(
UserPoolId=profile["user_pool_id"],
U... | 4c1f83c0ab7fd28dc7b1e2d8f2efa224360dfdb1 | 9,629 |
def generate_move_probabilities(
in_probs: np.ndarray,
move_dirn: float,
nu_par: float,
dir_bool: np.ndarray
):
""" create move probabilities from a 1d array of values"""
out_probs = np.asarray(in_probs.copy())
if np.isnan(out_probs).any():
print('NANs in move probabilities!')
... | 4ea9ef914b905b6ab79933ba90a3604b0391f038 | 9,630 |
def _is_diagonal(x):
"""Helper to identify if `LinearOperator` has only a diagonal component."""
return (isinstance(x, tf.linalg.LinearOperatorIdentity) or
isinstance(x, tf.linalg.LinearOperatorScaledIdentity) or
isinstance(x, tf.linalg.LinearOperatorDiag)) | de3bb0ab2313c5432abab4bf7b0c1e227bc682d7 | 9,631 |
def index():
"""Index Controller"""
return render_template('login.html') | 53499d68c734e6315e3f24927d70cb7cddca346a | 9,632 |
def match_twosided(desc1,desc2):
""" Two-sided symmetric version of match(). """
matches_12 = match(desc1,desc2)
matches_21 = match(desc2,desc1)
ndx_12 = matches_12.nonzero()[0]
# remove matches that are not symmetric
for n in ndx_12:
if matches_21[int(matches_12[n])] != n... | a86d1cfb19afa5404d8c4950dd8b24a130a6a003 | 9,633 |
import re
def parse_header_links(value):
"""Return a list of parsed link headers proxies.
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
:rtype: list
"""
links = []
replace_chars = ' \'"'
value = value.strip(replace_c... | 58e1a73a524333cbd019387866047d434c7de494 | 9,634 |
import functools
import asyncio
def validate_term(fun):
"""Compares current local (node's) term and request (sender's) term:
- if current local (node's) term is older:
update current local (node's) term and become a follower
- if request (sender's) term is older:
respond with {'success': ... | 326ad6e9d937f9e07c2ac9e774578ddb34c61d04 | 9,635 |
def _friends_bootstrap_radius(args):
"""Internal method used to compute the radius (half-side-length) for each
ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using
bootstrapping."""
# Unzipping.
points, ftype = args
rstate = np.random
# Resampling.
npoints, ndim = points... | 0492f316c53b434faf79445313ec853830f87867 | 9,636 |
def _parametrize_plus(argnames=None, # type: Union[str, Tuple[str], List[str]]
argvalues=None, # type: Iterable[Any]
indirect=False, # type: bool
ids=None, # type: Union[Callable, Iterable[str]]
idstyle=None, # type: O... | 200da7befaa0695744c2f339a32711beb25ad69a | 9,637 |
def _clip_grad(clip_value, grad):
"""
Clip gradients.
Inputs:
clip_value (float): Specifies how much to clip.
grad (tuple[Tensor]): Gradients.
Outputs:
tuple[Tensor], clipped gradients.
"""
dt = ops.dtype(grad)
new_grad = nn.ClipByNorm()(grad, ops.cast(ops.tuple_to_... | 31cd4693a2bd80af7d3dd4be6a830b2982f8fce8 | 9,638 |
def sample_cast(user, name='David'):
"""Creates a sample Cast"""
return Cast.objects.create(user=user, name=name) | 3e4d03878697dfac931babbeaacaa7687d520189 | 9,639 |
import re
def sort_special_vertex_groups(vgroups,
special_vertex_group_pattern='STYMO:',
global_special_vertex_group_suffix='Character'):
"""
Given a list of special vertex group names, all with the prefix of
special_vertex_group_pattern, selec... | 0cc8f0992553e5da5b37ea9a9886996cb9013582 | 9,640 |
def _GetFullDesktopName(window_station, desktop) -> str:
"""Returns a full name to a desktop.
Args:
window_station: Handle to window station.
desktop: Handle to desktop.
"""
return "\\".join([
win32service.GetUserObjectInformation(handle, win32service.UOI_NAME)
for handle in [window_station... | e9a2aeebdb6f705efab1a0c1997ca66f4079cc07 | 9,641 |
def decrypt(plain_text: str, a: np.ndarray, b: np.ndarray, space: str) -> str:
"""Decrypts the given text with given a, b and space
:param plain_text: Text you want to decrypt
:type plain_text: str
:param a: An integer that corresponds to the A parameter in block cypher
:type a: np.ndarray
:param b: An integer... | 642b47d3459c64c5c7b280401aa96bd8f37cfa59 | 9,642 |
from typing import List
from functools import reduce
def merge_rois(roi_list: List,
temporal_coefficient: float, original_2d_vol: np.ndarray,
roi_eccentricity_limit=1.0, widefield=False):
# TODO is this the most efficient implementation I can do
"""
Merges rois based on tempo... | 631b953dcbf401f17392cd0cade06dc51d369e11 | 9,643 |
def well2D_to_df1D(xlsx_path, sheet, data_col):
"""
Convert new 2D output format (per well) to 1D dataframe
:param str xlsx_path: path to the xlsx file
:param str sheet: sheet name to load
:param str data_col: new column name of the linearized values
:return dataframe df: linearized dataframe
... | 0d8403b311c50cbc7f723e044f3aa93c50f17e80 | 9,644 |
import hashlib
def obtain_file_hash(path, hash_algo="md5"):
"""Obtains the hash of a file using the specified hash algorithm
"""
hash_algo = hashlib.sha256() if hash_algo=="sha256" else hashlib.md5()
block_size = 65535
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(block_si... | daa996339c638eaab4f3d067dcaaa4b865a6f923 | 9,645 |
def b_q_bar(z_c):
"""Result of integrating from z_c to 1/2 of the
hard collinear part of the quark splitting function"""
b_q_zc = CF * (-3. + 6. * z_c + 4.* np.log(2. - 2.*z_c))/2.
return b_q_zc | c7e68a2b4b17e035081fd07784aeef017fcedabc | 9,646 |
def getsize(store, path=None):
"""Compute size of stored items for a given path."""
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif isinstance(store, dict):
# compute from size of values
prefix = _path_to_pr... | e537a231c49ac1edb6153d4751bd7f1b01979778 | 9,647 |
def split_2DL5AB(GL, cursor, log):
"""
splits the KIR2DL5 GL-string into 2 separate GL strings for 2DL5A and 2DL5B
:param GL: GL-string for KIR2DL5, combining both A and B
:param cursor: cursor to a connection to the nextype archive
:param log: logger instance
"""
log.info("Splitting 2DL5-a... | e4c5eb51927b9e9cd607f95c1e2d1f853f4f2a3e | 9,648 |
def set_system_bios(context, settings, system_id=None, workaround=False):
"""
Finds a system matching the given ID and sets the BIOS settings
Args:
context: The Redfish client object with an open session
settings: The settings to apply to the system
system_id: The system to locate; ... | c28f52db53363399df534efacc506a7e25c99930 | 9,649 |
def geometric_augmentation(images,
flow = None,
mask = None,
crop_height = 640,
crop_width = 640,
probability_flip_left_right = 0.5,
probability_flip_up_down ... | f1a9ce6983edfd47388360b9d777ad5909c046e7 | 9,650 |
def edit_distance_between_seqs(seq1, seq2):
"""Input is two strings. They are globally aligned
and the edit distance is returned. An indel of any length
is counted as one edit"""
aln1, aln2 = _needleman_wunsch(seq1, seq2)
return edit_distance_from_aln_strings(aln1, aln2) | 88e98475c1652311745af69c6f521bba0497e633 | 9,651 |
import torch
def sentence_prediction(sentence):
"""Predict the grammar score of a sentence.
Parameters
----------
sentence : str
The sentence to be predicted.
Returns
-------
float
The predicted grammar probability.
"""
tokenizer = config.TOKENIZER.f... | 14d7c8efa76df4727419c2d99d685707ef46eb25 | 9,652 |
def DB():
"""Create a DB wrapper object connecting to the test database."""
db = pg.DB(dbname, dbhost, dbport)
if debug:
db.debug = debug
return db | fceb8d15d52cabc1814b42b286c10bbe7470216c | 9,653 |
def build_seq(variants, phased_genotype, ref, pre_start, ref_end=None):
"""
Build or extend the haplotype according to provided genotype. We marked the start position iterator of each haplotype and
update with variant alternative base.
"""
seqs = ""
position = pre_start
for variant, phased... | b5f5168603b941fe8a55df5bd3bbf69898db3804 | 9,654 |
def handle_str(x):
"""
handle_str returns a random string of the same length as x.
"""
return random_string(len(x)) | 856341d0e3ff6d41c4c0f14beda5133b7285478c | 9,655 |
def clean_profile(profile, sid, state_final, state_canceled):
"""
This method will prepare a profile for consumption in radical.analytics. It
performs the following actions:
- makes sure all events have a `ename` entry
- remove all state transitions to `CANCELLED` if a different final state
... | d58f8ad53623c6809f12f0ba589afcdaa807cf21 | 9,656 |
def get_process_causality_network_activity_query(endpoint_ids: str, args: dict) -> str:
"""Create the process causality network activity query.
Args:
endpoint_ids (str): The endpoint IDs to use.
args (dict): The arguments to pass to the query.
Returns:
str: The created query.
"... | 97330c89f7599cf4096322088ed7e7bad0699d49 | 9,657 |
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
try:
client = TickTick()
client.login(data.get("username"), data.get("password"))
except RequestExcepti... | 7f6989ae0a87579f2270aab479247634b7d1f7e8 | 9,658 |
def _shard_batch(xs):
"""Shards a batch for a pmap, based on the number of devices."""
local_device_count = jax.local_device_count()
def _prepare(x):
return x.reshape((local_device_count, -1) + x.shape[1:])
return jax.tree_map(_prepare, xs) | 5c6fb53a97af3543b9e147abfb896719f83a0a28 | 9,659 |
def get_time_limit(component_limit, overall_limit):
"""
Return the minimum time limit imposed by the component and overall limits.
"""
limit = component_limit
if overall_limit is not None:
try:
elapsed_time = util.get_elapsed_time()
except NotImplementedError:
... | 4699ff18459a434a93fb50f8ac8bcc569ceb5e63 | 9,660 |
def keras_decay(step, decay=0.0001):
"""Learning rate decay in Keras-style"""
return 1. / (1. + decay * step) | f26f1f100ecf1622d6da9958d0a6cd95a37b8b2a | 9,661 |
def get_swagger():
""" Request handler for the /swagger path.
GET: returns the My Cars API spec as a swagger json doc.
"""
try:
return _make_response(response=validator.get_swagger_spec())
except Exception as e:
return _make_error(500, e.message) | a7ce1def456264d180dcb15e6039cd32e4df7597 | 9,662 |
def subtract(value, *args, **kwargs):
"""
Return the difference between ``value`` and a :class:`relativedelta`.
:param value: initial date or datetime.
:param args: positional args to pass directly to :class:`relativedelta`.
:param kwargs: keyword args to pass directly to :class:`relativedelta`.
... | 9f3c17b07c4010d9b1bfcff93280f0a59247fc5f | 9,663 |
def plot_coastline(
axes,
bathymetry,
coords='grid',
isobath=0,
xslice=None,
yslice=None,
color='black',
server='local',
zorder=2,
):
"""Plot the coastline contour line from bathymetry on the axes.
The bathymetry data may be specified either as a file path/name,
or as a ... | 1166ea3e942bf5c9212cf07e69326c38f6e77f96 | 9,664 |
def safelog(func):
"""Version of prism.log that has prism as an optional dependency.
This prevents the sql database, which may not be available, from becoming a strict dependency."""
@wraps(func)
def inner(self, update, context):
try:
self.bot.cores["prism"].log_user(update.effective... | fbd1ad03417151705640f0fd20c0caa685896496 | 9,665 |
def draw(args):
"""
Draw a GraphML with the tribe draw method.
"""
G = nx.read_graphml(args.graphml[0])
draw_social_network(G, args.write)
return "" | f5347dceaf6f79ab22218eb8838944d4f3e5a8ea | 9,666 |
import re
def extract_stem_voc(x):
"""extract word from predefined vocbulary with stemming and lemmatization
Args:
x ([string]): [a sentence]
Returns:
[list]: [word after stemming and lemmatization]
"""
stem = PorterStemmer()
# wnl = WordNetLemmatizer()
all_words = se... | 0e882eb8f9b938fc8eb50e69dda2864d2d8a12da | 9,667 |
from typing import Union
from typing import Optional
from typing import List
from typing import Dict
def plot_without_vis_spec(
conditions_df: Union[str, pd.DataFrame],
grouping_list: Optional[List[IdsList]] = None,
group_by: str = 'observable',
measurements_df: Optional[Union[str, pd.... | dba21fae889057e83dd8084b727e7c6312c3cd0f | 9,668 |
import torch
def _get_culled_faces(face_verts: torch.Tensor, frustum: ClipFrustum) -> torch.Tensor:
"""
Helper function used to find all the faces in Meshes which are
fully outside the view frustum. A face is culled if all 3 vertices are outside
the same axis of the view frustum.
Args:
fa... | edb9594b4a9d5fe6c3d7fcf24e9b0e312b94d3cb | 9,669 |
import collections
def _build_pep8_output(result):
"""
Build the PEP8 output based on flake8 results.
Results from both tools conform to the following format:
<filename>:<line number>:<column number>: <issue code> <issue desc>
with some issues providing more details in the description within
... | a4abda2f9d3a2d9b3524c60429b047cbfe0285d9 | 9,670 |
def form_value(request, entity, attribute):
"""
Return value from request params or the given entity.
:param request: Pyramid request.
:param entity: Instance to get attribute from if it isn't found in the request
params.
:param str attribute: Name of attribute to search for in the request ... | 1daea77474dae5a1cb6fdab0b075a5b2f5c40865 | 9,671 |
def process_batch_data(batch_words, batch_tags=None):
"""
Padding batched dataset.
Args:
batch_words: Words in a batch.
batch_tags: Punctuations in a batch.
Returns: Words and punctuations after padding.
"""
b_words, b_words_len = pad_sequences(batch_words)
if batch_tags is N... | 2428b1009cfcaf55df8ef5be275d87f1053643fd | 9,672 |
import os
import glob
def grb2nc(glob_str, in_dir='./', out_dir='./'):
"""
Creates netCDF files from grib files.
:param glob_str: (str) - the naming pattern of the files
:param in_dir: (str) - directory of input files
:param out_dir: (str) - directory of output files
:return fo_names: (list) ... | c06a9496600ff847d4f35128d9c90fe373b32163 | 9,673 |
import uuid
import os
import json
def emit(path_local, path_s3, time, poisson=0.0, ls=None, z_line=None,
actin_permissiveness=None, comment = None, write = True, **kwargs):
"""Produce a structured JSON file that will be consumed to create a run
Import emit into an interactive workspace and populate a di... | 279159bfdd4b6035c439dcefe05d4e351a3f3dce | 9,674 |
import torch
import math
def adjust_learning_rate(
optimizer: torch.optim,
base_lr: float,
iteration: int,
warm_iter: int,
max_iter: int,
) -> float:
""" warmup + cosine lr decay """
start_lr = base_lr / 10
if iteration <= warm_iter:
lr = start_lr + (base_lr - start_lr) * itera... | 1304e22abb712cfb6c589a2adf199971c058986f | 9,675 |
import os
def load_data(region):
"""
Function to read in data according to region
Args:
region (str): valid values are US, JP and EU
Returns:
pd.DataFrame containing factors returns
"""
# region='US'
reg_mapper = {'US': 'USA', 'JP': 'JPN', 'EU': 'Europe'}
if region no... | 04de0cf3836d84907ce61fbfc7aea280d2fe92e0 | 9,676 |
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
... | a5d044fa5be8ceefdb3cee7fb212608110f8dae5 | 9,677 |
def face_at_link(shape, actives=None, inactive_link_index=BAD_INDEX_VALUE):
"""Array of faces associated with links.
Returns an array that maps link ids to face ids. For inactive links,
which do not have associated faces, set their ids to
*inactive_link_index*. Use the *actives* keyword to specify an a... | db7e3e87144354fb850b0741a7531d06e73227f6 | 9,678 |
def snrcat(spec,plugmap):
"""This function calculates the S/N for each fiber.
Parameters
----------
spec : SpecFrame object
The SpecFrame object that constrains the 1D extracted spectra.
plugmap : numpy structured array
The plugmap information for each fiber including which... | 30b3de8197425b92d0b69c3d49f3a1bca46ca659 | 9,679 |
def forward(S, A, O, obs):
"""Calculates the forward probability matrix F. This is a matrix where each
(i, j) entry represents P(o_1, o_2, ... o_j, X_t = i| A, O). In other words,
each (i, j) entry is the probability that the observed sequence is o_1, ...
o_j and that at position j we are in hidden st... | 24c6ddfa053b623a5a56dcc773c8fc4419258df8 | 9,680 |
def calculate_state(position, dt):
"""
Sometimes, a data file will include position only. In those cases,
the velocity must be calculated before the regression is run.
If the position is
| position_11 position_21 |
| position_12 position_22 |
| ....................... |
... | 9db6d94c8d80f99ccebbdcb9e0691e85e03c836d | 9,681 |
from typing import Optional
def get_server(name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetServerResult:
"""
Use this data source to retrieve an auth server from Okta.
## Example Usage
```python
import pulumi
import pulumi_okta as okta
... | d1693c032a254397d44f82bea626a54343c2dfef | 9,682 |
import pathos
from functools import partial
from itertools import repeat
from typing import Sequence
from typing import Dict
from typing import Set
def estimate_aps_user_defined(ml, X_c = None, X_d = None, data = None, C: Sequence = None, D: Sequence = None, L: Dict[int, Set] = None,
S: ... | 23e94a27800e8cdeca140666d23aace3fd8c5b2d | 9,683 |
def shared_vinchain_instance():
""" This method will initialize ``SharedInstance.instance`` and return it.
The purpose of this method is to have offer single default
vinchainio instance that can be reused by multiple classes.
"""
if not SharedInstance.instance:
clear_cache()
... | 8668ec7b3b56353545f7fb35fd834918de4207fc | 9,684 |
import os
import math
import uuid
def export_viewpoint_to_nw(view_point: ViewPoint) -> Element:
"""
Represents current view point as a NavisWorks view point XML structure
:param view_point: ViewPoint instance that should be represented in XML
:return: XML Element instance with inserted view point
... | ef50899b94d82300831e0b668fd334fdfc73a8a5 | 9,685 |
def generateMfccFeatures(filepath):
"""
:param filepath:
:return:
"""
y, sr = librosa.load(filepath)
mfcc_features = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)
return mfcc_features | 985519827a04d7375e021524d9b8ce6b4fb0482f | 9,686 |
def homography_crop_resize(org_img_size, crop_y, resize_img_size):
"""
compute the homography matrix transform original image to cropped and resized image
:param org_img_size: [org_h, org_w]
:param crop_y:
:param resize_img_size: [resize_h, resize_w]
:return:
"""
# transform original... | 85d252627e947306f3ece89eec1a678c2fa86bc9 | 9,687 |
def extract_project_info(req_soup, full_name=False):
"""Extract the relevant project info from a request.
Arguments:
req_soup (BS4 soup object):
The soup of the request.
full_name (boolean):
Whether or not to capture the entire project name or just the last
h... | 04064b769cb97688f47133df6c8dca0f806b6544 | 9,688 |
from typing import Optional
def get_underlying_asset_price(token_symbol: str) -> Optional[Price]:
"""Gets the underlying asset price for token symbol, if any
This function is neither in inquirer.py or chain/ethereum/defi.py
due to recursive import problems
"""
price = None
if token_symbol ==... | 8b8e7e79e3e77e7e2985d1a7f5aee337da424f87 | 9,689 |
import asyncio
def do_call_async(
fn_name, *args, return_type=None, post_process=None
) -> asyncio.Future:
"""Perform an asynchronous library function call."""
lib_fn = getattr(get_library(), fn_name)
loop = asyncio.get_event_loop()
fut = loop.create_future()
cf_args = [None, c_int64, c_int64]... | c3d32f9521a58c81231fe70601a9807b4b9841be | 9,690 |
def prefer_static_value(x):
"""Return static value of tensor `x` if available, else `x`.
Args:
x: `Tensor` (already converted).
Returns:
Numpy array (if static value is obtainable), else `Tensor`.
"""
static_x = tensor_util.constant_value(x)
if static_x is not None:
return static_x
return x | 4bd38e5f3a57314b48c86e37f543e6fb69847d1c | 9,691 |
from psyneulink.core.components.component import Component, ComponentsMeta
import types
import copy
def copy_parameter_value(value, shared_types=None, memo=None):
"""
Returns a copy of **value** used as the value or spec of a
Parameter, with exceptions.
For example, we assume that if we h... | 2586cc79524b63d74920f4b262d0b9b63cb8ef02 | 9,692 |
def ajax_login_required(function):
"""
Decorator for views that checks that the user is logged in, resulting in a
403 Unauthorized response if not.
"""
@wraps(function, assigned=available_attrs(function))
def wrapped_function(request, *args, **kwargs):
if request.user.is_authenticated:
... | 194d97cd4f9897482a27addeca74780316c39083 | 9,693 |
def compile_str_from_parsed(parsed):
"""The (quasi-)inverse of string.Formatter.parse.
Args:
parsed: iterator of (literal_text, field_name, format_spec, conversion) tuples,
as yield by string.Formatter.parse
Returns:
A format string that would produce such a parsed input.
>>> ... | bfc3d39ecee6e07e41690ee8f85f969c110de69b | 9,694 |
def calculate_class_weight(labels):
"""Calculates the inverse of the class cardinalities and
normalizes the weights such that the minimum is equal to 1.
Args:
labels: List of integers representing class labels
Returns:
Numpy array with weight for each class
"""
labels =... | ff88ac33b49e90f75ac743aec463e87d36023876 | 9,695 |
def CosEnv(length,rft=(0.005),fs=(44100)):
"""
rft : Rise and fall time [s]
length : Total length of window [s]
fs : Sampling freq [Hz]
"""
rfsamp = int(np.round(rft * fs))
windowsamp = int(np.round(length * fs))
flatsamp = windowsamp - (2 * rfsamp)
time_index = np.arange(0, 1,... | e15cf02bfad7f0a1935507d8e394718429df6958 | 9,696 |
def flatten(nested_list):
"""
Args:
nested_list (list): list of lists
Returns:
list: flat list
Example:
>>> import ubelt as ub
>>> nested_list = [['a', 'b'], ['c', 'd']]
>>> list(ub.flatten(nested_list))
['a', 'b', 'c', 'd']
"""
return it.chain.f... | 418c8d76ff97991ef26e59d7740df14690655cd5 | 9,697 |
def fetch_reply(query, session_id):
"""
main function to fetch reply for chatbot and
return a reply dict with reply 'type' and 'data'
"""
response = apiai_response(query, session_id)
intent, params = parse_response(response)
reply = {}
if intent == None:
reply['type'] = 'none'
reply['data'] = "I didn't u... | bfcb2938042b964da15c33c614d37433948b37f2 | 9,698 |
def create_SpatialReference(sr):
""" creates an arcpy.spatial reference object """
return arcpy.SpatialReference(sr) | fdb535d4e1c1acda4da4270d78ceb4db9c114584 | 9,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.