content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def command_line_parsing():
""" Parse the command line arguments, set global TESTING and return the
current position as a tuple (either default or one given on command line """
global TESTING
parser = argparse.ArgumentParser(description='Food Truck Finder.')
parser.add_argument('latlong', metavar='... | 5,100 |
def read_samplesheet(config):
"""
read samplesheet
"""
sample_sheet = pd.read_csv(config["info_dict"]["flowcell_path"]+"/SampleSheet.csv",
sep = ",", skiprows=[0])
# sample_sheet = sample_sheet.fillna("no_bc")
sample_sheet['I7_Index_ID'] = sample_sheet['I7_Inde... | 5,101 |
def convert_to_float_if_possible(x, elsevalue=MISSING):
"""
Return float version of value x, else elsevalue (MISSING or other specified value
if conversion fails
"""
if isnonnumeric(x):
return elsevalue
else:
return float(x) | 5,102 |
def resolve(
names: Union[list, pd.Series, str],
data_source_ids: list = None,
resolve_once: bool = False,
best_match_only: bool = False,
with_context: bool = False,
with_vernaculars: bool = False,
with_canonical_ranks: bool = False
) -> pd.DataFrame:
"""
Receives a list of names and... | 5,103 |
def ResultObject(): # real signature unknown; restored from __doc__
"""
ResultObject()
ResultObject(success: bool)
ResultObject(success: bool,message: str)
"""
pass | 5,104 |
def polarisation_frame_from_wcs(wcs, shape) -> PolarisationFrame:
"""Convert wcs to polarisation_frame
See FITS definition in Table 29 of https://fits.gsfc.nasa.gov/standard40/fits_standard40draft1.pdf
or subsequent revision
1 I Standard Stokes unpolarized
2 Q Standard Stokes linear
... | 5,105 |
def _update_traffic_class(class_name, class_type, **kwargs):
"""
Perform a PUT call to version-up a traffic class. This is required whenever entries of a traffic class are changed
in any way.
:param class_name: Alphanumeric name of the traffic class
:param class_type: Class type should be one of "i... | 5,106 |
def eff_w_error(n_before, n_after):
"""
n_before = entries before
n_after = entries after
"""
eff = n_after/n_before
eff_error = np.sqrt(eff*(1-eff)/n_before)
return (eff, eff_error) | 5,107 |
def hurst(x):
"""Estimate Hurst exponent on a timeseries.
The estimation is based on the second order discrete derivative.
Parameters
----------
x : 1D numpy array
The timeseries to estimate the Hurst exponent for.
Returns
-------
h : float
The estimation of the Hurst ... | 5,108 |
def get_models(download_models=None):
"""
This runs through all models and downloads them from
remote servers. To add a new model, simply append
the model to the 'models' dict with a server location,
that contains a zip file that can be extracted and a
local location to download and unzip this f... | 5,109 |
def explode_on_matched_columns(df, safe_columns, other_columns):
"""Given the name of multiple columns where each entry is a string encoding
a list, and where for each row the lists in all columns are the same length,
return a dataframe where the each row is transformed into len(list)
rows, each of whic... | 5,110 |
def plot_time_series_graph(val_matrix,
var_names=None,
fig_ax=None,
figsize=None,
sig_thres=None,
link_matrix=None,
link_colorbar_label='MCI',
save_name=None,
link_width=None,
arrow_linewidth=20.,
vmin_edges=-1,
vmax_edges=1.,
... | 5,111 |
def get_configuration_docname(doctype=None, txt=None, searchfield=None, start=None, page_len=None, filters=None):
"""get relevant fields of the configuration doctype"""
return frappe.db.sql("""select soi.configuration_docname, so.name, so.customer from `tabSales Order Item` soi
inner join `tabSales Order` so... | 5,112 |
def run_cnn_dist(
X_bytes: bytes,
) -> bytes:
"""Run distributed CNN on bytes_in and return the calculated result."""
X = pickle.loads(X_bytes)
# TODO: <He> Process the X data with the fancy neural network.
result_data = X
# MARK: Metadata could be added here to mark the processing status of t... | 5,113 |
def bootstrap(command, conf, vars):
"""Place any commands to setup weeehire here"""
# <websetup.bootstrap.before.auth
from sqlalchemy.exc import IntegrityError
try:
a = model.User()
a.user_name = env['ADMIN_USERNAME']
a.display_name = env['ADMIN_USERNAME']
a.email_addres... | 5,114 |
def skymapper_search(searchrad,waveband,targetra,targetdec):
""" Search for stars within search radius of target in Skymapper
catalogue
"""
# set up arrays and url
star_ra = []
star_dec = []
star_mag = []
star_magerr = []
sky_ra = []
sky_dec = []
sky_u_petro = []
sky_u_petro_err = []
sky_u_psf = []
sky... | 5,115 |
def Decimal_to_Hexadecimal(x : str) -> str:
"""
It Converts the Given Decimal Number into Hexadecimal Number System of Base `16` and takes input in `str` form
Args:
x `(str)` : It is the Positional Argument by order which stores the Decimal Input from User.
Returns (str) : The Outp... | 5,116 |
def hardcorenas_d(pretrained=False, **kwargs):
""" hardcorenas_D """
arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre_se0.25', 'ir_r1_k5_s1_e3_c24_nre_se0.25'],
['ir_r1_k5_s2_e3_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', 'ir_r1_k3_s1_e3_c40_nre_se0.25'],
['... | 5,117 |
def refine(weights, trees, X, Y, epochs, lr, batch_size, optimizer, verbose):
"""Performs SGD using the MSE loss over the leaf nodes of the given trees on the given data. The weights of each tree are respected during optimization but not optimized.
Args:
weights (np.array): The weights of the trees.
... | 5,118 |
def test_ebi_goa_dnld(run_full=False):
"""Test downloading files from GOA source http://www.ebi.ac.uk/GOA."""
obj = DnldGoa()
dnld_files = dnld_goa(obj, run_full, ['gpa']) # 'gpi', 'gaf'
for fout in dnld_files:
assert os.path.isfile(fout), "FILE({F}) NOT PROPERLY DOWNLOADED FROM {FTP}".format(
... | 5,119 |
def test_aggregate_median_allvar():
"""
Testing aggregate pycytominer function
"""
aggregate_result = aggregate(
population_df=data_df, strata=["g"], features="infer", operation="median"
)
expected_result = pd.concat(
[
pd.DataFrame({"g": "a", "Cells_x": [3], "Nuclei... | 5,120 |
def fetch_db_object(cls: ClassVar, body: Any):
"""Fetch a database object via SQLAlchemy.
:param cls: the class of object to fetch.
:param body: the body of the object. If the body is None then None is returned (for the case where no object
exists), if the body is already of type cls then the body is r... | 5,121 |
def should_skip_cred_test():
"""
Returns `True` if a test requiring credentials should be skipped.
Otherwise returns `False`
"""
if username is None or password is None:
return True
return False | 5,122 |
def update_registry_location():
"""Handle changes to the container image registry.
Monitor the image registry location. If it changes, manage flags to ensure
our image-related handlers will be invoked with an accurate registry.
"""
registry_location = get_registry_location()
if registry_locati... | 5,123 |
def write_project_name_file(
annofab_service: annofabapi.Resource, project_id: str, command_line_args: CommnadLineArgs, output_project_dir: Path
):
"""
ファイル名がプロジェクト名のjsonファイルを生成する。
"""
project_info = annofab_service.api.get_project(project_id)[0]
project_title = project_info["title"]
logger.... | 5,124 |
def print_genome_matrix(hits, fastas, id2desc, file_name):
"""
optimize later? slow ...
should combine with calculate_threshold module
"""
out = open(file_name, 'w')
fastas = sorted(fastas)
print('## percent identity between genomes', file=out)
print('# - \t %s' % ('\t'.join(fastas)), fi... | 5,125 |
def test_unicode_ipdir():
"""Check that IPython starts with non-ascii characters in the IP dir."""
ipdir = tempfile.mkdtemp(suffix=u"€")
# Create the config file, so it tries to load it.
with open(os.path.join(ipdir, 'ipython_config.py'), "w") as f:
pass
old_ipdir1 = os.environ.pop... | 5,126 |
def list_input_images(img_dir_or_csv: str,
bucket_name: str = None,
glob_patterns: List = None):
"""
Create list of images from given directory or csv file.
:param img_dir_or_csv: (str) directory containing input images or csv with list of images
:param bucke... | 5,127 |
def get_insta_links(L: Instaloader, url: str) -> tuple:
"""
Return list of shortcodes
:param url: URL
:return: success status and list of shortcodes
"""
try:
shortcode = get_insta_shortcode(url)
post = Post.from_shortcode(L.context, shortcode)
return True, post
exc... | 5,128 |
def read_snli(data_dir, is_train):
"""将SNLI数据集解析为前提、假设和标签"""
def extract_text(s):
# 删除我们不会使用的信息
s = re.sub('\\(', '', s)
s = re.sub('\\)', '', s)
# 用一个空格替换两个或多个连续的空格
s = re.sub('\\s{2,}', ' ', s)
return s.strip()
label_set = {'entailment': 0, 'contradiction': ... | 5,129 |
async def http_request_callback(_request: HttpRequest) -> HttpResponse:
"""A response handler which returns some text"""
with open(__file__, 'rb') as file_pointer:
buf = file_pointer.read()
headers = [
(b'content-type', b'text/plain'),
(b'content-length', str(len(buf)).encode('ascii... | 5,130 |
def ensure_directory_exists(directory, domain=None, permissions=0o777):
"""Create a directory and give access rights to all
Args:
directory (str): Root directory
domain (str): Domain. Basically a subdirectory to prevent things like
overlapping signal filenames.
rig... | 5,131 |
def on_state_changed_farm(parent, state):
"""Callback event handler for changed "AWS" checkbox on the specified tab.
Args:
parent (App(QDialog)): Object corresponding to the parent UI element.
state (str): Identifier of the callback state.
"""
parent.is_farm = state > 0
if not paren... | 5,132 |
def item_coverage(
possible_users_items: Tuple[List[Union[int, str]], List[Union[int, str]]],
recommendations: List[Tuple[Union[int, str], Union[int, str]]],
) -> float:
"""
Calculates the coverage value for items in possible_users_items[1] given the collection of recommendations.
Recommendations ov... | 5,133 |
def test_create_alias(mock_es_client):
"""Test create_alias()."""
index_name = 'test-index'
alias_name = 'test-alias'
client = mock_es_client.return_value
elasticsearch.associate_index_with_alias(alias_name, index_name)
client.indices.put_alias.assert_called_with(index_name, alias_name) | 5,134 |
def display_budgets(budgets_tab, max_resources, reduction_factor):
"""Display hyperband budget as a table in debug log"""
num_brackets = len(budgets_tab[0])
table_str = "Display Budgets:\n"
col_format_str = "{:<4}" + " {:<12}" * num_brackets + "\n"
col_title_list = ["i "] + ["n_i r_i"] * num_brack... | 5,135 |
def test_scope():
"""Test that the use of scope dictionary works as intended"""
cip = TwoWheelerInputParameters()
cip.static()
scope = {"powertrain": ["ICEV-d"], "size": ["Lower medium"]}
_, array = fill_xarray_from_input_parameters(cip, scope=scope)
assert "BEV" not in array.coords["powertrain... | 5,136 |
def calc_area(img_it, contours, conv_sq, list_save):
"""
Summary
Parameters
----------
yearstr : TYPE
DESCRIPTION.
Returns
-------
TYPE
DESCRIPTION.
"""
# Calculate areas
sum_file = 0
for c in contours:
M = cv2.moments(c)
area = M['m00']... | 5,137 |
def truth_seed_box(true_params, init_range, az_ind=4, zen_ind=5):
"""generate initial box limits from the true params
Parameters
----------
true_params : np.ndarray
init_range : np.ndarray
Returns
-------
np.ndarray
shape is (n_params, 2); returned energy limits are in units of... | 5,138 |
def unlike_post(entry_entity, unliker):
"""Deletes a PostLike entity"""
likes_query = PostLike.all()
likes_query.filter('liker =', unliker)
likes_query.filter('blogEntry =', entry_entity)
like_entity = likes_query.get()
like_entity.delete() | 5,139 |
def Report(DriverType=None):
"""A factory for ReportWrapper classes."""
from xia2.Driver.DriverFactory import DriverFactory
DriverInstance = DriverFactory.Driver(DriverType)
class ReportWrapper(DriverInstance.__class__):
def __init__(self):
DriverInstance.__class__.__init__(self)
... | 5,140 |
def summary(task):
"""Given an ImportTask, produce a short string identifying the
object.
"""
if task.is_album:
return u'{0} - {1}'.format(task.cur_artist, task.cur_album)
else:
return u'{0} - {1}'.format(task.item.artist, task.item.title) | 5,141 |
def ds_tc_resnet_model_params(use_tf_fft=False):
"""Generate parameters for ds_tc_resnet model."""
# model parameters
model_name = 'ds_tc_resnet'
params = model_params.HOTWORD_MODEL_PARAMS[model_name]
params.causal_data_frame_padding = 1 # causal padding on DataFrame
params.clip_duration_ms = 160
params... | 5,142 |
def expected_calibration_error_evaluator(test_data: pd.DataFrame,
prediction_column: str = "prediction",
target_column: str = "target",
eval_name: str = None,
... | 5,143 |
def test_unify_lifted_to_ground():
"""Tests for unify() when lifted atoms are the first argument and ground
atoms are the second argument."""
cup_type = Type("cup_type", ["feat1"])
cup0 = cup_type("cup0")
cup1 = cup_type("cup1")
cup2 = cup_type("cup2")
var0 = cup_type("?var0")
var1 = cup... | 5,144 |
def format_bytes(size):
"""
Takes a byte size (int) and returns a formatted, human-interpretable string
"""
# 2**10 = 1024
power = 2 ** 10
n = 0
power_labels = {0: " bytes", 1: "KB", 2: "MB", 3: "GB", 4: "TB"}
while size >= power:
size /= power
n += 1
return str(round... | 5,145 |
def plot_features(df):
"""
:param df:
:return:
"""
dfp = df.toPandas()
column_list = ["avgSessionsMonth", "avgSessionMonthDuration", "avgSessionitemsMonth", "avgSessionsDay",
"avgSessionDayDuration", "avgSessionitemsDay", "activeDuration",
"AboutPageMonth"... | 5,146 |
def load_input_data(filenames, Ag_class):
"""
Load the files specified in filenames.
Parameters
---
filenames: a list of names that specify the files to
be loaded.
Ag_class: classification of sequences from MiXCR txt file
(i.e., antigen binder = 1, non-binder = 0)
""... | 5,147 |
def get_maximum_value(
inclusive: Optional[Edge] = None,
exclusive: Optional[Edge] = None,
ignore_unlimited: bool = False,
) -> Result[Boundary, TestplatesError]:
"""
Gets maximum boundary.
:param inclusive: inclusive boundary value or None
:param exclusive: exclusive boundary value or Non... | 5,148 |
def draw_maglites(bmap,**kwargs):
"""
Plot the MagLiteS Phase-I footprint.
Parameters:
-----------
bmap : The basemap object
kwargs : Various plotting arguments
Returns:
--------
None
"""
# Plot the wide-field survey footprint
logging.debug("Plotting MagLiteS footpri... | 5,149 |
def build_graph(order: int, edges: List[List[int]]) -> List[List[int]]:
"""Builds an adjacency list from the edges of an undirected graph."""
adj = [[] for _ in range(order)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return adj | 5,150 |
def construct_scheduler(
optimizer,
cfg: OmegaConf,
):
"""
Creates a learning rate scheduler for a given model
:param optimizer: the optimizer to be used
:return: scheduler
"""
# Unpack values from cfg.train.scheduler_params
scheduler_type = cfg.train.scheduler
decay_factor = cf... | 5,151 |
def dump_eetf_info(eetf):
"""
18% Gray, 100% White などの情報をダンプする
"""
x_18_gray = tf.oetf_from_luminance(18.0, tf.ST2084)
x_100_white = tf.oetf_from_luminance(100.0, tf.ST2084)
x_ref_white = tf.oetf_from_luminance(250.0, tf.ST2084)
x_18_idx = int(np.round(x_18_gray * 1023))
x_100_idx = int... | 5,152 |
def GenerateSerialGraph(num_samples, block_size):
""" Generates a (consistent) serial graph. """
N = num_samples
num_blocks = N // block_size
if N % block_size != 0:
err = "num_samples(%d) must be a multiple of block_size (%d)" % (num_samples, block_size)
raise Exception(err)
if nu... | 5,153 |
def load_ref_system():
""" Returns alpha-d-rhamnopyranose as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C -0.8728 1.4263 -0.3270
O -1.5909 0.3677 0.2833
C -1.1433 -0.9... | 5,154 |
def load_aggregates(affiliations, a_agg, d_agg, table, dry_run=False):
"""
Description: Will take a dict of affiliation statuses, total affiliation, and individual and load them
into the VP database.
Args:
affiliations (dict): Keyed on carId. Expects a similar format to
'<carId>... | 5,155 |
def find_python_root_dir(possibles):
"""Find a python root in a list of dirs
If all dirs have the same name, and one of them has setup.py
then it is probably common Python project tree, like
/path/to/projects/cd
/path/to/projects/cd/cd
Or, if all dirs are the same,
except that o... | 5,156 |
def _unzip_and_handle_result(zip_content, run, output_handler, benchmark):
"""
Call handle_result with appropriate parameters to fit into the BenchExec expectations.
"""
result_values = collections.OrderedDict()
def _open_output_log(output_path):
log_file = open(run.log_file, 'wb')
... | 5,157 |
def findEndpoint():
"""
scroll to bottom to get the last number
"""
print("Fetching school count")
clickToOpen()
# get scroller
scrollbar = driver.find_elements_by_class_name("scrollbar-inner")[1]
driver.execute_script("arguments[0].scrollBy(0,2);", scrollbar)
inner = driver.find_... | 5,158 |
def _shake_shake_block(x, output_filters, stride, is_training):
"""Builds a full shake-shake sub layer."""
batch_size = tf.shape(x)[0]
# Generate random numbers for scaling the branches
rand_forward = [
tf.random_uniform(
[batch_size, 1, 1, 1], minval=0, maxval=1, dtype=tf.float32)
for _ ... | 5,159 |
def find_wp_dir(con, clean_wp_path):
""" Finds the WP file directory based on the directory list of the WP version.
Change the FTPutil connection directory if a matching directory list exists.
Otherwise, gracefully exits the program and closes the FTP connection.
Keyword Arguments:
con ... | 5,160 |
def get_all_paged_events(decision, conn, domain, task_list, identity, maximum_page_size):
"""
Given a poll_for_decision_task response, check if there is a nextPageToken
and if so, recursively poll for all workflow events, and assemble a final
decision response to return
"""
# First check if the... | 5,161 |
def get_pools():
""" gets json of pools. schema follows
#{
# "kind": "tm:ltm:pool:poolcollectionstate",
# "selfLink": "https://localhost/mgmt/tm/ltm/pool?ver=11.5.3",
# "items": [
# {
# "kind": "tm:ltm:pool:poolstate",
# "name": "mypoolname",
# "partit... | 5,162 |
def set_runner_properties(timestep, infguard=False, profile_nodenet=False, profile_world=False, log_levels={}, log_file=None):
"""Sets the speed of the nodenet calculation in ms.
Argument:
timestep: sets the calculation speed.
"""
if log_file:
if not tools.is_file_writeable(log_file):
... | 5,163 |
def merge_aeroMap(tixi, aeromap_uid_1,aeromap_uid_2,aeromap_uid_merge,
keep_originals = True):
""" Merge two existing aeroPerformanceMap into a new one
Function 'merge_aeroMap' merge two aeroMap into one, an option
allow to keep or not the orignal ones.
Args:
tixi (... | 5,164 |
def chunk_sum(vec, chunksize):
"""Computes the sums of chunks of points in a vector.
"""
Nchunks = len(vec)//chunksize
end = Nchunks*chunksize
arr = np.reshape(vec[:end], [Nchunks, chunksize])
sums = np.sum(arr, 1)
return sums | 5,165 |
def test_catalog_generate_failures(tmp_trestle_dir: pathlib.Path, monkeypatch: MonkeyPatch) -> None:
"""Test failures of author catalog."""
# disallowed output name
test_args = 'trestle author catalog-generate -n foo -o profiles'.split()
monkeypatch.setattr(sys, 'argv', test_args)
assert Trestle().r... | 5,166 |
def install_custom_app(app, app_url, app_trigger = "False"):
"""this function is used to install custom apps"""
if app.endswith(".zip"):
app = app.split(".")[0]
if app.endswith(".git"):
app = app.split(".")[0]
if not os.path.exists(wapps_dir_path):
os.mkdir(wapps_dir)
app_url... | 5,167 |
def get_feature_definitions(df, feature_group):
"""
Get datatypes from pandas DataFrame and map them
to Feature Store datatypes.
:param df: pandas.DataFrame
:param feature_group: FeatureGroup
:return: list
"""
# Dtype int_, int8, int16, int32, int64, uint8, uint16, uint32
# and uin... | 5,168 |
def draw_2d_wp_basis(shape, keys, fmt='k', plot_kwargs={}, ax=None,
label_levels=0):
"""Plot a 2D representation of a WaveletPacket2D basis."""
coords, centers = _2d_wp_basis_coords(shape, keys)
if ax is None:
fig, ax = plt.subplots(1, 1)
else:
fig = ax.get_figure()
... | 5,169 |
def contributor_translations(settings, user_a, project_a):
"""
Setup a sample contributor with random set of translations.
"""
translations = OrderedDict()
for i in range(6):
date = make_aware(datetime(2016, 12, 1) - timedelta(days=i))
translations_count = 2
translations.setd... | 5,170 |
def build_normalizer(signal, sample_weight=None):
"""Prepares normalization function for some set of values
transforms it to uniform distribution from [0, 1]. Example of usage:
>>>normalizer = build_normalizer(signal)
>>>pylab.hist(normalizer(background))
>>># this one should be uniform in [0,1]
... | 5,171 |
def main(target_dir=".", depth=2):
"""Catch main function."""
print(target_dir)
if target_dir == ".":
td_name = os.getcwd().split(
"/")[-1]
elif target_dir == "..":
td_name = os.getcwd().split(
"/")[-2]
else:
td_name = target_dir
directory = 'gene... | 5,172 |
def plot_tseries_together(data, onset=None, years=None, suptitle='',
figsize=(14,10), legendsize=10,
legendloc='lower right', nrow=3, ncol=4,
yearnm='year', daynm='day', standardize=True,
label_attr=None, data_style=... | 5,173 |
def get_angler_tag_recoveries(project_slug, tagstat="A"):
"""This is a helper function used by tags_applied_project(). It uses
raw sql to retrieve all of the non-MNR recoveries of tags applied
in a particular project. Only recap's with both a lat and lon and
of the same species as the original tagging ... | 5,174 |
def sort(pipe: Pipe):
"""Sort values by columns."""
pipe.matrix.sort_values(by=pipe.matrix.columns.values.tolist(), axis=0, inplace=True) | 5,175 |
def get_phased_trajectory(init_state: np.ndarray,
update_fn: Callable) -> Tuple[np.ndarray, HashableNdArray]:
"""
evolve an initial state until it reaches a limit cycle
Parameters
----------
init_state
update_fn
Returns
-------
trajectory, phase-point pair... | 5,176 |
def _execute_gramtools_cpp_build(build_report, action, build_paths, args):
"""Executes `gram build` backend."""
log.info("Running backend build")
command = [
common.gramtools_exec_fpath,
"build",
"--gram_dir",
str(args.gram_dir),
"--ref",
str(args.reference),... | 5,177 |
async def test_get_user_by_id(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
) -> None:
"""Should return OK, and a body containing one user."""
mocker.patch(
"user_service.adapters.users_adapter.UsersAdapter.get_user_by_id",
side_effect=mock_user_object,
)
moc... | 5,178 |
async def test_reauth_unknown_error(hass: HomeAssistant) -> None:
"""Test we show user form on unknown error."""
with patch(
"homeassistant.components.mazda.config_flow.MazdaAPI.validate_credentials",
side_effect=Exception,
):
result = await hass.config_entries.flow.async_init(
... | 5,179 |
def list_attribute(db_ip, db_user, db_pass, db_name, log_object):
""" List attributes in database """
from my_library import test_socket, ClassDB
if test_socket(db_ip, 3306, log_object) == 0:
o_db = ClassDB('mysql', (db_ip, '3306', db_user, db_pass, db_name), log_object)
result = o_db.selec... | 5,180 |
def test_country_unicode_insert(session):
"""Country 002: Insert a single record with Unicode characters into Countries table and verify data."""
ivory_coast = mco.Countries(name=u"Côte d'Ivoire", confederation=enums.ConfederationType.africa)
session.add(ivory_coast)
country = session.query(mco.Countri... | 5,181 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the OpenWeatherMap weather platform."""
name = config.get(CONF_NAME)
phone_id = config.get(PHONE_ID)
device_ids = []
for device_id in config[CONF_DEVICE_ID]:
device_ids.append(device_id... | 5,182 |
def exponential_backoff(func):
"""
Retries a Boto3 call up to 5 times if request rate limits are hit.
The time waited between retries increases exponentially. If rate limits are
hit 5 times, exponential_backoff raises a
:py:class:sceptre.exceptions.RetryLimitExceededException().
:param func: a... | 5,183 |
def create_result_as_html(template_data):
"""
Generates html file containing results of web pages comparison
:param template_data: Contains data required to create html file.
:type template_data: TemplateData.
"""
template = JINJA_ENVIRONMENT.get_template(template_data.template_path... | 5,184 |
def post_config_adobe_granite_saml_authentication_handler(key_store_password=None, key_store_password_type_hint=None, service_ranking=None, service_ranking_type_hint=None, idp_http_redirect=None, idp_http_redirect_type_hint=None, create_user=None, create_user_type_hint=None, default_redirect_url=None, default_redirect_... | 5,185 |
def _Disable( module_file ):
"""Disables the loading of a module for the current session."""
_module_for_module_file[ module_file ] = None | 5,186 |
def describe_shape(tree: KDTree, mass: float, name: Optional[str] = None, pole: Optional[str] = None):
"""
Describe the statistics of a tessellated shape to std out.
:param tree: The KDTree containing the tesselated shapes
:param mass: The mass of the object, typically computed from GM
:param name:... | 5,187 |
def test_ll2xy_edge():
"""Testing edge cases, literally"""
x = [0, 0, 0, 100, 181, 181, 181]
y = [0, 100, 191, 191, 191, 100, 0]
lon, lat = xy2ll(A, x, y)
x1, y1 = ll2xy(A, lon, lat)
# print(x1)
# print(y1)
assert (~np.any(np.isnan(x1)))
assert (~np.any(np.isnan(y1))) | 5,188 |
def test_dataproc_operator_execute_failure_async(mock_submit_job, event):
"""Tests that an AirflowException is raised in case of error event"""
mock_submit_job.return_value.reference.job_id = TEST_JOB_ID
task = DataprocSubmitJobOperatorAsync(
task_id="task-id", job=SPARK_JOB, region=TEST_REGION, pro... | 5,189 |
def get_req_env(var_name: str) -> str:
"""
Try to get environment variable and exits if not available
"""
try:
return os.environ[var_name]
except KeyError:
print(f"Missing required environment variable '{var_name}'.")
exit(1) | 5,190 |
def print_value_function(value_func, grid_width):
"""Print the value function in human-readable format.
Parameters
----------
value_func: np.ndarray
Array of state to state value mappings
grid_width: int
width of the map: eg, 4 (4x4 environment), 8 (8x8 environment)
"""
delimit... | 5,191 |
def test_order(problem, method):
"""Test order of time discretization.
"""
# TODO add test for spatial order
# Methods together with the expected order of convergence.
helpers.assert_time_order(problem, method)
return | 5,192 |
def _pcheck(block):
""" Helper for multiprocesses: check a block of logs
Args:
block List[List[str], int]: lines, block_id
Returns:
[type]: [description]
"""
results = []
lines, block_id = block
for li, line in enumerate(lines):
json_line = json.loads(line)
... | 5,193 |
def fetch_exon_locations(database):
""" Queries the database to create a dictionary mapping exon IDs to
the chromosome, start, end, and strand of the exon """
conn = sqlite3.connect(database)
cursor = conn.cursor()
query = """
SELECT
e.edge_ID,
loc1.chromosome,
MIN(loc1.position,loc2.position),
... | 5,194 |
def question_1f_sanity_check(model, src_sents, tgt_sents, vocab):
""" Sanity check for question 1f.
Compares student output to that of model with dummy data.
"""
print ("-"*80)
print("Running Sanity Check for Question 1f: Step")
print ("-"*80)
reinitialize_layers(model)
# Inputs
... | 5,195 |
def add(request):
"""Displays/processes a form to create a collection."""
data = {}
if request.method == 'POST':
form = forms.CollectionForm(
request.POST, request.FILES,
initial=initial_data_from_request(request))
aform = forms.AddonsForm(request.POST)
if for... | 5,196 |
def get_camera_pose_cpp():
"""
Returns camera pose
"""
rospy.wait_for_service('/asr_robot_model_services/GetCameraPose', timeout=5)
pose = rospy.ServiceProxy('/asr_robot_model_services/GetCameraPose',GetPose)
return pose().pose | 5,197 |
def _convert_model_from_bytearray_to_object(model_bytearray):
"""Converts a tflite model from a bytearray into a parsable object."""
model_object = schema_fb.Model.GetRootAsModel(model_bytearray, 0)
model_object = schema_fb.ModelT.InitFromObj(model_object)
model_object = copy.deepcopy(model_object)
return mod... | 5,198 |
def hardenPointCurve(*args, **kwargs):
"""
The hardenPointCurve command changes the knots of a curve given a list of control point indices so that the knot corresponding to that control point gets the specified multiplicity.
Returns: `string[]` Object name and node name
"""
pass | 5,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.