content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_id(asset, **kwargs):
"""Get an asset by the unique id.
The key for the id must have 'id' in the name in the kwargs.
Example::
get_id(Foo, foo_id=1) # works
get_id(Foo, foo=1) # TypeError
"""
id_key = next(_parse_id(kwargs), None)
if id_key is None:
raise Typ... | 5,334,600 |
def put_study_document(request):
"""PUT method for editing an existing study.
Adds "resource_type" -> "study" then calls generic `put_document`.
See `finish_write_operation` for description of the response.
"""
request.matchdict['resource_type'] = 'study'
return put_document(request) | 5,334,601 |
def getDataByHash(sha256):
"""Grab all data Viper has. Save."""
payload = {'sha256': sha256}
resp = requests.post(viper_url + "file/find", payload,
headers=post_headers)
resp.raise_for_status()
result = resp.json()
data = {}
data = result['results']['default']
sa... | 5,334,602 |
def create_command(input_file, columns_to_use, column_separator, output_file):
"""
This function creates the linux command to filter the columns and creating the output file
:param input_file: A valid file path to raw data file
:param columns_to_use: Indexes of the columns that needs to be filtered out ... | 5,334,603 |
def create():
"""Creates all tables defined in models.py"""
db.create_all()
log.info("Table {} was created.".format(SETTINGS['provider_parameters']['table_name'])) | 5,334,604 |
def vprint(message, stream=DEFAULT_STREAM, flush=False):
"""
Easily handle verbose printing. Newline characters are automatically
appended if they are not already present.
Arguments:
message (str|unicode|list|tuple): A single or multi-line message to be
... | 5,334,605 |
def _new_data_generated(dataset, datagen):
"""
Function to put augmented data in directories
:param dataset: The path for the specified directory
:param datagen: The augmented data
:return: The new data to use for model
"""
new_data = datagen.flow_from_directory(
dataset,
tar... | 5,334,606 |
def findOutNode( node, testFunc, fallback=... ):
""" get node and all its parents, inner to outer order """
for out_node in getOutNodes( node ):
if testFunc( out_node ):
return out_node
if fallback is not ...:
return fallback
raise Exception( 'cannot find out node' ) | 5,334,607 |
def lookup_cpe(vendor, product, cpe_type, cpe_table, remap):
"""Identify the correct vendor and product values for a CPE
This function attempts to determine the correct CPE using vendor and product
values supplied by the caller as well as a remapping dictionary for mapping
these values to more correct ... | 5,334,608 |
def main():
"""main function of git learning
"""
return 'Google git' | 5,334,609 |
def tf_split_v_infer(node: Node):
"""
Partial infer of split node similar to SplitV op of TF.
"""
if len(node.in_nodes()) == 1 and not (node.has_valid('axis') and node.has_valid('size_splits')):
return
if len(node.in_nodes()) == 3 and (node.has_valid('axis') or node.has_valid('size_splits'... | 5,334,610 |
def SSIM(img1, img2, cs_map=False):
"""Return the Structural Similarity Map corresponding to input images img1
and img2 (images are assumed to be uint8)
This function attempts to mimic precisely the functionality of ssim.m a
MATLAB provided by the author's of SSIM
https://ece.uwaterloo.... | 5,334,611 |
def covariance(prices: np.ndarray) -> np.ndarray:
"""Calculate covariance matrix.
Args:
prices: Prices of market data.
Returns:
Covariance matrix.
"""
Q = np.cov(prices.T, ddof=0)
return np.array(Q) | 5,334,612 |
def resume_scrape(db, tf):
"""
Resume a unfinished scrape. Need to import a task file
:param db: Dictionary object to which the task information is stored
:param tf: File descriptor for the task file
"""
store = json.load(db)
db.close()
db = open(tf, 'w')
rosie = crawler.Crawler(db=... | 5,334,613 |
def fiveplates_clean_design_file(field, designID):
"""
string representation of targets_clean file for field within
fiveplates_field_files zip file.
Parameters
----------
field : str
identifier of field, e.g. 'GG_010'
"""
return f'{field}_des{designID}_targets_clean.txt' | 5,334,614 |
def setup_figure(diff=False):
"""Set diff to True if you want an additional panel showing pair-wise differences in accuracy"""
fig = plt.figure(figsize=(2*3.385, 2*3)) # two column figure for bio-informatics
plt.subplots_adjust(left=0.15, bottom=0.1, right=0.98, top=0.93, wspace=0.05, hspace=0.01)
gs = plt.Gri... | 5,334,615 |
def main():
"""Connects to the stream and starts threads to write them to a file."""
listener = QueueListener()
ckey="i9m8JABm5zmB1scZDUg94SLf4"
csecret="Og7AXk99eXMF4v6sc0FTj3fEvfdDhkATzr3HZnNJksXCBPClpF"
atoken="258676850-2TSMkNpJq3mkp6SXXIDoHZvTtthnPkOgR3utaxME"
asecret="vz22ULf6FKowaDq2GIh0t... | 5,334,616 |
def load_axon_morphometrics(morphometrics_file):
"""
:param morphometrics_file: absolute path of file containing the morphometrics (must be .csv, .xlsx or pickle format)
:return: stats_dataframe: dataframe containing the morphometrics
"""
# If string, convert to Path objects
morphometrics_f... | 5,334,617 |
def register_network(key, module):
"""
Register a customized GNN model.
After registeration, the module can be directly called by GraphGym.
Args:
key (string): Name of the module
module: PyTorch module
"""
register(key, module, network_dict) | 5,334,618 |
def fatal(message: str) -> None:
"""
Sends a message with the FATAL prefix.
:param message: The message that must be printed.
"""
if log:
printf(fatal_prefix + message) | 5,334,619 |
def get_input_costs(
inputs, cost_class="monetary", unit="billion_2015eur", mapping=COST_NAME_MAPPING,
**kwargs
):
"""
Get costs used as model inputs
"""
costs = {}
for var_name, var_data in inputs.data_vars.items():
if "costs" not in var_data.dims or not var_name.startswith("cost"):... | 5,334,620 |
def render_template(language, context, data, template):
"""Renders HTML display of metadata XML"""
env = Environment(extensions=['jinja2.ext.i18n'],
loader=FileSystemLoader(context.ppath))
env.install_gettext_callables(gettext, ngettext, newstyle=True)
template_file = 'resources/... | 5,334,621 |
def ht_26():
"""Making one Hash table instance with 26 key val pairs inserted."""
ht = HashTable()
count = 1
for char in letters:
ht.set(char, count)
count += 1
return ht | 5,334,622 |
def get_session(uuid):
"""
Api.get_session method
returns: [uuid, users, payload, state, ts]
200 -- session created
400 -- wrong arguments
403 -- wrong authorization
404 -- session not found
500 -- internal error
"""
conn = conn_get()
session = database.get_session(conn, uui... | 5,334,623 |
def fetch_data(
indicator: WorldBankIndicators, country_names: Iterable[str], fill_missing=None
) -> pd.DataFrame:
"""
Fetch data from the market_data_cache collection (not to be confused with the market_quote_cache collection)
and ensure the specified countries are only present in the data (if present)... | 5,334,624 |
def _(dbmodel, backend):
"""
get_backend_entity for Django DbAuthInfo
"""
from . import authinfos
return authinfos.DjangoAuthInfo.from_dbmodel(dbmodel, backend) | 5,334,625 |
def wavelen_diversity_doppler_est(echo, prf, samprate, bandwidth,
centerfreq):
"""Estimate Doppler based on wavelength diversity.
It uses slope of phase of range frequency along with single-lag
time-domain correlator approach proposed by [BAMLER1991]_.
Parameters
... | 5,334,626 |
def _parse_line(line):
"""
Parse node string representation and return a dict with appropriate node values.
"""
res = {}
if 'leaf' in line:
res['is_leaf'] = 1
res['leaf_val'] = _parse_leaf_node_line(line)
else:
res['is_leaf'] = 0
res['feature'], res['threshold']... | 5,334,627 |
def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> Optional[str]:
"""Generates a wrapper for richcompare dunder methods."""
# Sort for determinism on Python 3.5
matches = sorted([name for name in RICHCOMPARE_OPS if cl.has_method(name)])
if not matches:
return None
nam... | 5,334,628 |
def display_credentials():
"""
Function that displays all saved credentials
"""
return Credentials.display_credentials() | 5,334,629 |
def render_diff_report():
"""
Render a summary of the diffs found and/or changed.
Returns a string.
Dependencies:
config settings: action, templates, report_order
globals: diff_dict, T_NAME_KEY
modules: nori
"""
if nori.core.cfg['action'] == 'diff':
diff_report = ... | 5,334,630 |
def get_step_handler_for_gym_env(gym_env_name: str, cfg: Configuration) -> StepRewardDoneHandler:
"""Return an example step handler for the given gym environemtn name, that uses the
given config file."""
if gym_env_name == 'Acrobot-v1':
handler = AcrobotStepHandler(cfg)
elif gym_env_name ... | 5,334,631 |
def archive(ts):
"""Reprocess an older date
Currently, we only support the METAR database :(
"""
asos = get_dbconn('asos', user='nobody')
acursor = asos.cursor()
iem = get_dbconn('iem')
icursor = iem.cursor()
table = "t%s" % (ts.year,)
acursor.execute("""WITH data as (
SELE... | 5,334,632 |
def get_post_ids() -> list:
"""
"""
create_directory(WORK_PATH)
list_of_files_and_folders = os.listdir(WORK_PATH)
list_of_folders = []
for p in list_of_files_and_folders:
path = f'{WORK_PATH}/{p}'
if os.path.isdir(path):
list_of_folders.append(p)
list_of_post_id... | 5,334,633 |
def get_module(mod_name):
"""Import module and return."""
try:
return import_module(mod_name)
except ImportError:
logger.error('Failed to import module "%s".' % mod_name)
logger.error(traceback.format_exc())
raise | 5,334,634 |
def sort_ranks(ranks):
"""Sort ranks by MAIN_RANKS order.
Parameters
----------
ranks
Ranks to sort
Returns
-------
Sorted ranks
"""
ret = False
ranks = list(ranks) if not isinstance(ranks, list) else ranks
if len(ranks) > 0:
ret = [rank for rank in VA... | 5,334,635 |
def formalize_rules(list_rules):
""" Gives an list of rules where
facts are separeted by coma.
Returns string with rules in
convinient form (such as
'If' and 'Then' words, etc.).
"""
text = ''
for r in list_rules:
t = [i for i in r.split(',') if i]
... | 5,334,636 |
def load_bib(config):
"""Read bibliography file if there is one."""
if "bib" in config:
with open(config["bib"], "r") as reader:
config["bib_data"] = bibtexparser.load(reader).entries
else:
config["bib_data"] = {} | 5,334,637 |
def filenames_to_labels(filenames, filename_label_dict):
"""Converts filename strings to integer labels.
Args:
filenames (List[str]): The filenames of the images.
filename_label_dict (Dict[str, int]): A dictionary mapping filenames to
integer labels.
Returns:
ndarray: Integer labels
"""
re... | 5,334,638 |
def test_get_init_3():
"""get_init can't find __init__ in empty testdir"""
assert mp.get_init(TMP_TEST_DIR) is None | 5,334,639 |
def load_model():
"""
保存した提供されているモデルを読み込む
Returns
----------
model
提供されたmodel
tokernizre
提供されたヤツ(よくわかってない)
"""
with open(MODEL_DIR + 'model.pickle', 'rb') as f:
model = pick.load(f)
with open(MODEL_DIR + 'tokenizer.pickle', 'rb') as f:
tokenizer = pic... | 5,334,640 |
def json_write(data, fname) -> bool:
"""
Write to JSON file given data.
"""
with open(fname, 'w', encoding='utf-8') as f:
json.dump(
data,
f,
ensure_ascii=False,
indent=4
) | 5,334,641 |
def post(post_id):
"""View function for post page"""
# Form object: `Comment`
form = CommentForm()
# form.validate_on_submit() will be true and return the
# data object to form instance from user enter,
# when the HTTP request is POST
if form.validate_on_submit():
new_comment = Comm... | 5,334,642 |
def pipe(val, *funcs):
"""Pipe a value through a sequence of functions
I.e. ``pipe(val, f, g, h)`` is equivalent to ``h(g(f(val)))``
>>> double = lambda i: 2 * i
>>> pipe(3, double, str)
'6'
"""
if not funcs:
raise PipeNotGivenAnyFunctions
if any_is_async(funcs):
return... | 5,334,643 |
def do_query(method, query, values):
"""Executes a query on a DFP API method, returning a list of results."""
# Trap exceptions here instead of in caller?
statement = dfp.FilterStatement(query, values)
data = []
while True:
response = method(statement.ToStatement())
if 'results' in response:
d... | 5,334,644 |
def markdown_format(text):
"""
The outside param 'name' is similar to "tag" (in 'usage')
which it'll determines how you use it, e.g. {{ THING | FILTER }}.
Just a reminder
for tag, {% my_post_count %}
for filter, {{ post.body | truncatewords:30 }}
... | 5,334,645 |
def _find_tex_env_recursive(original_s: str, s: str, offset: int = 0, depth: int = 0) -> List:
"""
Find all environments.
:param s: Latex string code
:param offset: Offset applied to the search
:return: Tuple of all commands
"""
tags = find_tex_commands(s, offset=offset)
new_tags = []
... | 5,334,646 |
def group_by_instance_type(
jobs: Iterable[JobConfiguration],
) -> List[List[JobConfiguration]]:
"""
Group job-configuration into different queues depending on which instance
each job should be run. This returns a list of the different queues.
>>> group_by_instance_type( # doctest: +SKIP
... ... | 5,334,647 |
def integral_func(phi, th1, n):
""" Used in computing the continuous hypersphere cap intersection below. """
return np.sin(phi)**(n-2) * scipy.special.betainc( (n-2)/2 , 1/2, 1-( (np.tan(th1))/(np.tan(phi)) )**2 ) | 5,334,648 |
def remove_first_item(nested_list):
"""
Removes the first element of the deepest list.
>>> tuple(remove_first_item([['abc','def','ghi'],['123','456','789'],[['000','999'],['AAA','BBB']]]))
(['def', 'ghi'], ['456', '789'], [['999'], ['BBB']])
"""
for item in nested_list:
if isinstance(ite... | 5,334,649 |
def test_model(image_path, class_names, img_height, img_width):
"""测试你的模型"""
img = keras.preprocessing.image.load_img(image_path, target_size=(img_height, img_width)) # 将图片加载为PIL格式
input_array = keras.preprocessing.image.img_to_array(img) # 将PIL映像实例转换为Numpy数组
input_array = np.array([input_array]) # 来... | 5,334,650 |
def asbytes(s: Literal["101 101 1.0e-05\n"]):
"""
usage.scipy: 1
"""
... | 5,334,651 |
def addList():
"""
Add a list. Needs custom function to create its internal meta object
"""
pass | 5,334,652 |
def order(order_id,complete):
"""
Charge completion return URL. Once the customer is redirected
back to this site from the authorization page, we search for the
charge based on the provided `order_id`.
"""
return render_template(
"complete.html",
order_id=order_id,
comp... | 5,334,653 |
def load_dimension_subdag(
parent_dag_name,
task_id,
redshift_conn_id,
*args, **kwargs):
"""
A python function with arguments, which creates a dag
:param parent_dag_name: imp ({parent_dag_name}.{task_id})
:param task_id: imp {task_id}
:param redshift_conn_id: {any con... | 5,334,654 |
def get_ns_lns_ids_config_file():
"""Reads node_id to host name mapping from one of the config files in the map"""
assert exp_config.node_config_folder is not None and os.path.exists(exp_config.node_config_folder)
files = os.listdir(exp_config.node_config_folder)
# read mapping from any file
return... | 5,334,655 |
def find(name, environment=None, guess=None):
"""Finds a particular binary on this system.
Attempts to find the binary given by ``name``, first checking the value of
the environment variable named ``environment`` (if provided), then by
checking the system path, then finally checking hardcoded paths in
... | 5,334,656 |
def upload_to(path):
"""
Generates unique ascii filename before saving. Supports strftime()
formatting as django.db.models.FileField.upload_to does.
Example:
class SomeModel(models.Model):
picture = models.ImageField(upload_to=upload_to('my_model_uploads/'))
It is possible to ... | 5,334,657 |
def standardize_measurements_lastref(measurements: List[Measurement], remove_ref: bool = True) \
-> List[Measurement]:
""" Sets the standardization of all measurement to the Reference Measurement before """
last_null_meas = None
clean_measurements = []
for measurement in measurements:
i... | 5,334,658 |
def blg2texkey(filename):
"""Extract TeX keys from a .blg file."""
keys = []
if not os.path.exists(filename):
LOGGER.error("File %s not found.", filename)
return keys
with open(filename, "r") as f:
lines = f.readlines()
# regexp to match 'Warning--I didn\'t find a database en... | 5,334,659 |
def build_train_valid_test_data_iterators(
build_train_valid_test_datasets_provider):
"""XXX"""
args = get_args()
(train_dataloader, valid_dataloader, test_dataloader) = (None, None, None)
print_rank_0('> building train, validation, and test datasets ...')
# Backward compatibility, assume... | 5,334,660 |
def get_lib_ver(library_path=""):
"""Returns the version of the Minipresto library.
### Parameters
- `library_path`: The Minipresto library directory."""
version_file = os.path.join(library_path, "version")
try:
with open(version_file, "r") as f:
for line in f:
... | 5,334,661 |
def test_validate_email():
"""Confirm that "only" valid emails are accepted."""
validator = validate.VALIDATION_MAPPER["email"]
assert validator("")
assert validator("test@example.com")
assert validator("test.name@sub.example.com")
with pytest.raises(ValueError):
validator("test@localh... | 5,334,662 |
def width():
"""Get console width."""
x, y = get()
return x | 5,334,663 |
def load_yaml_config(path):
"""returns the config parsed based on the info in the flags.
Grabs the config file, written in yaml, slurps it in.
"""
with open(path) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
return config | 5,334,664 |
def convert_year(years, debug=False):
"""Example usage: db['date'] = cln.convert_year(db['date']) """
for i, yr in years.iteritems():
if debug:
print(yr)
print(type(yr))
if yr is None:
years.set_value(i, np.nan)
continue
if is_int(yr):
... | 5,334,665 |
def home(request):
"""View function for home page of site."""
return laboratorio_list(request) | 5,334,666 |
def scan_armatures(context):
"""
scans the selected objects or the scene for a source (regular)
armature and a destination (Make Human) armature
"""
src = (
scan_for_armature(context.selected_objects)
or scan_for_armature(context.scene.objects)
)
dst = (
s... | 5,334,667 |
def populate_instance(msg, inst):
"""
:param msg: contains the values to use to populate inst.
:param inst: message class instance to populate.
:return: an instance of the provided message class, with its fields populated according to the values in msg
"""
return _to_inst(msg, type(inst).__name_... | 5,334,668 |
def setup_args():
"""Setup and return the command line argument parser"""
parser = argparse.ArgumentParser(description='')
# parser.add_argument('csv', type=str, help='CSV file to load')
parser.add_argument(
'-clang-tidy-binary', help='Path to the clang-tidy executable.', metavar='PATH', requir... | 5,334,669 |
def create_event(type_, source):
"""Create Event"""
cls = _events.get(type_, UnknownEvent)
try:
return cls(type=type_, **source)
except TypeError as e:
raise TypeError(f'Error at creating {cls.__name__}: {e}') | 5,334,670 |
def _execute(script, prefix=None, path=None):
"""
Execute a shell script.
Setting prefix will add the environment variable
COLCON_BUNDLE_INSTALL_PFREFIX equal to the passed in value
:param str script: script to execute
:param str prefix: the installation prefix
:param str path: (optional) ... | 5,334,671 |
def main(event, context):
"""
Gets layer arns for each region and publish to S3
"""
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["DB_NAME"])
region = event.get("pathParameters").get("region")
python_version = event.get("pathParameters").get("python_version", "p3.8... | 5,334,672 |
def rescore_and_rerank_by_num_inliers(test_image_id,
train_ids_labels_and_scores):
"""Returns rescored and sorted training images by local feature extraction."""
test_image_path = get_image_path(test_image_id)
try:
name = os.path.basename(test_image_path).spli... | 5,334,673 |
def aggregate_policy(
policies: Iterable[PermissionPolicy_T],
aggregator: Callable[[Iterable[object]], bool] = all
) -> PermissionPolicy_T:
"""
在默认参数下,将多个权限检查策略函数使用 AND 操作符连接并返回单个权限检查策略。在实现中对这几个策略使用内置 `all` 函数,会优先执行同步函数而且尽可能在同步模式的情况下短路。
在新的策略下,只有事件满足了 `policies` 中所有的原策略,才会返回 `True`。
`aggregato... | 5,334,674 |
def optionally_load_system_paasta_config(
path: str = PATH_TO_SYSTEM_PAASTA_CONFIG_DIR,
) -> "SystemPaastaConfig":
"""
Tries to load the system paasta config, but will return an empty configuration if not available,
without raising.
"""
try:
return load_system_paasta_config(path=path)
... | 5,334,675 |
def get_sage_bank_accounts(company_id: int) -> list:
"""
Retrieves the bank accounts for a company in Sage One
**company_id** The Company ID
"""
config = get_config() # Get the config
sage_client = SageOneAPIClient(config.get("sageone", "url"), config.get("sageone", "api_key"), config.get("sage... | 5,334,676 |
def compute_fstar(tarr, mstar, index_select, index_high, fstar_tdelay):
"""Time averaged SFH that has ocurred over some previous time period
fstar = (mstar(t) - mstar(t-fstar_tdelay)) / fstar_tdelay
Parameters
----------
tarr : ndarray of shape (n_times, )
Cosmic time of each simulated snap... | 5,334,677 |
def workaround():
"""contextually invoke this when loading *.src.py"""
__metadata_to_wrap.__globals__["metadata"] = metadata
try:
yield
finally:
__metadata_to_wrap.__globals__["metadata"] = __metadata_to_wrap | 5,334,678 |
def notification_error(code: str, search_id: str, status_code, message: str = None):
"""Return to the event listener a notification error response based on the status code."""
error = CALLBACK_MESSAGES[code].format(search_id=search_id)
if message:
error += ' ' + message
current_app.logger.error(... | 5,334,679 |
async def send_dumplings_from_queue_to_hub(
kitchen_name: str,
hub: str,
dumpling_queue: multiprocessing.Queue,
kitchen_info: dict,
log: logging.Logger,
):
"""
Grabs dumplings from the dumpling queue and sends them to ``nd-hub``.
:param kitchen_name: The name of the ... | 5,334,680 |
def get_avg(feature_name, default_value):
"""Get the average of numeric feature from the environment.
Return the default value if there is no the statistics in
the environment.
Args:
feature_name: String, feature name or column name in a table
default_value: Float.
Return:
... | 5,334,681 |
def arccos(x: REAL) -> float:
"""Arc cosine."""
return pi/2 - arcsin(x) | 5,334,682 |
def isLinkValid(test_video_link):
"""def isLinkValid(test_video_link): -> test_video_link
check if youtube video link is valid."""
try:
import requests
data = requests.get("https://www.youtube.com/oembed?format=json&url=" + test_video_link).json()
if data == "Not Found":
... | 5,334,683 |
def _strptime(data_string, format='%a %b %d %H:%M:%S %Y'):
"""Return a 2-tuple consisting of a time struct and an int containing
the number of microseconds based on the input string and the
format string."""
for index, arg in enumerate([data_string, format]):
if not isinstance(arg, str):
... | 5,334,684 |
def to_simple_rdd(sc, features, labels):
"""Convert numpy arrays of features and labels into
an RDD of pairs.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:return: Spark RDD with feature-label pairs
"""
pairs = [(x, y) for x,... | 5,334,685 |
def delete():
"""Delete located record, if there is one."""
if g[REC]:
records.remove(g[REC])
g[REC] = None | 5,334,686 |
def add_decimal(op1: Decimal, op2: Decimal)-> Decimal:
"""
add
:param op1:
:param op2:
:return:
"""
result = op1 + op2
if result > 999:
return float(result)
return result | 5,334,687 |
def get_data_file_path(project, filename):
"""
Gets the path of data files we've stored for each project
:param project:
:return:
"""
return os.path.join(BASE_DIR, "waterspout_api", "data", project, filename) | 5,334,688 |
def test_PoliteBufferedConsumer(flush: mock.MagicMock) -> None:
"""Test that PoliteBufferedConsumer logs errors and continues."""
structlog.configure(
processors=[structlog.processors.KeyValueRenderer(sort_keys=True)],
logger_factory=structlog.stdlib.LoggerFactory(),
)
consumer = Polite... | 5,334,689 |
def freenas_spec(**kwargs):
"""FreeNAS specs."""
# Setup vars from kwargs
builder_spec = kwargs['data']['builder_spec']
bootstrap_cfg = None
builder_spec.update(
{
'boot_command': [
'<enter>',
'<wait30>1<enter>',
'y',
... | 5,334,690 |
def test_id_g017_id_g017_v(mode, save_output, output_format):
"""
TEST :Identity-constraint Definition Schema Component : key category,
selector points to element outside of targetNamespace in a non-
imported schema
"""
assert_bindings(
schema="msData/identityConstraint/idG017.xsd",
... | 5,334,691 |
def checksum(routine):
"""
Compute the M routine checksum used by ``CHECK1^XTSUMBLD``,
implemented in ``^%ZOSF("RSUM1")`` and ``SUMB^XPDRSUM``.
"""
checksum = 0
lineNumber = 0
with open(routine, 'r') as f:
for line in f:
line = line.rstrip('\r\n')
lineNumber += 1
# ignore the second ... | 5,334,692 |
def nusdas_parameter_change(param, value):
"""
def nusdas_parameter_change()
"""
# Set argtypes and restype
nusdas_parameter_change_ct = libnus.NuSDaS_parameter_change
nusdas_parameter_change_ct.restype = c_int32
nusdas_parameter_change_ct.argtypes = (c_int32,POINTER(c_int32))
icond... | 5,334,693 |
def validate_retention_time(retention_time):
# type: (str) -> str
"""Validate retention_time. If -1, return string, else convert to ms.
Keyword arguments:
retention_time -- user configured retention-ms, pattern: %d%h%m%s%ms
Return:
retention_time -- If set to "-1", return it
"""
if ret... | 5,334,694 |
def is_sale(this_line):
"""Determine whether a given line describes a sale of cattle."""
is_not_succinct = len(this_line.split()) > 3
has_price = re.search(r'[0-9]+\.[0-9]{2}', this_line)
return bool(has_price and is_not_succinct) | 5,334,695 |
def map_copy(source: tcod.map.Map, dest: tcod.map.Map) -> None:
"""Copy map data from `source` to `dest`.
.. deprecated:: 4.5
Use Python's copy module, or see :any:`tcod.map.Map` and assign between
array attributes manually.
"""
if source.width != dest.width or source.height != dest.hei... | 5,334,696 |
def transformRoot():
"""Bind trackball to the root object.
The mouse transforms the whole scene move"""
vi = self.GUI.VIEWER
vi.TransformRootOnly(yesno=1)
vi.SetCurrentObject(vi.rootObject) | 5,334,697 |
def extract_policy(env, v, gamma = 1.0):
""" Extract the policy given a value-function """
policy = np.zeros(env.env.nS)
for s in range(env.env.nS):
q_sa = np.zeros(env.env.nA)
for a in range(env.env.nA):
q_sa[a] = sum([p * (r + gamma * v[s_]) for p, s_, r, _ in env.env.P[s][a]])... | 5,334,698 |
def generate_parameters(var):
"""
Defines a distribution of parameters
Returns a settings dictionary
var is an iterable of variables in the range [0,1) which
we can make use of.
"""
var = iter(var)
model={}
training={}
settings = {'model':model, 'training':training}
# ma... | 5,334,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.