content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def select_tables():
"""Select all table names from sqlite_master."""
return (sa.select(sqlite_master.c.name)
.select_from(sqlite_master)
.filter_by(type='table')
.where(~sqlite_master.c.name.like('sqlite_%'))
.order_by('name')) | 67,800 |
def parallel_train(trainh: TrainHolder, folder_name=None, folder_list=None, max_threads=None, shuffle=True, seed=None, debug_mode=False):
"""
folder_name : str
folder_list : str
find all classes in folder_name and/or one by one in folder_list
max_threads : int
max number of threads for ... | 67,801 |
def get_sparse_index(x, sparse_index_dict, feat):
"""sparse特征id编码"""
if feat in sparse_index_dict:
values = sparse_index_dict[feat]
if x in values:
return values.index(x)
else:
return len(values) #unk问题
else:
raise LookupError("{} is not in sparse_ind... | 67,802 |
def nonzero_rmse(y_true, y_pred):
"""RMSE that ignores zero values, assuming that there is at least
one nonzero value per row
"""
mask = K.cast(K.not_equal(y_true, 0), K.floatx())
count = K.sum(mask, 1)
se = K.sum(K.square(y_true-y_pred)*mask, 1)
rmse = K.sqrt(se / count)
return K.mean(r... | 67,803 |
def scroll_out(experiment, stimulus, movement_direction, pixel_per_ms = 0.5,
reset_position=False):
"""Scroll stimulus out of the screen.
Parameters
----------
experiment : Expyriment experiment
the currently running experiment
stimulus : Expyriment stimulus
the stimu... | 67,804 |
def __add_vertex_to_occurence(
first_occurence: Dict[Vertex, int],
second_occurence: Dict[Vertex, int],
vertex: Vertex,
index: int,
) -> None:
"""Add vertex to either the first or second occurence lookup"""
if vertex in first_occurence:
second_occurence[vertex] = index
elif vertex no... | 67,805 |
def _infer_storage_long_name(field: xr.DataArray) -> str:
"""Infer the long_name for the storage component of a budget."""
field_long_name = field.attrs.get("long_name", field.name)
return f"Storage of {field_long_name}" | 67,806 |
def get_sparsity(arr):
"""Calculates sparsity of ndarray (0 - 1)"""
if isinstance(arr, np.ndarray):
return 1 - (np.count_nonzero(arr) / arr.size)
elif isinstance(arr, pd.DataFrame):
return arr.isnull().sum().sum() / arr.size
else:
raise TypeError("input must be a numpy array") | 67,807 |
def update_board(screen, event, first, last, peg_color, flag):
"""update the board as guesses are made"""
global LOCATION, POSITION, GUESS_LIST_SCREEN
pygame.draw.rect(screen, WHITE, SHIELD)
if event.type == QUIT:
saved_game = shelve.open("SavedGame")
saved_game['Story_Mode_Finished... | 67,808 |
def jvp_solve_Ez_source(g, Ez, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER):
""" Gives jvp for solve_Ez with respect to source """
A = make_A_Ez(info_dict, eps_vec)
return 1j * info_dict['omega'] * sparse_solve(A, g, iterative=iterative, method=method) | 67,809 |
def submit(script_name: str = 'script.sh', env_name: Optional[str] = None):
"""Submit script to cluster.
Usage:
`fab submit:script_name`
"""
cmd = "umask g+rwx"
# set env vars on cluster
for key, val in env_vars.items():
cmd += f'; export {key}={val}'
cmd += f'; export CLUSTER_... | 67,810 |
def is_unary_operator(oper):
"""returns True, if operator is unary operator, otherwise False"""
# definition:
# memeber in class
# ret-type operator symbol()
# ret-type operator [++ --](int)
# globally
# ret-type operator symbol( arg )
# ret-type operator [++ --](X&, int)
symbols = [... | 67,811 |
def read_sparse(*args, **kwargs):
"""
given a collection of file paths representing relational data
returns a pandas pandas DataFrame of the data
:param args: collection of file paths representing an input file
:param kwargs: keyword arguments to pass to pandas read function
:return: pandas Data... | 67,812 |
def save_credentials(credentials):
"""
Function to save credentials
:param credentials:
"""
credentials.save_credentials() | 67,813 |
def IM_write(self):
""" IntcodeMachine append to outputs[] the value given by parameter 1 """
value = self.nth_value(1) # value of parameter 1
self.outputs.append(value) # write to output
self.ip += 2 # skip past (instruction, param_1) | 67,814 |
def clear_logs() -> NoReturn:
"""Deletes log files that were updated before 48 hours."""
for __path, __directory, __file in os.walk('logs'):
for file_ in __file:
if int(time.time() - os.stat(f'{__path}/{file_}').st_mtime) > 172_800:
os.remove(f'{__path}/{file_}') | 67,815 |
async def create_app() -> web.Application:
"""Create an web application."""
app = web.Application(
middlewares=[
cors_middleware(allow_all=True),
error_middleware(), # default error handler for whole application
],
)
# Set up logging
logging.basicConfig(level... | 67,816 |
def split3(img):
"""Splits a 3-channel image into its constituent channels.
Convenience function using numpy slices, ~300x faster than cv2.split()."""
assert(isinstance(img, numpy.ndarray))
assert(nchannels(img) == 3)
return img[:, :, 0], img[:, :, 1], img[:, :, 2]
#TODO: split into column vect... | 67,817 |
def when(obj, strict=True):
"""Central interface to stub functions on a given `obj`
`obj` should be a module, a class or an instance of a class; it can be
a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface
where you configure a stub in three steps::
when(<obj>).<method_... | 67,818 |
def before_request():
"""Set variables before each request."""
host_parts = request.host.split('.')
if 'www' in host_parts:
host_parts.remove('www')
g.project_name = PROJECT_NAME or host_parts[0]
g.config = CONFIG[g.project_name]
g.variables = CONFIG[g.project_name].config_tree.copy() | 67,819 |
def get_nrg_const_hyb_coefficients(V, Lambda, nof_coefficients, corrected=True):
"""
Coefficients for the exact chain mapping for a constant hybridization in the SIAM, V_k = V
(equivalent to setting Delta(eps) = pi*V^2 / 2, for eps in [-1.0, 1.0])
using logarithmic discratization
Sou... | 67,820 |
async def async_setup(hass):
"""Set up the Hassbian config."""
hass.http.register_view(CheckConfigView)
websocket_api.async_register_command(hass, websocket_update_config)
websocket_api.async_register_command(hass, websocket_detect_config)
return True | 67,821 |
def blink_color(lifx: Group, colors: Optional[ColorTheme] = None, blink_time_secs=.5, how_long_secs=8):
"""change colors on lights every `blink_time_secs`"""
num_cycles = math.ceil(how_long_secs / blink_time_secs)
theme = colors_to_theme(colors) or (Colors.COPILOT_BLUE, Colors.COPILOT_DARK_BLUE)
with li... | 67,822 |
def split_apt(field):
"""
Parses the ADDRESS field (<site address>, <apt number> <municipality>) from the CLEMIS CFS Report
and returns the apartment number.
"""
if ',' in field:
f = field.split(', ')
f = f[1]
f = f.split(' ')
apt = f[0]
else:
apt = None
... | 67,823 |
def sin(angle):
"""
Examples
>>> sin(90*degrees)
1.0
"""
if is_quantity(angle):
return math.sin(angle/radians)
else:
return math.sin(angle) | 67,824 |
def tempread(fp: str):
"""reads an audio file into a numpy array via a temp file
Returns a tuple containing the sample rate in Hz followed by the audio
data
"""
if not FFMPEG_INSTALLED:
raise FFmpegException("ffmpeg is not available")
fp = os.path.abspath(os.path.expanduser(fp))
# generat... | 67,825 |
def random_series(
n: int = 1,
dtype=int,
p_missing: float = 0,
astype=None,
low: (int, float) = 0,
high: (int, float) = 1,
):
"""
Generate random pandas Series with given length, type and
percentage of corrupted data.
Parameters
----------
n : int, optional
... | 67,826 |
def compile_partition(formulaPartition):
"""
Compile a formula Partition of UPPER case letters as numeric digits.
E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
Non-uppercase Partitions unchanged: compile_word('+') => '+'
"""
if formulaPartition.isupper():
terms = [('{}*{}'.format(10**i... | 67,827 |
def cla():
"""Clear the current axes."""
# Not generated via boilerplate.py to allow a different docstring.
return gca().cla() | 67,828 |
def is_distinguished_by_hyp_invars(M, s, t, tries, verbose):
"""
Given a manifold M and two slopes (where we think that both
fillings are hyperbolic), try to prove that M(s) is not
orientation-preservingly homeomorphic to M(t).
Returns a tuple of booleans (distinguished, rigor)
distinguished is... | 67,829 |
def camel_to_snake_case(name):
"""
AssimilatedVatBox --> assimilated_vat_box
"""
exceptional = {
"avg_c_p_a": "avg_cpa",
"avg_c_p_m": "avg_cpm",
"avg_c_p_t": "avg_cpt"
}
sn = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
sn = sn.split(" ")[0] # i.e. "duration (in se... | 67,830 |
def initialize_and_download(datadir, state, year, horizon, survey, download=False):
"""Download the dataset (if required)."""
assert horizon in ['1-Year', '5-Year']
assert int(year) >= 2014
assert state in state_list
assert survey in ['person', 'household']
state_code = _STATE_CODES[state]
... | 67,831 |
def test_biosamples_list__slow_response_retry_list(mocker):
"""Test BaseSpace Biosamples slow response retry on the list."""
runner = CliRunner()
mocked_login = mocker.patch.object(APIClient, "login", return_value=None)
mocked_list_biosamples = mocker.patch.object(
APIClient,
"list_biosa... | 67,832 |
def get_all_members():
"""Gets all current members (potential hassle participants)."""
query = sqlalchemy.text("""
SELECT user_id, name, graduation_year,
member_type, membership_desc, user_id IN (
SELECT user_id FROM hassle_participants
) AS participating
FROM members
NATURAL JOIN ... | 67,833 |
def content(f, *gens, **args):
"""Returns GCD of polynomial coefficients. """
F = NonStrictPoly(f, *_analyze_gens(gens), **args)
if not F.is_Poly:
raise GeneratorsNeeded("can't compute content of %s without generators" % f)
else:
return F.content() | 67,834 |
def entropy_of_list(lst):
"""Given a list of values, generate histogram and calculate the entropy."""
unique_values = N.unique(lst)
unique_counts = N.array([float(len([i for i in lst if i == unique_val])) for unique_val in unique_values])
total = N.sum(unique_counts)
probs = unique_counts/total
... | 67,835 |
def cli(ctx, app, filename):
"""Update an application with your developer account."""
try:
ctx.is_auth_valid()
try:
app = int(app)
except:
app = read_app_id_from_config(app)
if app is None:
raise AppIdInvalid("Please check if applicat... | 67,836 |
def polygon_from_points(points):
"""
Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4
"""
resBoxes = np.empty([1, 8], dtype='int32')
resBoxes[0, 0] = int(points[0])
resBoxes[0, 4] = int(points[1])
resBoxes[0, 1] = int(points[2])
res... | 67,837 |
def get_awsathena_db_name(db_name_env_var: str = "ATHENA_DB_NAME") -> str:
"""Get awsathena database name from environment variables.
Returns:
String of the awsathena database name.
"""
athena_db_name: str = os.getenv(db_name_env_var)
if not athena_db_name:
raise ValueError(
... | 67,838 |
def get_microservice_target_directory(path: Path, name: str) -> Path:
"""Get the target directory for a microservice.
:param path: The starting path.
:param name: The name of the microservice.
:return: A ``Path`` instance.
"""
current = path
while current != current.parent:
if (curr... | 67,839 |
def load_experiments(file_name, experiment_names=None):
""" Returns experimental parameters for experiment names of choice.
:param file_name: str. Only the file name (not the path) of the yml file, located in conf folder.
:param experiment_names: list. List of the experiment names to be loaded. Non... | 67,840 |
def update_order_status(order_id):
"""updates order status
"""
if request.method == "PUT":
data = request.get_json()
if not data.get('complete'):
return FeedbackResponse.display("status changed to complete", 406)
complete = data.get('complete')
status = customer_... | 67,841 |
def BasicTest():
"""Return a new class - we do it this way to allow this to work properly for multiple tests"""
class _BasicTest(unittest.TestCase):
"""Holder class which gets built into a whole test case"""
dialect = 'VB6'
container = vb2py.parserclasses.VBModule
return _BasicTest | 67,842 |
def category_to_detection_name(category_name: str) -> Optional[str]:
"""
Default label mapping from nuScenes to nuScenes detection classes.
Note that pedestrian does not include personal_mobility, stroller and wheelchair.
:param category_name: Generic nuScenes class.
:return: nuScenes detection clas... | 67,843 |
def derive_schema_path(catalog, request_version, schema):
"""Handle the implicit schema case by falling back on locally provided schema (matching the catalog)."""
if schema:
LOG.debug(f"xml validate try reading schema catalog={catalog},"
f" schema={schema}, catalog env=({os.getenv('XML... | 67,844 |
def acosh(x):
"""
Calculates the hyperbolic arccosine of the given input tensor element-wise.
Args:
x (Tensor): Input tensor
Returns:
Tensor, the output
"""
return Acosh()(x)[0] | 67,845 |
def multiclass_positive_predictive_value(confusion_matrix: np.ndarray,
label_index: int) -> float:
"""
Gets the "positive predictive value" for a multi-class confusion matrix.
The positive predictive value is also known as *precision*.
See the documentation of
... | 67,846 |
def mine_next_block(last_block, difficulty=None):
"""Generate and return the next block in the chain.
Arguments:
last_block: the last block in the chain to point to
difficulty: [int] the difficulty, number of zeros the hash much start with
Returns:
A new Block to be appended to the... | 67,847 |
def flatten_enumeration(my_enumeration):
""" Flatten a dictionary of DCIMAttributeObjects """
pure_dictionary = {k: v.dictionary for k, v in my_enumeration.items()}
return flatten_dict(pure_dictionary) | 67,848 |
def transliterate(string: str) -> str:
# Copy from inflection Library https://github.com/jpvanhal/inflection
"""
Replace non-ASCII characters with an ASCII approximation. If no
approximation exists, the non-ASCII character is ignored. The string must
be ``unicode``.
Examples::
>>> transl... | 67,849 |
def plot_envelope_interrupts(envelope, interrupt_t, thresholds):
""" Creates a pretty plot of the signal, interrups, and thresholds.
"""
fig, ax = plt.subplots()
# The signalFORMAT = pyaudio.paInt16
plt.plot(envelope)
# Points at each interrupt
plt.scatter(interrupt_t, np.array([1000]*len(in... | 67,850 |
def zfs_create_zvol(volume: str,
size: int,
size_suffix: str = "G",
blocksize: int = None,
create_parent: bool = False,
sparse: bool = False,
properties: list = None) -> str:
"""
zfs create [... | 67,851 |
def test_copy_exam(dummy_exam):
"""GIVEN an exam
WHEN a copy is made
THEN the new one is identical"""
ex = dummy_exam
new_ex = ex.copy()
for ex_question, new_ex_question in zip(ex.questions, new_ex.questions):
assert ex_question.text == new_ex_question.text
assert ex_question.le... | 67,852 |
def delete_ec2_nodes(
instance_id_list,
client=None
):
"""This deletes EC2 nodes and terminates the instances.
Parameters
----------
instance_id_list : list of str
A list of EC2 instance IDs to terminate.
client : boto3.Client or None
If None, this function will in... | 67,853 |
def handle_test_runners(args):
"""usage: {program} test-runners
List the available test-runner plugins.
"""
assert args
print('\n'.join(cosmic_ray.plugins.test_runner_names()))
return ExitCode.OK | 67,854 |
def filter_by_status(project_name:str,
dataset_name:str,
task_id:str,
status:str,
email:str,
timestamp:str):
"""
Function to filter items per task by status, works for all statuses (e.g., approved, completed... | 67,855 |
def show_std_icons():
"""
Show all standard Icons
"""
app = qapplication()
dialog = ShowStdIcons(None)
dialog.show()
sys.exit(app.exec_()) | 67,856 |
def real_device_online_setup(
arntask,
creds,
s3_folder,
info,
search_value,
device_value,
res_completed,
results_json,
):
"""Real device online value test setup."""
qtarntask = {'quantumTaskArn': arntask}
body = StreamingBody(StringIO(results_json), len(results_json))
re... | 67,857 |
def cli(ctx, secrets_file, data_dir):
""" Code running for all commands """
ctx.obj = {}
# Try to get a setting dir
if data_dir:
data_dir = Path(data_dir)
if not data_dir.isdir():
click.echo("Setting dir does not exist. Attempting to create one.")
try:
... | 67,858 |
def hex(value):
"""
return `value` in hex format
:param value:
:return:
"""
return hex(value) | 67,859 |
def change_password(session, uid_hash, current_password, new_password, logout_sessions=True):
"""Change the User's Password.
Change or set the user password and create a new user hash so that
any login tokens referencing the current user will be invalidated and
the sessions must log in again with the n... | 67,860 |
def test_observe():
"""
Parameters
----------
Returns
-------
"""
# Create hi-res wavelength grid
lamhr = np.linspace(0.2, 2.5, int(1e4))
# Create fake hi-resolution reflectivity
Ahr = 0.1 + 0.1 * lamhr * np.sin(np.pi * lamhr / 5.)
# Create fake stellar flux
Bstar =... | 67,861 |
def get_amino_acids(table):
"""
Get field "amino acids" from table
Receives a results table
Returns a list of amino acids
"""
return get_field(table, 1) | 67,862 |
def eval(dataset, meta_learner, test_langs, ext, proto):
"""
Cross-lingual Evaluation
:param dataset:
:param meta_learner:
:param test_langs:
:param ext:
:param proto:
:return:
"""
metrics = meta_learner.zero_shot_test(test_langs, dataset, ext, proto)
print("metrics:", metri... | 67,863 |
def add_remote_dataset_metadata(
root,
dataset_name,
bucket_name,
service_endpoint,
authentication='Anonymous',
region='us-west-2'
):
""" Add metadata to upload remote version of dataset.
Arguments:
root [str] - root data folder of the project
dataset_name [str] - name o... | 67,864 |
def add_host_network(host_id):
"""add host network.
Must fields: ['interface', 'ip', 'subnet_id']
Optional fields: ['is_mgmt', 'is_promiscuous']
"""
data = _get_request_data()
return utils.make_json_response(
200, host_api.add_host_network(host_id, user=current_user, **data)
) | 67,865 |
def get_inverse_transform(transform):
"""Generates a transform which is the inverse of the provided transform"""
inverse_transform = [0] * len(transform)
for i in range(len(transform)):
inverse_transform[transform[i]] = i
return inverse_transform | 67,866 |
def recover_password(email: str) -> Any:
"""
Password Recovery
"""
user = user_crud.get_by_email(db, email=email)
if not user:
raise HTTPException(
status_code=404,
detail="The user with this username does not exist in the system.",
)
password_reset_token... | 67,867 |
def is_text(filename):
"""Return True if file is a text file.
This is a guess. Files with null bytes are considered to be binary.
Also, files that start with an extremely long line are considered to
be binary. Empty files are considered as not text.
"""
if os.path.islink(filename):
ret... | 67,868 |
def fill_zeros(symbol: int):
"""
将 数字 symbol 填满为 00开头的6位号
:param symbol:
:return:
"""
if symbol < 100000:
b_ = 6 - len(str(symbol))
return ('0' * b_ + str(symbol))
else:
return str(symbol) | 67,869 |
def load_strace_results(target_dir=TARGET_DIR, force=False):
"""Read and search strace results and retain internet addresses
with ports and executed files. Collect the strace results and
serialize to JSON for faster deserialization.
"""
if STRACE_RESULTS_FILE.exists() and not force:
logger.... | 67,870 |
async def get_statistics(request):
"""
Returns summary statistics on all available currencies
"""
version = request.app['openapi']['info']['version']
currency_stats = list()
db = request.app['db']
aws = [get_currency_statistics(request, currency, version)
for currency in db.get_su... | 67,871 |
def squeeze_integers(intVec):
"""
Make integers in an array consecutive numbers
starting from 0. ie. [7,2,7,4,1] -> [3,2,3,1,0].
Useful for removing unused class IDs from y_true
and outputting something appropriate for softmax.
This is v2. The old version is busted.
RH 2021
Args:
... | 67,872 |
def get_organization(organization_uri):
"""
Given the URI of an organnization, return an object that contains the
organization it represents.
As for most of the access functions, additional attributes can be added.
"""
organization = {'organization_uri':organization_uri}
organization['uri']... | 67,873 |
def dist(a=array([]),b=array([])):
"""
Compute euclidean distance between 2 points given by 2 arrays.
"""
n1=len(a)
n2=len(b)
d=0.0
if (n1==n2):
d2 = (a - b)*(a - b)
d = sum(d2,axis=0)
return (sqrt(d)[0])
else :
print("ERROR: Coordinates are not i... | 67,874 |
def extract_fields(gh_json, fields):
"""
extract_fields Extract field from GH API data
Extract fields from GH API data and standardize name of keys
Parameters
----------
gh_json : json
JSON content from Github
fields : dict
A list of fields to extract and the name we want t... | 67,875 |
def PersistProperty(prop, value, scope=None):
"""Sets the given property in the properties file.
This function should not generally be used as part of normal program
execution. The property files are user editable config files that they should
control. This is mostly for initial setup of properties that get ... | 67,876 |
def pytest_addoption(parser):
"""Support command line marks."""
for mrk in MARKERS:
parser.addoption(
f"--{mrk}", action="store_true", help=f"include the {mrk} tests"
) | 67,877 |
def define_network_parameters(m, data):
"""Define network parameters"""
# Max voltage angle difference between connected nodes
m.P_NETWORK_VOLTAGE_ANGLE_MAX_DIFFERENCE = pyo.Param(initialize=float(math.pi / 2), mutable=True)
# Branch susceptance matrix elements
m.P_NETWORK_BRANCH_SUSCEPTANCE = pyo... | 67,878 |
def bayesian_prob(counts, tuning_curves, binsize, min_neurons, min_spikes=1):
"""Computes the bayesian probability of location based on spike counts.
Parameters
----------
counts : nept.AnalogSignal
Where each inner array is the number of spikes (int) in each bin for an individual neuron.
t... | 67,879 |
def distance(waypoints, wp1, wp2):
"""Compute distance between to waypoint indices"""
dist = 0
def d_l( a, b ):
return math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)
for i in range(wp1, wp2+1):
dist += d_l(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.pos... | 67,880 |
def clustering_coefficient_weighted(user, interaction=None):
"""
The clustering coefficient of the user's weighted, undirected network.
It is defined the same way as :meth`~bandicoot.network.clustering_coefficient_unweighted`,
except that closed triplets are weighted by the number of interactions. For
... | 67,881 |
def user_by_group(ctx, server, username, password):
"""Fetch user by group"""
# TODO | 67,882 |
def test_renyi_entropy_3(alpha):
"""
Test that negative orders raise ValueErrors.
"""
d = uniform(8)
with pytest.raises(ValueError):
renyi_entropy(d, alpha) | 67,883 |
def time_lag(lc1, lc2):
"""
Estimate the time lag of two light curves.
Calculate time lag and uncertainty.
Equation from Bendat & Piersol, 2011 [bendat-2011]_.
Parameters
----------
lc1: :class:`stingray.Lightcurve` object
The first light curve data for the channel of interest.
... | 67,884 |
def init_pygit2():
""":raise ImportError: if pygit2 is not present"""
try:
import pygit2
except ImportError:
raise ImportError("Could not find 'pygit2' in the PYTHONPATH - pygit2 functionality is not available")
#END handle pygit2 import | 67,885 |
def pad_batch_tensorize(inputs, pad, cuda=True):
"""
pad_batch_tensorize
找到最长文章,拉齐,填pad ,tensor化
:param inputs: List of size B containing torch tensors of shape [T, ...] T32
:type inputs: List[np.ndarray]
:rtype: TorchTensor of size (B, T, ...)
"""
tensor_type = torch.cuda.LongTe... | 67,886 |
def as_json(config: Dict[str, Any], **json_args: Any) -> None:
"""Use json standard library to write JSON file"""
return json.dumps(config, **json_args) | 67,887 |
def get_etfs_by_name(name: str) -> Dict:
"""Return a selection of ETFs based on name filtered by total assets. [Source: Finance Database]
Parameters
----------
name: str
Search by name to find ETFs matching the criteria.
Returns
----------
data : Dict
Dictionary with ETFs t... | 67,888 |
def delete_event(id):
"""Deletes an event
:param id: the id of the event
:returns: a dictionary with a response of success or failure
"""
response = db(db.events.id==id).delete()
return dict(response=response) | 67,889 |
def train_classifier(dataframe, labels, maxlen, max_features, batch_size, epochs, model_save_dir, model_log_dir):
"""train the multilabel classifier
Parameters
----------
dataframe : dataframe
the generated dataframe from data folder
labels : str
the extracted labels
maxlen : i... | 67,890 |
def parametric(Class=None, runtime_type_of=False, metaclass=CovariantMeta):
"""A decorator for parametric classes.
When the constructor of this parametric type is called before the type parameter
has been specified, the type parameters are inferred from the arguments of the
constructor by calling the f... | 67,891 |
def add_qartod_ident(qartod_id, qartod_test_name):
"""
Adds attributes to the QARTOD functions corresponding to database fields.
Mostly for internal use
:param qartod_id: The QARTOD test identifier, as represented by an integer
:param qartod_test_name: The test name as stored in the database.
"... | 67,892 |
async def get_balance(
user_id: int,
db_con: Connection,
convert_to: Optional[str] = None,
) -> Decimal:
"""Get user account balance.
Args:
user_id: user id
db_con: database connection
convert_to: currency for convertation
Returns:
balance value
"""
asyn... | 67,893 |
def _save_to_file(template_dir: str, file_name: str, content: str):
"""save template result to the file"""
if not os.path.exists(template_dir):
os.mkdir(template_dir)
path = os.path.join(template_dir, file_name)
with open(path, 'w', encoding='utf-8') as f:
f.write(content) | 67,894 |
def output_factory(writer_format: str = "pqr") -> Writer:
"""Provides the writer based on the output format.
:param writer_format: Format indicating with writer to use
:type writer_format: str
:return: Writer object for a given output factory
:rtype: Writer
"""
writer_type = writer_forma... | 67,895 |
def run(optimizer, objectivefunc, NumOfRuns, params, export_flags):
"""
It serves as the main interface of the framework for running the experiments.
Parameters
----------
optimizer : list
The list of optimizers names
objectivefunc : list
The list of benchmark functions
NumO... | 67,896 |
def imshow(img, text ='Image'):
"""
imshow(img, text='')
AfmImgをカラーの画像ファイルとして表示する関数です。
引数
----------
img : 表示するAfmImg形式の画像
text : 表示するウィンドウのタイトル(オプション)
戻り値
-------
なし
"""
cv2.namedWindow(text, cv2.WINDOW_KEEPRATIO | cv2.WINDOW_NORMAL)
cv2.imshow(text, img.getOpenCV... | 67,897 |
def handlerInit(service,node):
"""pyvel initialization.. This is where we load
our modules and setup the state objects"""
if not service.state.has_key("groups"):
service.state["groups"]={'/':{}}
if not service.state.has_key("games"):
service.state["games"]={}
rdict={}
for n in no... | 67,898 |
def unflatten_wave(y, shape):
""" Unflatten a flattened array.
Parameters
----------
y: ndarray 1D
a flattened input array.
shape: list of dict
the output structure information.
Returns
-------
x: list of ndarray
the unflattened dataset.
"""
... | 67,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.