content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_context(config_fname: str, ignore_io_errors: bool, **kwargs):
"""
Load the config yaml as the base context, and enrich it with the
information added by the context preprocessors defined in the file.
"""
with open(config_fname) as f:
context = yaml.safe_load(f)
context["source_pa... | 5,292,800 |
def run_demo(num_primes=30):
""" Calculate primes by recursive filtering """
input = OneOne()
output = ManyOne()
@fork_proc
def source():
for n in itertools.count(start=2):
input << n
def worker(port_in, port_out):
prime = ~port_in
port_out << prime
... | 5,292,801 |
def setup_suite(config_file, time0, n_sixhr_segs, run_dir):
"""main program"""
sanity_check(config_file, time0, n_sixhr_segs, run_dir)
config = ecfsetup.read_config_file(config_file)
two_levels_up = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'..',
'..')
... | 5,292,802 |
def get_group_members(user: User, user_group: UserGroup) -> List[User]:
"""
Get the users who belong to this group.
:param user:
:param user_group:
:return:
"""
return get_read_permitted_records(user, user_group.members) | 5,292,803 |
def show_alert_aggregate(state, alert_id):
"""Show an aggregated alert details view."""
alert_data = get_alert_aggregate_data(state.sdk, alert_id)
output_pretty(alert_data) | 5,292,804 |
def test_can_instantiate_system():
"""
Test that system imports properly and its constructor works.
"""
assert System
system = System(1, 1, 'o', (255, 0, 0), 'test', 'test', None, 5, 0, 0, 0, 0)
assert type(system) is System | 5,292,805 |
def set_dataset_args(args, fields, multi_label_data=None):
"""Return dataset arguments dict
"""
dataset_args = set_basic_dataset_args(args)
objective_field = (None if not hasattr(args, 'objective_field')
else args.objective_field)
if multi_label_data is not None and objective... | 5,292,806 |
def complete(request, reference_id):
""" Upon completion of a transaction, users are sent back to this URL.
If SIMPLEPAY_COMPLETE_REDIRECT is defined in settings.py, the user will
be redirected to this URL. Otherwise the simplepay.transaction_complete.html
template will be displayed to ... | 5,292,807 |
def debug():
"""Determine whether to we are in debugging mode."""
# look through all open files to see if this plugin is currently being
# edited
for w in sublime.windows():
for v in w.views():
if v.file_name() == __file__:
return True
return False | 5,292,808 |
def load_corpus(corpus, split=0.8, V=10000, shuffle=0):
"""Load a named corpus and split train/test along sentences.
This is a convenience wrapper to chain together several functions from this
module, and produce a train/test split suitable for input to most models.
Sentences are preprocessed by canon... | 5,292,809 |
def get_graylog_response(message, fields=None):
"""Search for a given log message (with possible additional fields)
within a local Graylog instance"""
fields = fields if fields else []
tries = 0
while True:
try:
return _parse_api_response(
api_response=_get_api_r... | 5,292,810 |
def blend2(*args, **kwargs):
"""
This command creates a surface by blending between given curves. This is an enhancement (more user control) compared to
blend which is now obsolete.
Flags:
- autoAnchor : aa (bool) [create,query,edit]
If true and both paths ar... | 5,292,811 |
def decrypt(sk, c):
"""Decrypt a cyphertext based on the provided key."""
return (c % sk) % 2 | 5,292,812 |
def _collapse_series_by_column(grouped_series, sort_data_col):
"""
For each grouped series, take each of its timeseries and
organize them by a data column/key name. Group by the specified
column/key name and extract metadata from them. This intended
to help with cases where there are multiple series... | 5,292,813 |
def ramp9(params, phase, args=dict(n=6, guess=[1, 0.003, 0.6, 0.009, 0.35, 4e-4])):
"""Model Ramp Eq. 9 from Stevenson et al. (2011).
params: 6-sequence
parameters that define the function, as shown below.
phase: NumPy array.
Orbital phase (or more generally, 'time')
Functional form:
... | 5,292,814 |
def test_do_fft_and_ifft():
"""Recover the original array after fft and ifft."""
arr2d_f = fourier.do_fft(arr2d, dim=2)
arr2d_r = fourier.do_ifft(arr2d_f, dim=2)
assert np.allclose(arr2d_r, arr2d) | 5,292,815 |
def view_other_user(request, other_user_id):
"""
Allows the user to view another users profile, and send them follow/friend requests.
Depending on what the relationship is between the user and other_user_id, different
templates will be rendered.
"""
if User.objects.filter(id=other_user_id, type... | 5,292,816 |
def rebin_image(bin_size, image, wht_map, sigma_bkg, ra_coords, dec_coords, idex_mask):
"""
rebins pixels, updates cutout image, wht_map, sigma_bkg, coordinates, PSF
:param bin_size: number of pixels (per axis) to merge
:return:
"""
numPix = int(len(image)/bin_size)
numPix_precut = numPix * ... | 5,292,817 |
def resize_and_crop(image, new_width, new_height, crop=True):
"""
Resize image and maintain aspect ration, then crop
:param image: input image as PIL Image
:param new_width: width of crop
:param new_height: height of crop
:param crop: False if only resizing is required
:return: resized (and ... | 5,292,818 |
def merge_dataframes(df1, df2, df1_column_names, column_keys):
"""
Merge two dataframes using a column value as a key.
Args:
df1 (table): [description]
df2 (table): [description]
column_keys (string): [description]
"""
df1 = df1[df1_column_names]
df1[column_key... | 5,292,819 |
def find_long_enough_videos(dataset_root, min_video_length=8):
"""Find videos whose length is longer than min_video_length, and write their paths
into a txt
Args:
dataset_root(Path): root to your dataset
min_video_length(int): the minimal frames you want to have in a video."""
all_... | 5,292,820 |
def chmod(config):
"""Set correct file permissions."""
output_dir = config["output_dir"]
for dirpath, dirnames, filenames in os.walk(output_dir):
for dirname in dirnames:
os.chmod(os.path.join(dirpath, dirname), 0755)
for filename in filenames:
os.chmod(os.path.join(d... | 5,292,821 |
def hmsdms_to_deg(ra='05h56m0s', dec='+07d25m0s'):
"""
Determine Coordinates in degree from format {RA in HMS, DEC in DMS} to {RA and DEC in degrees}
This can then be copy/pasted in http://simbad.u-strasbg.fr/simbad/sim-fcoo
Example usage:
_ = hmsdms_to_deg(ra='05h55m10.30536s', dec... | 5,292,822 |
def delete_user(
user: UserBase = Depends(auth_user),
db: Session = Depends(get_db)
)-> Dict[str, Any]:
"""
deletes the currently logged in user
Parameters
----------
None
Returns
--------
user_id : UUID
"""
return crud_user.delete_user(db, _id=user.uid).dict(excl... | 5,292,823 |
def de_coalesce_visibility(vis: Visibility, vistemplate: Visibility, params={}) -> Visibility:
""" De-coalesce visibility in time and frequency i.e. replicate to template Visibility
This is the opposite of coalescing - the Visibility is expanded into sampling independent
of baseline length.
:p... | 5,292,824 |
def adapt_session(session, book, readonly):
"""
Change the SA session object to add some features.
:param session: the SA session object that will be modified in place
:param book: the gnucash singleton book linked to the SA session
:param readonly: True if the session should not allow commits.
... | 5,292,825 |
def stickyheptominos_twocolor(rows, cols, seed=None):
"""
A row sticky heptominos, with jitter and randomly oriented.
"""
if seed is not None:
random.seed(seed)
centerx = cols // 2
centery = rows // 2
# Place one methuselah every N grid spaces
# maximum number - 1
n = 10
... | 5,292,826 |
def list_images(remove_ext=True):
"""Based on the .png files in the data/images folder, return the paths."""
data = os.path.join(here, "data", "images")
return list_folder(data, remove_ext=remove_ext, ext=".png") | 5,292,827 |
def cli_ncbi_link_bioproject(email, password, endpoint, org_name, bioproj_accession):
"""Create a pangea group from an NCBI BioProject.
Creates a Pangea SampleGroup corresponding to the given bioproject accession.
- This SampleGroup is a Pangea Library that can contain samples
- A PangeaSample is cre... | 5,292,828 |
async def project_edit(
project_id: int,
project: CreateAndUpdateProject,
db=Depends(get_db),
current_user=Depends(get_current_active_user)
):
"""
Update existing project
"""
try:
return edit_project(db, project_id, project)
except Exception as e:
return JSONResponse(... | 5,292,829 |
def preprocess_image(image):
"""
预处理图片,包括变形到(1,width, height)形状,数据归一到0-1之间
:param image: 输入一张图片
:return: 预处理好的图片
"""
image = image.resize((width, height))
image = img_to_array(image)
image = np.expand_dims(image, axis=0) # (width, height)->(1,width, height)
image = vgg19.preprocess_... | 5,292,830 |
def is_valid_broker(obj: Any) -> bool:
"""
Helper utils to check if an object can
be used as a broker in `WebSocketManager`.
Exposed to developers who need to implement a
custom broker.
"""
return (
(hasattr(obj, 'subscribe') and inspect.iscoroutinefunction(obj.subscribe))
an... | 5,292,831 |
async def enable_entity(
hass: HomeAssistant, entry_id: str, entity_id: str
) -> er.RegistryEntry:
"""Enable a disabled entity."""
entity_registry = er.async_get(hass)
updated_entity = entity_registry.async_update_entity(entity_id, disabled_by=None)
assert not updated_entity.disabled
await hass... | 5,292,832 |
def summary(result):
"""A summary string of a result object.
Args:
result (AugmentedResult): The result object to get the summary of.
Returns:
str: The summary string.
"""
assert isinstance(result, AugmentedResult)
untested = list(
result.augmented_results(
lambda case_re... | 5,292,833 |
def print_error_test_results(all_tests):
"""
@fn print_error_test_results
@param all_tests
@return
"""
print '%d tests...' % len(all_tests)
error_tests = []
for t in all_tests:
test_name = t.keys()[0]
success = t.values()[0]['success']
info = test_name
if ... | 5,292,834 |
def compute_unique_fused_charges(
charges: List[BaseCharge], flows: Union[np.ndarray,
List[bool]]) -> BaseCharge:
"""
For a list of charges, compute all possible fused charges resulting
from fusing `charges`.
Args:
charges: List of `BaseCharge`, one for each l... | 5,292,835 |
def get_window(image, window_size, centre_coordinates):
"""
Get a window in image taking into account boundary conditions
image: a numpy array representing our image
window_size: an odd number specifying the size of the window
centre_coordinates: a list containing the x-y coordinates of ... | 5,292,836 |
def truncation_logic(df, snappt, lencolname, gordcolname, elevcolname):
"""Figure out where to stop this flowpath."""
df["distance"] = df["geometry"].distance(snappt["geometry"])
# 91 gully head
# 98 Gulley Head -10m
# 99 Gulley Head +10m
# 100 Gulley Head -20m
# 101 Gulley Head +20m
off... | 5,292,837 |
def get_base_generic_type(object_type):
"""
Utility method to return the equivalent non-customized type for a Generic type, including user-defined ones.
for example calling it on typing.List<~T>[int] will return typing.List<~T>.
If the type is not parametrized it is returned as is
:param object_ty... | 5,292,838 |
def centre_dot(dot_ls):
"""计算多个经纬度坐标的中心点"""
lng = 0
lat = 0
count = len(dot_ls)
for dot in dot_ls:
lng += float(dot[0]) * math.pi / 180
lat += float(dot[1]) * math.pi / 180
lng /= count
lat /= count
center_dot = (lng * 180 / math.pi, lat * 180 / math.pi)
return cente... | 5,292,839 |
def up(ctx): # pylint: disable=invalid-name
""" Run Docker compose up which brings up the compose stack. """
get_compose_environment()
ctx.run(DOCKER_COMPOSE_UP_CMD) | 5,292,840 |
def get_steam_app_html(app_id):
"""
Get html from Steam app's Steam store page.
:param app_id: Steam Store app id
:return: html string from Steam store page.
"""
url = get_steam_app_url(app_id)
request = requests.get(url)
return request.text | 5,292,841 |
def get_elevator_floor(actual_floor):
"""
Given an actual floor, convert it to an elevator
button number by skipping the thirteenth floor
Parameters
----------
actual_floor: int
The actual floor we're traveling to
Returns
----------
elevator_floor: int
What the eleva... | 5,292,842 |
def parse_options():
"""
set up command line parser options
"""
from optparse import OptionParser
usage = 'usage: %prog [options]'
parser = OptionParser(usage=usage)
parser.add_option('-t', '--task', dest='task', type='str',
help='tasks: u09, u08, u07, m07, m06, m... | 5,292,843 |
def select_output_dir():
"""Called when the user wishes to set the output directory to be used when the capture images button is pressed"""
global capture_outputpath
capture_outputpath = tkFileDialog.askdirectory()
print(f'About to set output dir to {capture_outputpath}') | 5,292,844 |
def test_invoking_prediction_tools(
prediction_query,
test_dir,
subprocess_returncode_1,
monkeypatch,
):
"""Test invoking prediction tools."""
def mock_getcwd(*args, **kwargs):
return test_dir
def mock_changing_dir(*args, **kwargs):
return
def mock_invoking_tools(*args... | 5,292,845 |
def _compute_attention(attention_mechanism, cell_output, attention_state,
attention_layer):
"""Computes the attention and alignments for a given attention_mechanism."""
alignments, next_attention_state = attention_mechanism(
cell_output, state=attention_state)
# Reshape from [batch_size, memory... | 5,292,846 |
def find(db, clazz, name):
""" Find something by name"""
dao = Daos.createBaseDao(db, clazz)
for item in dao.getAll():
if item.name == name:
return item
return None | 5,292,847 |
def merge_delta(m, delta):
"""
Update (in-place) the metrics entry 'm' by merging another entry 'delta'.
Counts and sums are simply added.
Histograms require more complex processing: the 'values' array needs to be
merged and the then the delta's counts added to the corresponding buckets.
"""
for k, v in... | 5,292,848 |
def search_location_reports_by_tags(tag_name_list): # works
"""returns a list of LocationReports that contain a certain tag"""
all_location_reports = get_all_location_reports()
location_report_key_set = set()
tag_key_list = []
for tn in tag_name_list:
tag = create_or_get_tag(tn)
... | 5,292,849 |
def __find_yzwing_candidates(sboard, current_cell_name, num_values, num_intersection_values):
"""
A support method to find candidate cells to be ywing or xyzwing pincers.
"""
candidates = []
current_cell = sboard.getCell(current_cell_name)
current_value_set = current_cell.getValueSet()
assoc... | 5,292,850 |
def rsck_to_kcrs(src):
"""Converts tensor from RSCK to KCRS format. Usually
used for converting convolution filter tensors.
cuDNN notation is used for dimensions where RS are
spatial dimensions (height and width), C - number
of input channels and K - number of output channels.
"""
assert len... | 5,292,851 |
def test_smooth_model():
""" Check that all keys for smooth model exist. """
smooth_keys = ['resolution', 'half_range']
for key in smooth_keys:
assert CONFIG_INI.has_option('smooth_model', key) | 5,292,852 |
def I3TestModuleFactory(*test_cases):
"""Test case factory
Create an `I3Module` that runs the given `unittest` test cases on
each Physics frame.
Example
-------
Create a simple test case::
class I3TimeHorizonCutTest(unittest.TestCase):
def testKeys(self):
#... | 5,292,853 |
def index():
"""Video streaming home page."""
return "Select a spell to cast." | 5,292,854 |
def dummy_dataframe() -> pd.DataFrame:
"""Create dummy data for testing."""
return pd.DataFrame({"col1": [1, 2], "col2": [4, 5], "col3": [5, 6]}) | 5,292,855 |
def rolling_window(a, window,axis=-1,pad=False,mode='reflect',**kargs):
"""
This function produces a rolling window shaped data with the rolled data in the last col
a : n-D array of data
window : integer is the window size
axis : integer, axis to move the window over
... | 5,292,856 |
def job_assign_role_flow(
assigner_email: str, job_id: int, assignee_email: str, assignee_role: str, db_session=None
):
"""Runs the job participant role assignment flow."""
# we resolve the assigner and assignee's contact information
contact_plugin = plugins.get(INCIDENT_PLUGIN_CONTACT_SLUG)
assigne... | 5,292,857 |
def execute_with_msg(cmd):
"""
返回命令执行的文本输出
:param cmd:
:return:
"""
core.v("execute_with_msg: " + str(cmd))
import os
r = os.popen(cmd)
text = r.read()
r.close()
return text | 5,292,858 |
def index_bam(job, bam_path):
"""
Creates a BAM index (.bai) in the same directory as the BAM
Indexing is necessary for viewing slices of the BAM
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str bam_path: Path to BAM
"""
work_dir = os.path.dirname(os.path.abspath(b... | 5,292,859 |
def volume(V, n_iter=100):
"""
Monte Carlo estimate of volume of
convex hull of V, intersected with the unit cube
"""
dim = len(V[0])
included = []
num_in = 0
for _ in range(n_iter):
x = np.random.random(dim) - 0.5
incl = in_hull(x, V)
num_in += incl
in... | 5,292,860 |
def color_set(num, black=False, cset='xkcd'):
"""Retrieve a (small) set of color-strings with hand picked values.
Arguments
---------
num : int
Number of colors to retrieve.
black : bool
Include 'black' as the first color.
cset : str, {'xkcd', 'def'}
Which set of colors ... | 5,292,861 |
def pylint(context, local=INVOKE_LOCAL):
"""Run pylint for the specified name and Python version.
Args:
context (obj): Used to run specific commands
local (bool): Define as `True` to execute locally
"""
exec_cmd = 'find . -name "*.py" | grep -v "test/unit" | xargs pylint'
run_cmd(co... | 5,292,862 |
def test_is_reverse_strand():
"""Test is_reverse_strand from CDS class"""
assert not cds_list[0].is_reverse_strand()
assert cds_list[1].is_reverse_strand()
assert not cds_list[2].is_reverse_strand()
assert cds_list[3].is_reverse_strand()
assert not cds_list[4].is_reverse_strand() | 5,292,863 |
def encode_length(mtype, length):
# type: (MainType, Length) -> int
"""
Encode length to integer value for header encoding.
The `length` value has MainType-specific semantics:
For MainTypes `META`, `SEMANTIC`, `CONTENT`, `DATA`, `INSTANCE`:
Length means number of bits for the body.
... | 5,292,864 |
def out_in_advance(play_dict, bto=None, bfrom=None):
"""runner out when advancing by next base
- play_dict: play dictionary
- bto : base to, heading to
- bfrom: base coming from, previous base
"""
bto = '1' if not bto and not bfrom else bto
if bfrom:
play_dict[bfrom] = 0
play... | 5,292,865 |
def calc_nkt(fldr, slices, dump_step, species_np, k_list, verbose):
"""
Calculate density fluctuations :math:`n(k,t)` of all species.
.. math::
n_{A} ( k, t ) = \sum_i^{N_A} \exp [ -i \mathbf k \cdot \mathbf r_{i}(t) ]
where :math:`N_A` is the number of particles of species :math:`A`.
Par... | 5,292,866 |
def _get_reader(source, batch_size):
"""Returns 'CsvReader' for the given source
Parameters
----------
source: str or bytes
Name of the SageMaker Channel, File, or directory from which the data is being read or
the Python buffer object from which the data is being read.
... | 5,292,867 |
def Spline(points, n_points=None):
"""Create a spline from points.
Parameters
----------
points : np.ndarray
Array of points to build a spline out of. Array must be 3D
and directionally ordered.
n_points : int, optional
Number of points to interpolate along the points arra... | 5,292,868 |
def clear_file(file_handle):
"""Empties the contents of the given file."""
file_handle.seek(0)
file_handle.truncate() | 5,292,869 |
def get_version():
"""
Get PDC version info
"""
return VERSION | 5,292,870 |
def _get_mock_tokenizer():
"""Creates a mock tokenizer."""
class MockSpieceModel:
"""Mock Spiece model for testing."""
def __init__(self):
self._special_piece_to_id = {
"<unk>": 0,
}
for piece in set(list('!"#$%&\"()*+,-./:;?@[\\]^_`{|}~')):
self._special_piece_to_id[pi... | 5,292,871 |
def make_processing_action(processing_step: BaseProcessingStep):
"""
Generate the admin action function for processing steps
"""
def perform_processing_step(modeladmin, request, queryset):
last_error = None
last_content = None
error_counter = 0
success_counter = 0
... | 5,292,872 |
def grid_search(model,
model_params,
make_feature_pipeline,
make_target_pipeline,
pipeline_params,
train_data):
"""
Grid search combined with cross validation
args
model (sklearn model)
model_params (list) contains dictionaries of parameters
make_feature_pipeline (function)
make... | 5,292,873 |
def processes(method):
"""
Returns Dict of all task id => process
"""
return background_processes.get(method, dict()) | 5,292,874 |
def plot_penalty_distribution_example(penalty):
"""
Show the penalty function for genuine and impostor users
"""
genuine_idx = penalty['reference_user'] == penalty['query_user']
genuine = penalty[genuine_idx]
impostor = penalty[genuine_idx == False]
thresh = genuine['penalty'].max()
impo... | 5,292,875 |
def permissions(store: BaseAccessStore, user_id: str) -> list:
"""
get all the direct and indirect user-permission relationships for this user
first, get the relationships in which a group is granted to this user
follow the group inheritance chain to get all the associated group-group relationships... | 5,292,876 |
def get_local_grb_rate(rate_name=None, with_range=False):
"""Returns local grb rate
:param rate_name: Name of chosen evolution
:param with_range: Boolean to return +/- one sigma range functions alongside central rate
:return: Normalised evolution, equal to 1 at z=0
"""
if rate_name is None:
... | 5,292,877 |
def text_to_csv(text_file, out_file):
"""
Converts text file produced by successful completion of E-Prime experiment
to csv. Output from text_to_csv can be used to determine information
necessary for text_to_rcsv (e.g. columns to merge, columns to rename,
etc.).
Parameters
----------
... | 5,292,878 |
def create_task(conn, task):
"""
Create a new task
:param conn:
:param task:
:return:
"""
sql = ''' INSERT INTO News(V2.1DATE, V2SOURCECOLLECTIONIDENTIFIER, V2SOURCECOMMONNAME, V2DOCUMENTIDENTIFIER, V1LOCATIONS, V1ORGANIZATIONS, V1.5TONE, V2GCAM, V2.1ALLNAMES, TITLE)
VALUES(?,... | 5,292,879 |
def wait_for_job(task_id: str, status_callback: Callable[[], Optional[S]]) -> S:
"""
Wait for a job to complete (with a CLI spinner) and return its final result.
:param task_id: ID of the task (used for display)
:param status_callback: Callback that returns a `JobStatus`
:return: Final `JobStatus`
... | 5,292,880 |
def delete_global_account_limit(account, rse_expression, issuer, vo='def', session=None):
"""
Delete a global account limit..
:param account: The account name.
:param rse_expression: The rse expression.
:param issuer: The issuer account_core.
:param vo: The VO to act ... | 5,292,881 |
def generateEmailFlags(emailFlagTuples):
"""
Takes emailFlagTuples and generates the part of the
script case statement which accepts email flags.
"""
emailFlagString = ""
for emailFlagTuple in emailFlagTuples:
#add a new line and indent
emailFlagString += "\n "
#add flag character
emai... | 5,292,882 |
def tail(n):
"""
Returns the last n rows of a DplyFrame
:param n: number of rows to select
:return: a function that returns a new DplyFrame
"""
return lambda d1: DplyFrame(d1.pandas_df.tail(n)) | 5,292,883 |
def export_jira_data(jira_base_url, jira_credentials_file, jira_filter, xml_filename):
"""Export XML assessment data from Jira to a file.
Parameters
----------
jira_base_url: str
The base URL of the Jira server that houses the assessment data.
jira_credentials_file : str
The text f... | 5,292,884 |
def producer(queue, event):
"""Pretend we're getting a number from the network."""
while not event.is_set():
message = random.randint(1, 101)
logging.info("Producer got message: %s", message)
queue.put(message)
logging.info("Producer received event. Exiting") | 5,292,885 |
def load():
"""
loads all blocks that should be loaded, only the ones for blocks may be loaded somewhere else
"""
from . import (BlockGrassBlock, BlockDirt, BlockCraftingTable) | 5,292,886 |
def _struct_alignment(alignments):
"""
Returns the minimum alignment for a structure given alignments for its fields.
According to the C standard, it the lowest common multiple of the alignments
of all of the members of the struct rounded up to the nearest power of two.
"""
return bounding_power... | 5,292,887 |
def test_init_with_illegal_arg():
"""
Ensure attempt to initialise with a nonsensical data structure is rejected.
"""
with pytest.raises(TypeError):
MetaDict({'a', 'b', 'c', 'd'}) | 5,292,888 |
async def get_database():
"""Provides an opened connection with the database, available for FastAPI's
dependency injection."""
async with SessionLocal() as session:
async with session.begin():
yield session | 5,292,889 |
def apply_operations(context_arrays, operations):
"""
:param context_arrays: numpy arrays to be transformed into a format such that can be fed into a TensorFlow op graph
:return: tensor-ready arrays
"""
preprocessed_context_arrays = []
for context_array in context_arrays:
preprocessed_f... | 5,292,890 |
def test_hapd_ctrl_sta(dev, apdev):
"""hostapd and STA ctrl_iface commands"""
ssid = "hapd-ctrl-sta"
passphrase = "12345678"
params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
hapd = hostapd.add_ap(apdev[0], params)
dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
addr = de... | 5,292,891 |
def set_tam_color_defaults():
"""
info: will set console colors to tam defaults
:return: None
"""
IO.set_tam_color_defaults() | 5,292,892 |
def _get_audio_parameters(param_dict):
"""
Get audio parameters from a dictionary of parameters. An audio parameter can
have a long name or a short name. If the long name is present, the short
name will be ignored. If neither is present then `AudioParameterError` is
raised.
Expected parameters ... | 5,292,893 |
def main():
"""
Parameter configuration
"""
# Is the total of characters used to predict the next one.
max_length = 10
# Is the leap of characters in the corpus taked in everytime.
# "Move -step- characters from the first take to the second, and so on"
step = 3
batch_size = 128
e... | 5,292,894 |
def plot_qqplot(
other_args: List[str],
ticker: str,
model_name: str,
residuals: List[float],
):
"""Qqplot time series against a standard normal curve
Parameters
----------
other_args : str
Command line arguments to be processed with argparse
ticker : str
Ticker of t... | 5,292,895 |
def _table_xml(x, y, w, h, bClosed=True, sXmlCells=None):
"""
XML Table element as a string
"""
if bClosed:
# close the list of coordinates
sPoints = "%d,%d %d,%d %d,%d %d,%d %d,%d" % (x, y, x + w, y, x + w, y + h, x, y + h, x, y)
else:
sPoints = "%d,%d %d,%d %d,%d %d,%d" % (... | 5,292,896 |
def check_for_station(ID, era):
"""
Check if there is a station specified by ID for given era.
INPUT
-----
ID : string with 5 digits of specifying station ID
era : string specifying the path to return, either 'recent', 'historical'
OUPUT
-----
no output
"""
... | 5,292,897 |
def server_add_floating_ip(request, server, address):
"""
Associates floating IP to server's fixed IP.
"""
server = novaclient(request).servers.get(server)
fip = novaclient(request).floating_ips.get(address)
return novaclient(request).servers.add_floating_ip(server, fip) | 5,292,898 |
def _constraintsearch(df, significance_level=0.05, verbose=3):
"""Contrain search.
test_conditional_independence() returns a tripel (chi2, p_value, sufficient_data),
consisting in the computed chi2 test statistic, the p_value of the test, and a heuristig
flag that indicates if the sample size was suffi... | 5,292,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.