content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
import string
def process_tweet(tweet):
"""Process tweet function.
Input:
tweet: a string containing a tweet
Output:
tweets_clean: a list of words containing the processed tweet"""
stemmer = PorterStemmer()
stopwords_english = stopwords.words('english')
# R... | 2b69f70cfec5f90a6e58408fcd054cda7ad0f20a | 3,655,798 |
def oracle_query_id(sender_id, nonce, oracle_id):
"""
Compute the query id for a sender and an oracle
:param sender_id: the account making the query
:param nonce: the nonce of the query transaction
:param oracle_id: the oracle id
"""
def _int32(val):
return val.to_bytes(32, byteorder... | aa97834efd3df10951e05b99035dbef8210ba33d | 3,655,799 |
from typing import List
from typing import Set
def knapsack_with_budget(vals: List[float], weights: List[int], budget: int,
cap: int) -> Set[int]:
"""
Solves the knapsack problem (with budget) of the items with the given values
and weights, with the given budget and capacity, in a... | 3d91f18f8be7b82f17ebcda9dbfa419eadeec0ea | 3,655,800 |
import functools
def _basemap_redirect(func):
"""
Docorator that calls the basemap version of the function of the
same name. This must be applied as the innermost decorator.
"""
name = func.__name__
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if getattr(self, 'name'... | f3cee9113a6f8044255d3013e357742e231ea98e | 3,655,801 |
def embedding_lookup(input_ids,
vocab_size,
embedding_size=128,
initializer_range=0.02,
word_embedding_name="word_embeddings"):
"""Looks up words embeddings for id tensor.
Args:
input_ids: int32 Tensor of shape [batch_size, s... | 2f66d05ab70f4fb38d990e66ec5829cb62fdc934 | 3,655,802 |
import re
def find_version(infile):
"""
Given an open file (or some other iterator of lines) holding a
configure.ac file, find the current version line.
"""
for line in infile:
m = re.search(r'AC_INIT\(\[tor\],\s*\[([^\]]*)\]\)', line)
if m:
return m.group(1)
retur... | 35ac18757ee1156f046bbd9ffa68ed4898bc317a | 3,655,803 |
import math
def linear_warmup_decay(warmup_steps, total_steps, cosine=True, linear=False):
"""
Linear warmup for warmup_steps, optionally with cosine annealing or
linear decay to 0 at total_steps
"""
# check if both decays are not True at the same time
assert not (linear and cosine)
def f... | 9326622a07be677cb82744a30850674ca3c5f789 | 3,655,804 |
def query_anumbers(bbox,bbox2,bounds2):
"""
Queries anumbers of the reports within region defined
Args:
`bbox`= bounds of the region defined
Returns:
`anumberscode`=list of anumbers
"""
try:
collars_file='http://geo.loop-gis.org/geoserver/loop/wfs?service=WFS&version=1.0.... | 91a31ba05df1a88f1c665f7d4dbb1c2d26bb2cc9 | 3,655,805 |
def Parse(spec_name, arg_r):
# type: (str, args.Reader) -> args._Attributes
"""Parse argv using a given FlagSpec."""
spec = FLAG_SPEC[spec_name]
return args.Parse(spec, arg_r) | 9dc2de95e8f9001eff82f16de6e14f51f768306f | 3,655,806 |
def get_path_url(path: PathOrString) -> str:
"""Covert local path to URL
Arguments:
path {str} -- path to file
Returns:
str -- URL to file
"""
path_obj, path_str = get_path_forms(path)
if is_supported_scheme(path_str):
return build_request(path_str)
return path_ob... | 812471da77d59cc0f331b5a031282abb5847f054 | 3,655,807 |
def process_keyqueue(codes, more_available):
"""
codes -- list of key codes
more_available -- if True then raise MoreInputRequired when in the
middle of a character sequence (escape/utf8/wide) and caller
will attempt to send more key codes on the next call.
returns (list of input, list ... | 8a49f55ca760853176c319487936c8e93911535e | 3,655,808 |
from typing import Dict
from typing import List
from typing import Tuple
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]:
"""
Given labels and a constraint type, returns the allowed transitions. It will
additionally include transitions for the start and end s... | 173dd26c17156ecd73ba1181022183b68f158331 | 3,655,809 |
def simple_linear(parent = None, element_count=16, element_pitch=7e-3):
"""1D line of elements, starting at xyz=0, along y, with given element_pitch
Parameters
----------
parent : handybeam.world.World
the world to give to this array as parent
element_count : int
count of ... | 7cb7a2f5de6ea4ecbe0a67ca8f383bae2bd0f5b0 | 3,655,812 |
def for_all_methods(decorator, exclude_methods=None):
"""
Class decorator
"""
if exclude_methods is None:
exclude_methods = []
def decorate(cls):
for attr in cls.__dict__:
if (
callable(getattr(cls, attr))
and attr not in DO_NOT_DECORATE_M... | 6a24961ebd512a20f3b0cad9c3657fa6ff5997ea | 3,655,813 |
def _kuramoto_sivashinsky_old(dimensions, system_size, dt, time_steps):
""" This function INCORRECTLY simulates the Kuramoto–Sivashinsky PDE
It is kept here only for historical reasons.
DO NOT USE UNLESS YOU WANT INCORRECT RESULTS
Even though it doesn't use the RK4 algorithm, it is bundled with the ot... | 3c0158946b1220e0fa56bea201e2ee31d6df51e5 | 3,655,815 |
def get_geneids_of_user_entity_ids(cursor, unification_table, user_entity_ids):
"""
Get the Entrez Gene IDs of targets using their BIANA user entity ids
"""
query_geneid = ("""SELECT G.value, G.type
FROM externalEntityGeneID G, {} U
WHERE U.externalEntityID... | bf192c192352da64716ecab6b4523b50fea5cd0f | 3,655,816 |
def int_array_to_hex(iv_array):
"""
Converts an integer array to a hex string.
"""
iv_hex = ''
for b in iv_array:
iv_hex += '{:02x}'.format(b)
return iv_hex | f3332b7672a266ad9cae9fc52bc8e1152bcee58b | 3,655,819 |
from io import StringIO
import logging
import tempfile
def minimal_sphinx_app(
configuration=None, sourcedir=None, with_builder=False, raise_on_warning=False
):
"""Create a minimal Sphinx environment; loading sphinx roles, directives, etc."""
class MockSphinx(Sphinx):
"""Minimal sphinx init to lo... | 55c911a16748e61ff3461833e82661314c5ffdca | 3,655,820 |
def calc_Mo_from_M(M, C=C):
"""
Calculate seismic moment (Mo) from
moment magnitude (M) given a scaling law.
C is a scaling constant; should be set at 6,
but is defined elsewhere in the module so
that all functions using it share a value.
"""
term1 = 3/2. * C * (np.log(2) + np.log(5) )
... | f72033100829126a353d7682f449d0ff4cd3efa8 | 3,655,821 |
import pathlib
def _file_format_from_filename(filename):
"""Determine file format from its name."""
filename = pathlib.Path(filename).name
return _file_formats[filename] if filename in _file_formats else "" | 25f90333696491ddd7b522ca2ac24c84a09e8d07 | 3,655,823 |
def r2k(value):
"""
converts temperature in R(degrees Rankine) to K(Kelvins)
:param value: temperature in R(degrees Rankine)
:return: temperature in K(Kelvins)
"""
return const.convert_temperature(value, 'R', 'K') | 93c3a7ead8b6b15fc141cd6339acedc044dd2c61 | 3,655,824 |
import select
def add_version(project, publication_id):
"""
Takes "title", "filename", "published", "sort_order", "type" as JSON data
"type" denotes version type, 1=base text, 2=other variant
Returns "msg" and "version_id" on success, otherwise 40x
"""
request_data = request.get_json()
if ... | b6887e5d09e54827ed4f5ad50f1c3e404d55e821 | 3,655,825 |
import functools
def to_decorator(wrapped_func):
"""
Encapsulates the decorator logic for most common use cases.
Expects a wrapped function with compatible type signature to:
wrapped_func(func, args, kwargs, *outer_args, **outer_kwargs)
Example:
@to_decorator
def foo(func, args, kwargs... | d7c9d0e759e59c26b7c5f7b098e15b78314c8860 | 3,655,826 |
def _get_unit(my_str):
""" Get unit label from suffix """
#
matches = [my_str.endswith(suffix) for suffix in _known_units]
# check to see if unit makes sense
if not any(matches):
raise KeyError('Unit unit not recognized <{}>!'.format(my_str))
# pick unit that matches, with prefix
... | 86cbb00dbd95025fde265461963e45d457d68470 | 3,655,827 |
import random
def spec_augment(spectrogram, time_mask_para=70, freq_mask_para=20, time_mask_num=2, freq_mask_num=2):
"""
Provides Augmentation for audio
Args: spectrogram, time_mask_para, freq_mask_para, time_mask_num, freq_mask_num
spectrogram (torch.Tensor): spectrum
time_mask_para (int... | a2f1c669253250a581a555a531db79fb756b91bb | 3,655,828 |
def scale(a: tuple, scalar: float) -> tuple:
"""Scales the point."""
return a[0] * scalar, a[1] * scalar | 9638b8cfbd792c2deb35da304c5c375e0402404e | 3,655,829 |
def parse_env(env):
"""Parse the given environment and return useful information about it,
such as whether it is continuous or not and the size of the action space.
"""
# Determine whether input is continuous or discrete. Generally, for
# discrete actions, we will take the softmax of the output
... | 4f5c97e71b7c1e8a319c28c4c1c26a1b758c731b | 3,655,830 |
def encode_dataset(dataset, tester, mode="gate"):
"""
dataset: object from the `word-embeddings-benchmarks` repo
dataset.X: a list of lists of pairs of word
dataset.y: similarity between these pairs
tester: tester implemented in my `tester.py`"""
words_1 = [x[0] for x in dataset["X"]]
... | 726aed93e3cef49f014d44f62e5ff73eae47da43 | 3,655,831 |
import csv
def readData(filename):
"""
Read in our data from a CSV file and create a dictionary of records,
where the key is a unique record ID and each value is dict
"""
data_d = {}
with open(filename) as f:
reader = csv.DictReader(f)
for row in reader:
clean_row =... | 193901c98966f4c0bd2b0e326711b962197ef4da | 3,655,834 |
def update_roi_mask(roi_mask1, roi_mask2):
"""Y.G. Dec 31, 2016
Update qval_dict1 with qval_dict2
Input:
roi_mask1, 2d-array, label array, same shape as xpcs frame,
roi_mask2, 2d-array, label array, same shape as xpcs frame,
Output:
roi_mask, 2d-array, label array, same shape ... | 211d6db69438866ff64c1944fa513ab847d9e641 | 3,655,836 |
from typing import List
from typing import Tuple
from typing import Dict
from typing import Any
def training_loop(
train_sequences: List[Tuple[pd.DataFrame, float]],
val_sequences: List[Tuple[pd.DataFrame, float]],
test_sequences: List[Tuple[pd.DataFrame, float]],
parameters: Dict[str, Any],
dir_... | 27b02630173d972a83c82140e0d2c6c957266fa4 | 3,655,838 |
def nmi(X, y):
"""
Normalized mutual information between X and y.
:param X:
:param y:
"""
mi = mutual_info_regression(X, y)
return mi / mi.max() | 5da09b9395883f9b197b2c2add7850d0e1870c44 | 3,655,839 |
from typing import Optional
import re
def attribute_as_str(path: str, name: str) -> Optional[str]:
"""Return the two numbers found behind --[A-Z] in path.
If several matches are found, the last one is returned.
Parameters
----------
path : string
String with path of file/folder to get at... | 257fec03ca911c703e5e06994477cf0b3b75a2ae | 3,655,840 |
def validate_inputs(input_data: pd.DataFrame) -> pd.DataFrame:
"""Check model for unprocessable values."""
valudated_data = input_data.copy()
# check for numerical variables with NA not seen during training
return validated_data | 65087650e9a5e85c3a362a5e27f82bf5f27a1f59 | 3,655,842 |
def index():
"""
Check if user is authenticated and render index page
Or login page
"""
if current_user.is_authenticated:
user_id = current_user._uid
return render_template('index.html', score=get_score(user_id), username=get_username(user_id))
else:
return redirect(url_f... | edb8ad552ab34640fc030250659ebd05027712fa | 3,655,843 |
from typing import Iterable
from typing import Callable
from typing import Optional
def pick(
seq: Iterable[_T], func: Callable[[_T], float], maxobj: Optional[_T] = None
) -> Optional[_T]:
"""Picks the object obj where func(obj) has the highest value."""
maxscore = None
for obj in seq:
score =... | 7f29c3aef5086957a1b1bd97f086a6ba6fb22cfd | 3,655,844 |
def rsync_public_key(server_list):
"""
推送PublicKey
:return: 只返回推送成功的,失败的直接写错误日志
"""
# server_list = [('47.100.231.147', 22, 'root', '-----BEGIN RSA PRIVATE KEYxxxxxEND RSA PRIVATE KEY-----', 'false')]
ins_log.read_log('info', 'rsync public key to server')
rsync_error_list = []
rsync_suce... | 94c9941e3f63caf15b0df8c19dc91ee54d002316 | 3,655,845 |
import re
from bs4 import BeautifulSoup
def create_one(url, alias=None):
"""
Shortens a URL using the TinyURL API.
"""
if url != '' and url is not None:
regex = re.compile(pattern)
searchres = regex.search(url)
if searchres is not None:
if alias is not None:
... | a543c23bc694fe09bae3bb4d59802fa6a5c3897d | 3,655,846 |
def duplicate_each_element(vector: tf.Tensor, repeat: int):
"""This method takes a vector and duplicates each element the number of times supplied."""
height = tf.shape(vector)[0]
exp_vector = tf.expand_dims(vector, 1)
tiled_states = tf.tile(exp_vector, [1, repeat])
mod_vector = tf.reshape(tiled_st... | 5b8ea4307d5779929def59805bc5210d8e948a4d | 3,655,847 |
def apk(actual, predicted, k=3):
"""
Computes the average precision at k.
This function computes the average precision at k for single predictions.
Parameters
----------
actual : int
The true label
predicted : list
A list of predicted elements (order does matter)... | 27c8d1d03f5fe571f89378d1beb60cde9d82f27e | 3,655,848 |
def make_predictor(model):
"""
Factory to build predictor based on model type provided
Args:
model (DeployedModel): model to use when instantiating a predictor
Returns:
BasePredictor Child: instantiated predictor object
"""
verify = False if model.example == '' else True
... | 87a89d179c28e971a3c29946e94105542686510e | 3,655,849 |
def get(identifier: str) -> RewardScheme:
"""Gets the `RewardScheme` that matches with the identifier.
Arguments:
identifier: The identifier for the `RewardScheme`
Raises:
KeyError: if identifier is not associated with any `RewardScheme`
"""
if identifier not in _registry.keys():
... | 574126cab1a1c1bd10ca2ada1fe626ba66910b11 | 3,655,850 |
def add_query_params(url: str, query_params: dict) -> str:
"""Add query params dict to a given url (which can already contain some query parameters)."""
path_result = parse.urlsplit(url)
base_url = path_result.path
# parse existing query parameters if any
existing_query_params = dict(parse.parse_q... | 8ea28c2492343e0f7af3bac5d44751827dd6b7aa | 3,655,851 |
def try_get_mark(obj, mark_name):
"""Tries getting a specific mark by name from an object, returning None if no such mark is found
"""
marks = get_marks(obj)
if marks is None:
return None
return marks.get(mark_name, None) | 1dd8b9635d836bbce16e795900d7ea9d154e5876 | 3,655,853 |
def timedelta_to_seconds(ts):
""" Convert the TimedeltaIndex of a pandas.Series into a numpy
array of seconds. """
seconds = ts.index.values.astype(float)
seconds -= seconds[-1]
seconds /= 1e9
return seconds | 4565d7a691e8ac004d9d529568db0d032a56d088 | 3,655,854 |
def parse_gage(s):
"""Parse a streamgage key-value pair.
Parse a streamgage key-value pair, separated by '='; that's the reverse of ShellArgs.
On the command line (argparse) a declaration will typically look like::
foo=hello or foo="hello world"
:param s: str
:rtype: tuple(key, value)
... | 299b47f3a4757c924620bdc05e74f195a4cb7967 | 3,655,855 |
from typing import Mapping
def get_attribute(instance, attrs):
"""
Similar to Python's built in `getattr(instance, attr)`,
but takes a list of nested attributes, instead of a single attribute.
Also accepts either attribute lookup on objects or dictionary lookups.
"""
for attr in attrs:
... | 121ef8d4b0b6b69fda1591e2f372a4cf9ec60129 | 3,655,856 |
from datetime import datetime
def get_log_line_components(s_line):
"""
given a log line, returns its datetime as a datetime object
and its log level as a string and the message itself as another
string - those three are returned as a tuple. the log level
is returned as a single character (first c... | 3ec7e5418f39a579ce8b71f3c51a8e1356cb5291 | 3,655,858 |
def is_eligible_for_bulletpoint_vote(recipient, voter):
"""
Returns True if the recipient is eligible to receive an award.
Checks to ensure recipient is not also the voter.
"""
if voter is None:
return True
return (recipient != voter) and is_eligible_user(recipient) | 20d34076c92b7fd9474a7cf4edf7ca38ad3ffba5 | 3,655,859 |
def _get_in_collection_filter_directive(input_filter_name):
"""Create a @filter directive with in_collecion operation and the desired variable name."""
return DirectiveNode(
name=NameNode(value=FilterDirective.name),
arguments=[
ArgumentNode(
name=NameNode(value="op_n... | 3c8b18314aa415d6dbec14b63a956e5fdf73aa9d | 3,655,860 |
def load_labelmap(path):
"""Loads label map proto.
Args:
path: path to StringIntLabelMap proto text file.
Returns:
a StringIntLabelMapProto
"""
with tf.gfile.GFile(path, 'r') as fid:
label_map_string = fid.read()
label_map = string_int_label_map_pb2.StringIntLabelMap()
try:
text_for... | 3ec29d2dc8fc4bacde5f0dfa49465676f5e8c44c | 3,655,861 |
def calc_internal_hours(entries):
"""
Calculates internal utilizable hours from an array of entry dictionaries
"""
internal_hours = 0.0
for entry in entries:
if entry['project_name'][:22] == "TTS Acq / Internal Acq" and not entry['billable']:
internal_hours = internal_hours + flo... | 0962ee49f60ac296668294e6d2f075ce981cbc55 | 3,655,862 |
def format_str_strip(form_data, key):
"""
"""
if key not in form_data:
return ''
return form_data[key].strip() | 44c5aaf8c5e11bfee05971d2961e5dcaf4cd8d9f | 3,655,863 |
def get_element(element_path: str):
"""
For base extension to get main window's widget,event and function,\n
pay attention,you must be sure the element's path
grammar: element's path (father>attribute>attribute...) like UI_WIDGETS>textViewer
"""
try:
listed_element_path = element_path.s... | 041ec89a700018ce5a6883a80a1998d7179c7041 | 3,655,864 |
import urllib
def gravatar_for_email(email, size=None, rating=None):
"""
Generates a Gravatar URL for the given email address.
Syntax::
{% gravatar_for_email <email> [size] [rating] %}
Example::
{% gravatar_for_email [email protected] 48 pg %}
"""
gravatar_url = "%savatar... | 73f3eed5ea073cd4bf6e4a978983c4ed12cedcd6 | 3,655,865 |
def decmin_to_decdeg(pos, decimals=4):
"""Convert degrees and decimal minutes into decimal degrees."""
pos = float(pos)
output = np.floor(pos / 100.) + (pos % 100) / 60.
return round_value(output, nr_decimals=decimals) | de6490ce5278090b90f87adab57fe8b912307e2c | 3,655,866 |
def get_selector(selector_list, identifiers, specified_workflow=None):
"""
Determine the correct workflow selector from a list of selectors, series of identifiers and user specified workflow if defined.
Parameters
----------
selector_list list
List of dictionaries, where the value of all di... | f458a82d2d0e81070eefabd490127567a1b67bbb | 3,655,867 |
import functools
import inspect
import re
def register_pth_hook(fname, func=None):
"""
::
# Add a pth hook.
@setup.register_pth_hook("hook_name.pth")
def _hook():
'''hook contents.'''
"""
if func is None:
return functools.partial(register_pth_hook, fname)
... | 1090d4601e0d51ec4c7761bb070318f906c23f87 | 3,655,868 |
def callable_or_raise(obj):
"""Check that an object is callable, else raise a :exc:`ValueError`.
"""
if not callable(obj):
raise ValueError('Object {0!r} is not callable.'.format(obj))
return obj | cb6dd8c03ea41bb94a8357553b3f3998ffcc0d65 | 3,655,869 |
def conv_coef(posture="standing", va=0.1, ta=28.8, tsk=34.0,):
"""
Calculate convective heat transfer coefficient (hc) [W/K.m2]
Parameters
----------
posture : str, optional
Select posture from standing, sitting or lying.
The default is "standing".
va : float or iter, option... | d351b82d2ffb81396b4e0ce2f05b429cb79ac28c | 3,655,871 |
def _one_formula(lex, fmt, varname, nvars):
"""Return one DIMACS SAT formula."""
f = _sat_formula(lex, fmt, varname, nvars)
_expect_token(lex, {RPAREN})
return f | 166c73c6214a0f6e3e6267804d2dd5c16b43a652 | 3,655,872 |
def _split_variables(variables):
"""Split variables into always passed (std) and specified (file).
We always pass some variables to each step but need to
explicitly define file and algorithm variables so they can
be linked in as needed.
"""
file_vs = []
std_vs = []
for v in variables:
... | 2b297bf99153256769d42c3669f3f8f29da95b70 | 3,655,873 |
import numpy
def percentiles_fn(data, columns, values=[0.0, 0.25, 0.5, 0.75, 1.0], remove_missing=False):
"""
Task: Get the data values corresponding to the percentile chosen at
the "values" (array of percentiles) after sorting the data.
return -1 if no data was found
:param da... | cfacd575e3e1f8183b1e82512859198a973a1f85 | 3,655,874 |
def base_checkout_total(
subtotal: TaxedMoney,
shipping_price: TaxedMoney,
discount: Money,
currency: str,
) -> TaxedMoney:
"""Return the total cost of the checkout."""
zero = zero_taxed_money(currency)
total = subtotal + shipping_price - discount
# Discount is subtracted from both gross... | 04017f67249b2415779b8a7bbfa854653ec6c285 | 3,655,875 |
def if_statement(lhs='x', op='is', rhs=0, _then=None, _else=None):
"""Celery Script if statement.
Kind:
_if
Arguments:
lhs (left-hand side)
op (operator)
rhs (right-hand side)
_then (id of sequence to execute on `then`)
_else (id of sequence to execute on `el... | c42baa0933be08e89049894acfd3c003832331db | 3,655,876 |
def add_next_open(df, col='next_open'):
"""
找出下根K线的开盘价
"""
df[col] = df[CANDLE_OPEN_COLUMN].shift(-1)
df[col].fillna(value=df[CANDLE_CLOSE_COLUMN], inplace=True)
return df | 185fdd87b437546be63548506adef7bb56c4aa5d | 3,655,877 |
def seasons_used(parameters):
"""
Get a list of the seasons used for this set of parameters.
"""
seasons_used = set([s for p in parameters for s in p.seasons])
# Make sure this list is ordered by SEASONS.
return [season for season in SEASONS if season in seasons_used] | 641e0b4dd01bd30bf9129a9302ad5935a614588f | 3,655,878 |
def get_polyphyletic(cons):
"""get polyphyletic groups and a representative tip"""
tips, taxonstrings = unzip(cons.items())
tree, lookup = make_consensus_tree(taxonstrings, False, tips=tips)
cache_tipnames(tree)
names = {}
for n in tree.non_tips():
if n.name is None:
continu... | b53a50170b3546f8228aa82013545148918155b7 | 3,655,879 |
from typing import Tuple
from typing import cast
def find_closest_integer_in_ref_arr(query_int: int, ref_arr: NDArrayInt) -> Tuple[int, int]:
"""Find the closest integer to any integer inside a reference array, and the corresponding difference.
In our use case, the query integer represents a nanosecond-discr... | 9d0e43d869b94008fb51b1281041538a85d48d7e | 3,655,880 |
def saver_for_file(filename):
"""
Returns a Saver that can load the specified file, based on the file extension. None if failed to determine.
:param filename: the filename to get the saver for
:type filename: str
:return: the associated saver instance or None if none found
:rtype: Saver
"""... | 0838a46be5a282849fdf48584e9a8e971b7ef966 | 3,655,881 |
def make(context, name):
"""Create an object in a registered table class.
This function will be stored in that object, so that the new table object
is able to create new table objects in its class.
!!! hint
This is needed when the user wants to insert new records in the table.
Parameters
... | 2b87aa461f97c1d1e1c6ff9a8c6d4128d8eccbb3 | 3,655,882 |
def cofilter(function, iterator):
"""
Return items in iterator for which `function(item)` returns True.
"""
results = []
def checkFilter(notfiltered, item):
if notfiltered == True:
results.append(item)
def dofilter(item):
d = maybeDeferred(function, item)
d.... | 0c14ce3310e1f1a2984b1faf5be21c552ca65b43 | 3,655,883 |
def download_dataset(dataset_name='mnist'):
"""
Load MNIST dataset using keras convenience function
Args:
dataset_name (str): which of the keras datasets to download
dtype (np.dtype): Type of numpy array
Returns tuple[np.array[float]]:
(train images, train labels), (test images... | c4bda5981acaf1907d46724f217012bf9349e9da | 3,655,884 |
from typing import Type
from textwrap import dedent
def create_trigger_function_sql(
*,
audit_logged_model: Type[Model],
context_model: Type[Model],
log_entry_model: Type[Model],
) -> str:
"""
Generate the SQL to create the function to log the SQL.
"""
trigger_function_name = f"{ audi... | 696443cee7752b74542d259d4a223f419462d18f | 3,655,886 |
def reorder_by_first(*arrays):
"""
Applies the same permutation to all passed arrays,
permutation sorts the first passed array
"""
arrays = check_arrays(*arrays)
order = np.argsort(arrays[0])
return [arr[order] for arr in arrays] | bd9e60cadba4644b06ae55396c7dcae33f1fa1d0 | 3,655,887 |
def embedding_weights(mesh,
vocab_dim,
output_dim,
variable_dtype,
name="embedding",
ensemble_dim=None,
initializer=None):
"""Embedding weights."""
if not ensemble_dim:
ensemble_di... | b89d5a411757d704c57baff6e4a74b7a5807c381 | 3,655,888 |
def generiraj_emso(zenska):
"""Funkcija generira emso stevilko"""
rojstvo = random_date_generator(julijana_zakrajsek)
# Odstranim prvo števko leta
emso_stevke = rojstvo[:4] + rojstvo[5:]
if zenska:
# Malce pretirana poenostavitev zadnjih treh cifer, lahko se zgodi da pridejo iste + zanemarja... | 89734021fd0d6f863a309b5c23c0a4ee6d385edf | 3,655,889 |
def pdf_markov2(x, y, y_offset=1, nlevels=3):
"""
Compute the empirical joint PDF for two processes of Markov order 2. This
version is a bit quicker than the more general pdf() function.
See the docstring for pdf for more info.
"""
y_offset = np.bool(y_offset)
# out = np.ones((nlevels,)*6... | 6d789d1ef9ff88c27f610e9904bdbc27fbe10e5b | 3,655,890 |
def check_if_recipe_skippable(recipe, channels, repodata_dict, actualname_to_idname):
"""
check_if_recipe_skippable
=========================
Method used to check if a recipe should be skipped or not.
Skip criteria include:
- If the version of the recipe in the channel repodata is greater t... | 604fdcf86ec45826f53fd837d165b234e9d11d91 | 3,655,893 |
def hello(name=None):
"""Assuming that name is a String and it checks for user typos to return a name with a first capital letter (Xxxx).
Args:
name (str): A persons name.
Returns:
str: "Hello, Name!" to a given name, or says Hello, World! if name is not given (or passed as an empty String... | f1aafbebd49507fd5417d8752f98ae7d0af8ec33 | 3,655,895 |
def computePCA(inputMatrix, n_components=None):
"""Compute Principle Component Analysis (PCA) on feature space. n_components specifies the number of dimensions in the transformed basis to keep."""
pca_ = PCA(n_components)
pca_.fit(inputMatrix)
return pca_ | 4061f998bfca9ed294b312ae746a63ea0eef8438 | 3,655,896 |
def tag(repo, subset, x):
"""The specified tag by name, or all tagged revisions if no name is given.
Pattern matching is supported for `name`. See
:hg:`help revisions.patterns`.
"""
# i18n: "tag" is a keyword
args = getargs(x, 0, 1, _("tag takes one or no arguments"))
cl = repo.changelog
... | d4ceadb7ef03ae6ed950c60c7bbf06b4d26f8671 | 3,655,897 |
def _embed_json(service, targetid):
"""
Returns oEmbed JSON for a given URL and service
"""
return d.http_get(_OEMBED_MAP[service] % (urlquote(targetid),)).json() | 347d38e2b4f69c853e8085308e334b7cc778d4ad | 3,655,898 |
import re
def is_blank(s):
"""Returns True if string contains only space characters."""
return re.search(reNonSpace, s) is None | 40b4ec62a2882d100b80fd951c6b9e4d31220581 | 3,655,899 |
def remove_invalid_chars_from_passage(passage_text):
"""
Return a cleaned passage if the passage is invalid.
If the passage is valid, return None
"""
# Check if any of the characters are invalid
bad_chars = [c for c in passage_text if c in INVALID_PASSAGE_CHARACTERS]
if bad_chars:
for b in set(bad_chars):
p... | 5eeac3393477c45ac361fb2ccbae194c83e47f25 | 3,655,900 |
import locale
def fallback_humanize(date, fallback_format=None, use_fallback=False):
"""
Format date with arrow and a fallback format
"""
# Convert to local timezone
date = arrow.get(date).to('local')
# Set default fallback format
if not fallback_format:
fallback_format = '%Y/%m/%d... | 06a758cea23978d877d12cfead25b21140370094 | 3,655,901 |
from functools import reduce
def min_column_widths(rows):
"""Computes the minimum column width for the table of strings.
>>> min_column_widths([["some", "fields"], ["other", "line"]])
[5, 6]
"""
def lengths(row): return map(len, row)
def maximums(row1, row2) : return map(max, row1, row2)
... | 36722e4250dde561836c1ea3042b796ed7650986 | 3,655,904 |
def entities(address_book):
"""Get the entities utility."""
return zope.component.getUtility(IEntities) | 6c64c5c8b8d0048425dcd91baf265134fbb2e96e | 3,655,905 |
from renku.core.management.migrations.models.v9 import Project
import pathlib
def generate_dataset_file_url(client, filepath):
"""Generate url for DatasetFile."""
if not client:
return
try:
if not client.project:
return
project = client.project
except ValueError:
... | 1aa3a97cfff523e0b7d7718c39dfb9935160e193 | 3,655,906 |
def _check_attrs(obj):
"""Checks that a periodic function/method has all the expected attributes.
This will return the expected attributes that were **not** found.
"""
missing_attrs = []
for attr_name in _REQUIRED_ATTRS:
if not hasattr(obj, attr_name):
missing_attrs.append(attr_... | 6a3326616aa5d1cd083f99a2e0f4c57f6f5a11c6 | 3,655,907 |
def TokenStartBlockElement(block):
"""
`TokenStartBlockElement` is used to denote that we are starting a new block element.
Under most circumstances, this token will not render anything.
"""
return {
"type": "SpaceCharacters",
"data": "",
"_md_type": mdTokenTypes["TokenStartB... | c7690b2ca7babc0cc5d6e36a8b8ecb33ad463294 | 3,655,908 |
import json
def parse_json(json_path):
"""
Parse training params json file to python dictionary
:param json_path: path to training params json file
:return: python dict
"""
with open(json_path) as f:
d = json.load(f)
return d | c34b241813996a8245ea8c334de72f0fbffe8a31 | 3,655,909 |
from unittest.mock import call
def cut_tails(fastq, out_dir, trimm_adapter, trimm_primer, hangF, hangR):
"""
The functuion ...
Parameters
----------
reads : str
path to ...
out_dir : str
path to ...
hang1 : str
Sequence ...
hang2 : str
Sequence ...
R... | 8e4ef0b24d5ecf22aa298a0e4e8cddeb7d681945 | 3,655,910 |
def load_spelling(spell_file=SPELLING_FILE):
"""
Load the term_freq from spell_file
"""
with open(spell_file, encoding="utf-8") as f:
tokens = f.read().split('\n')
size = len(tokens)
term_freq = {token: size - i for i, token in enumerate(tokens)}
return term_freq | 236cb5306632990e1eefcf308dea224890ccd035 | 3,655,912 |
def NotP8():
"""
Return the matroid ``NotP8``.
This is a matroid that is not `P_8`, found on page 512 of [Oxl1992]_ (the
first edition).
EXAMPLES::
sage: M = matroids.named_matroids.P8()
sage: N = matroids.named_matroids.NotP8()
sage: M.is_isomorphic(N)
False
... | d475810244338532f4611b120aa15b4776bd2aeb | 3,655,913 |
def eqv(var_inp):
"""Returns the von-mises stress of a Field or FieldContainer
Returns
-------
field : ansys.dpf.core.Field, ansys.dpf.core.FieldContainer
The von-mises stress of this field. Output type will match input type.
"""
if isinstance(var_inp, dpf.core.Field):
return _... | 5977b1317fc5bfa43c796b95680a7b2a21ae4553 | 3,655,914 |
def sort(array: list[int]) -> list[int]:
"""Counting sort implementation.
"""
result: list[int] = [0, ] * len(array)
low: int = min(array)
high: int = max(array)
count_array: list[int] = [0 for i in range(low, high + 1)]
for i in array:
count_array[i - low] += 1
for j in range(1,... | 86864db6e012d5e6afcded3365d6f2ca35a5b94b | 3,655,915 |
def build_updated_figures(
df, colorscale_name
):
"""
Build all figures for dashboard
Args:
- df: census 2010 dataset (cudf.DataFrame)
- colorscale_name
Returns:
tuple of figures in the following order
(datashader_plot, education_histogram, income_histogram,
... | 01dd0f298f662f40919170b4e37c533bd3ba443b | 3,655,916 |
from typing import Optional
def get_or_else_optional(optional: Optional[_T], alt_value: _T) -> _T:
"""
General-purpose getter for `Optional`. If it's `None`, returns the `alt_value`.
Otherwise, returns the contents of `optional`.
"""
if optional is None:
return alt_value
return optiona... | 340fc67adc9e73d748e3c03bec9d20e1646e894c | 3,655,918 |
def create_dic(udic):
"""
Create a glue dictionary from a universal dictionary
"""
return udic | aa854bb8f4d23da7e37aa74727446d7436524fe2 | 3,655,919 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.