content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_conf_file_interface(config_name):
"""
Get interface settings.
@param config_name: Name of WG interface
@type config_name: str
@return: Dictionary with interface settings
@rtype: dict
"""
conf_location = WG_CONF_PATH + "/" + config_name + ".conf"
with open(conf_location, 'r'... | 5,341,600 |
def test_basic_reliable_data_transfer():
"""Basic test: Check that when you run server and client starter code
that the input file equals the output file
"""
# Can you think of how you can test this? Give it a try!
pass | 5,341,601 |
def add_to_history(media, watched_at=None):
"""Add a :class:`Movie`, :class:`TVShow`, or :class:`TVEpisode` to your
watched history.
:param media: The media object to add to your history
:param watched_at: A `datetime.datetime` object indicating the time at
which this media item was viewed
... | 5,341,602 |
def book_transformer(query_input, book_dict_input):
"""grabs the book and casts it to a list"""
sample_version = versions_dict.versions_dict()
query_input[1] = query_input[1].replace('[', '').replace(']', '').lstrip().rstrip().upper()
for i in list(book_dict_input.keys()):
result = re.search(i, ... | 5,341,603 |
def custom_response(message, status, mimetype):
"""handle custom errors"""
resp = Response(json.dumps({"message": message, "status_code": status}),
status=status,
mimetype=mimetype)
return resp | 5,341,604 |
def demo():
"""
Let the user play around with the standard scene using programmatic
instructions passed directly to the controller.
The environment will be displayed in a graphics window. The user can type
various commands into the graphics window to query the scene and control
the grasper. Typ... | 5,341,605 |
def embed_network(input_net, layers, reuse_variables=False):
"""Convolutional embedding."""
n_layers = int(len(layers)/3)
tf.logging.info('Number of layers: %d' % n_layers)
# set normalization and activation functions
normalizer_fn = None
activation_fn = tf.nn.softplus
tf.logging.info('Softplus activati... | 5,341,606 |
def write_pair(readID, read1, read2, fh_out_R1, fh_out_R2):
"""Write paired reads to two files"""
fh_out_R1.write("@%s\n%s\n+\n%s\n" % (readID + "/1", read1[0], read1[1]))
fh_out_R2.write("@%s\n%s\n+\n%s\n" % (readID + "/2", read2[0], read2[1]))
pass | 5,341,607 |
def sample_variance(sample1, sample2):
"""
Calculate sample variance. After learn.co
"""
n_1, n_2 = len(sample1), len(sample2)
var_1, var_2 = variance(sample1), variance(sample2)
return (var_1 + var_2)/((n_1 + n_2)-2) | 5,341,608 |
def dwritef2(obj, path):
"""The dwritef2() function writes the object @p obj to the Python
pickle file whose path is pointed to by @p path. Non-existent
directories of @p path are created as necessary.
@param obj Object to write, as created by e.g. dpack()
@param path Path of output file
@return Path... | 5,341,609 |
def extract_test_zip(pattern, dirname, fileext):
"""Extract a compressed zip given the search pattern.
There must be one and only one matching file.
arg 1- search pattern for the compressed file.
arg 2- name of the output top-level directory.
arg 3- a list of search patterns for the sour... | 5,341,610 |
def test_imageprocessor_read():
"""Test the Imageprocessor."""
# Test with 4 channels
transform_sequence = [ToPILImage('RGBA')]
p = ImageProcessor(transform_sequence)
img_out = p.apply_transforms(test_input)
assert np.array(img_out).shape == (678, 1024, 4)
# Test with 3 channels
transf... | 5,341,611 |
def app(*tokens):
"""command function to add a command for an app with command name."""
apps_handler.add(*tokens) | 5,341,612 |
def test_ant():
"""
target_files = [
"tests/apache-ant/main/org/apache/tools/ant/types/ArchiveFileSet.java",
"tests/apache-ant/main/org/apache/tools/ant/types/TarFileSet.java",
"tests/apache-ant/main/org/apache/tools/ant/types/ZipFileSet.java"
]
"""
ant_dir = "/home/ali/Deskt... | 5,341,613 |
def calculate_area(geometry):
"""
Calculate geometry area
:param geometry: GeoJSON geometry
:return: the geometry area
"""
coords = get_coords_from_geometry(
geometry, ["Polygon", "MultiPolygon"], raise_exception=False
)
if get_input_dimensions(coords) >= 4:
areas = l... | 5,341,614 |
def read_prb(file):
"""
Read a PRB file and return a ProbeGroup object.
Since PRB do not handle contact shape then circle of 5um are put.
Same for contact shape a dummy tip is put.
PRB format do not contain any information about the channel of the probe
Only the channel index on device is give... | 5,341,615 |
def alt_credits():
""" Route for alt credits page. Uses json list to generate page body """
alternate_credits = tasks.json_list(os.path.join(pathlib.Path(__file__).parent.absolute(),'static/alt_credits.json'))
return render_template('alt_credits.html',title='collegeSMART - Alternative College Credits',alt_c... | 5,341,616 |
def CreateNode(parent, node_type, position, wx_id):
""" Create an instance of a node associated with the specified name.
:param parent: parent of the node object (usually a wx.Window)
:param node_type: type of node from registry - the IDName
:param position: default position for the node
:param wx_... | 5,341,617 |
def decode_json_content(content):
"""
Decodes a given string content to a JSON object
:param str content: content to be decoded to JSON.
:return: A JSON object if the string could be successfully decoded and None otherwise
:rtype: json or None
"""
try:
return json.loads(content) if c... | 5,341,618 |
def plot_dist(noise_feats, label=None, ymax=1.1, color=None, title=None, save_path=None):
"""
Kernel density plot of the number of noisy features included in explanations,
for a certain number of test samples
"""
if not any(noise_feats): # handle special case where noise_feats=0
noise_feat... | 5,341,619 |
def simple_simulate(choosers, spec, nest_spec,
skims=None, locals_d=None,
chunk_size=0, custom_chooser=None,
log_alt_losers=False,
want_logsums=False,
estimator=None,
trace_label=None, trace_choice_na... | 5,341,620 |
def state(predicate):
"""DBC helper for reusable, simple predicates for object-state tests used in both preconditions and postconditions"""
@wraps(predicate)
def wrapped_predicate(s, *args, **kwargs):
return predicate(s)
return wrapped_predicate | 5,341,621 |
def dpp(kernel_matrix, max_length, epsilon=1E-10):
"""
Our proposed fast implementation of the greedy algorithm
:param kernel_matrix: 2-d array
:param max_length: positive int
:param epsilon: small positive scalar
:return: list
"""
item_size = kernel_matrix.shape[0]
cis = np... | 5,341,622 |
def adjust_image_resolution(data):
"""Given image data, shrink it to no greater than 1024 for its larger
dimension."""
inputbytes = cStringIO.StringIO(data)
output = cStringIO.StringIO()
try:
im = Image.open(inputbytes)
im.thumbnail((240, 240), Image.ANTIALIAS)
# co... | 5,341,623 |
def timing_function():
"""
There's a better timing function available in Python 3.3+
Otherwise use the old one.
TODO: This could be a static analysis at the top of the module
"""
if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
return time.monotonic()
else:
return t... | 5,341,624 |
async def test_volume_down(mock_device, heos):
"""Test the volume_down command."""
await heos.get_players()
player = heos.players.get(1)
with pytest.raises(ValueError):
await player.volume_down(0)
with pytest.raises(ValueError):
await player.volume_down(11)
mock_device.register(
... | 5,341,625 |
def parse_date(txt):
""" Returns None or parsed date as {h, m, D, M, Y}. """
date = None
clock = None
for word in txt.split(' '):
if date is None:
try:
date = datetime.strptime(word, "%d-%m-%Y")
continue
except ValueError:
... | 5,341,626 |
def log_success(msg):
"""
Log success message
:param msg: Message to be logged
:return: None
"""
print("[+] " + str(msg))
sys.stdout.flush() | 5,341,627 |
def diff_configurations(model_config, bench_config, model_bundle, bench_bundle):
"""
Description
Args:
model_config: a dictionary with the model configuration data
bench_config: a dictionary with the benchmark configuration data
model_bundle: a LIVVkit model bundle object
be... | 5,341,628 |
def update_statvar_dcids(statvar_list: list, config: dict):
"""Given a list of statvars, generates the dcid for each statvar after
accounting for dependent PVs.
"""
for d in statvar_list:
ignore_props = get_dpv(d, config)
dcid = get_statvar_dcid(d, ignore_props=ignore_props)
d['N... | 5,341,629 |
def _extract_archive(file_path, path='.', archive_format='auto'):
"""Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats.
Arguments:
file_path: path to the archive file
path: path to extract the archive file
archive_format: Archive format to try for extracting the file.... | 5,341,630 |
def calc_angle(m, n):
"""
Calculate the cosθ,
where θ is the angle between 2 vectors, m and n.
"""
if inner_p_s(m, n) == -1:
print('Error! The 2 vectors should belong on the same space Rn!')
elif inner_p_s(m,n) == 0:
print('The cosine of the two vectors is 0, so th... | 5,341,631 |
def Seuil_var(img):
"""
This fonction compute threshold value. In first the image's histogram is calculated. The threshold value is set to the first indexe of histogram wich respect the following criterion : DH > 0, DH(i)/H(i) > 0.1 , H(i) < 0.01 % of the Norm.
In : img : ipl Image : image to treated
... | 5,341,632 |
def convert_numpy(file_path, dst=None, orient='row', hold=False, axisf=False, *arg):
"""
Extract an array of data stored in a .npy file or DATABLOCK
Parameters
---------
file_path : path (str)
Full path to the file to be extracted.
dst : str
Full path to t... | 5,341,633 |
def index():
"""Every time the html page refreshes this function is called.
Checks for any activity from the user (setting an alarm, deleting an alarm,
or deleting a notification)
:return: The html template with alarms and notifications added
"""
notification_scheduler.run(blocking=False)
... | 5,341,634 |
def team_6_adv():
"""
Team 6's refactored chapter.
Originally by lovelle, refactored by lovelle.
:return: None
"""
global dead
direction = input("Which direction would you like to go? [North/South/East/West] ")
if direction == "East":
# Good choice
print()
prin... | 5,341,635 |
def do_upgrade_show(cc, args):
"""Show software upgrade details and attributes."""
upgrades = cc.upgrade.list()
if upgrades:
_print_upgrade_show(upgrades[0])
else:
print('No upgrade in progress') | 5,341,636 |
def check_icinga_should_run(state_file: str) -> bool:
"""Return True if the script should continue to update the state file, False if the state file is fresh enough."""
try:
with open(state_file) as f:
state = json.load(f)
except Exception as e:
logger.error('Failed to read Icing... | 5,341,637 |
def ln_new_model_to_gll(py, new_flag_dir, output_dir):
"""
make up the new gll directory based on the OUTPUT_MODEL.
"""
script = f"{py} -m seisflow.scripts.structure_inversion.ln_new_model_to_gll --new_flag_dir {new_flag_dir} --output_dir {output_dir}; \n"
return script | 5,341,638 |
def compare_tuple(Procedure, cfg):
"""Validate the results using a tuple
"""
profile = DummyData()
tp = {}
for v in profile.keys():
if isinstance(profile[v], ma.MaskedArray) and profile[v].mask.any():
profile[v][profile[v].mask] = np.nan
profile.data[v] = profile[v].d... | 5,341,639 |
def deserialize_item(item: dict):
"""Deserialize DynamoDB item to Python types.
Args:
item: item to deserialize
Return: deserialized item
"""
return {k: DDB_DESERIALIZER.deserialize(v) for k, v in item.items()} | 5,341,640 |
def good_result(path_value, pred, source=None, target_path=''):
"""Constructs a JsonFoundValueResult where pred returns value as valid."""
source = path_value.value if source is None else source
return jp.PathValueResult(pred=pred, source=source, target_path=target_path,
path_value=pat... | 5,341,641 |
def add_task(task_name):
"""Handles the `add_task` command.
Syntax: `add_task <task_name>`
Function: register a new task in TASK_NAME_CACHE
Precondition on argument `task_name`:
- `task_name` is non-empty and is registered in global object task_keys as the the input validation has already been
... | 5,341,642 |
def bot_properties(bot_id):
"""
Return all available properties for the given bot. The bot id should be
available in the `app.config` dictionary.
"""
bot_config = app.config['BOTS'][bot_id]
return [pd[0] for pd in bot_config['properties']] | 5,341,643 |
def find_path(ph_tok_list, dep_parse, link_anchor, ans_anchor, edge_dict, ph_dict):
"""
:param dep_parse: dependency graph
:param link_anchor: token index of the focus word (0-based)
:param ans_anchor: token index of the answer (0-based)
:param link_category: the category of the current focus link
... | 5,341,644 |
def get_theme_section_directories(theme_folder:str, sections:list = []) -> list:
"""Gets a list of the available sections for a theme
Explanation
-----------
Essentially this function goes into a theme folder (full path to a theme), looks for a folder
called sections and returns a list of all the ... | 5,341,645 |
def download_video_url(
video_url: str,
pipeline: PipelineContext,
destination="%(title)s.%(ext)s",
progress=ProgressMonitor.NULL,
):
"""Download a single video from the ."""
config = pipeline.config
logger = logging.getLogger(__name__)
logger.info("Starting video download from URL: %s"... | 5,341,646 |
def get_block_name(source):
"""Get block name version from source."""
url_parts = urlparse(source)
file_name = url_parts.path
extension = file_name.split(".")[-1]
new_path = file_name.replace("." + extension, "_block." + extension)
new_file_name = urlunparse(
(
url_parts.s... | 5,341,647 |
def int_to_symbol(i):
""" Convert numeric symbol or token to a desriptive name.
"""
try:
return symbol.sym_name[i]
except KeyError:
return token.tok_name[i] | 5,341,648 |
def test_iron_skillet(g):
"""
Test the "iron-skillet" snippet
"""
sc = g.build()
test_stack = 'snippets'
test_snippets = ['all']
push_test(sc, test_stack, test_snippets) | 5,341,649 |
def write_radius_pkix_cd_manage_trust_infile(policy_json, roles, trust_infile_path):
"""Write the input file for radius_pkix_cd_manage_trust.py."""
role_list = roles.split(",")
ti_file_lines = []
for role in role_list:
for policy_role in policy_json["roles"]:
if policy_role["name"] =... | 5,341,650 |
def debugger(parser, token):
"""
Activates a debugger session in both passes of the template renderer
"""
pudb.set_trace()
return DebuggerNode() | 5,341,651 |
def extra_init(app):
"""Extra blueprint initialization that requires application context."""
if 'header_links' not in app.jinja_env.globals:
app.jinja_env.globals['header_links'] = []
# Add links to 'header_links' var in jinja globals. This allows header_links
# to be read by all templates in th... | 5,341,652 |
def get_openmm_energies(system_pdb, system_xml):
"""
Returns decomposed OPENMM energies for the
system.
Parameters
----------
system_pdb : str
Input PDB file
system_xml : str
Forcefield file in XML format
"""
pdb = simtk.openmm.app.PDBFile(system_pdb)
ff_xml_... | 5,341,653 |
def cranimp(i, s, m, N):
"""
Calculates the result of c_i,s^dag a_s acting on an integer m. Returns the new basis state and the fermionic prefactor.
Spin: UP - s=0, DOWN - s=1.
"""
offi = 2*(N-i)-1-s
offimp = 2*(N+1)-1-s
m1 = flipBit(m, offimp)
if m1<m:
m2=flipBit(m1, offi)
if m2>m1:
prefactor = prefac... | 5,341,654 |
def _can_beeify():
""" Determines if the random chance to beeify has occured """
return randint(0, 12) == 0 | 5,341,655 |
def test_relax_parameters_vol_shape(init_relax_parameters):
"""Test volume and shape relaxation combinations."""
del init_relax_parameters.relax.positions
massager = ParametersMassage(init_relax_parameters)
parameters = massager.parameters[_DEFAULT_OVERRIDE_NAMESPACE]
assert parameters.isif == 6 | 5,341,656 |
def p_for_header(p):
"""
for_header : for_simple
| for_complex
"""
p[0] = p[1] | 5,341,657 |
def get_object_classes(db):
"""return a list of all object classes"""
list=[]
for item in classinfo:
list.append(item)
return list | 5,341,658 |
def load_arviz_data(dataset=None, data_home=None):
"""Load a local or remote pre-made dataset.
Run with no parameters to get a list of all available models.
The directory to save to can also be set with the environement
variable `ARVIZ_HOME`. The checksum of the dataset is checked against a
hardco... | 5,341,659 |
def get_ax(rows=1, cols=1, size=8):
"""Return a Matplotlib Axes array to be used in
all visualizations in the notebook. Provide a
central point to control graph sizes.
Change the default size attribute to control the size
of rendered images
"""
_, ax = plt.subplots(rows, cols, figsize=(size... | 5,341,660 |
def prepare_ablation_from_config(config: Mapping[str, Any], directory: str, save_artifacts: bool):
"""Prepare a set of ablation study directories."""
metadata = config['metadata']
optuna_config = config['optuna']
ablation_config = config['ablation']
evaluator = ablation_config['evaluator']
eval... | 5,341,661 |
def spin_coherent(j, theta, phi, type='ket'):
"""Generates the spin state |j, m>, i.e. the eigenstate
of the spin-j Sz operator with eigenvalue m.
Parameters
----------
j : float
The spin of the state.
theta : float
Angle from z axis.
phi : float
Angle from x axis... | 5,341,662 |
def vgg_upsampling(classes, target_shape=None, scale=1, weight_decay=0., block_name='featx'):
"""A VGG convolutional block with bilinear upsampling for decoding.
:param classes: Integer, number of classes
:param scale: Float, scale factor to the input feature, varing from 0 to 1
:param target_shape: 4D... | 5,341,663 |
def show_toolbar(request):
"""Determine if toolbar will be displayed."""
return settings.DEBUG | 5,341,664 |
def compute_metrics(logits, labels, weights):
"""Compute summary metrics."""
loss, weight_sum = compute_weighted_cross_entropy(logits, labels, weights)
acc, _ = compute_weighted_accuracy(logits, labels, weights)
metrics = {
'loss': loss,
'accuracy': acc,
'denominator': weight_sum,
}
return... | 5,341,665 |
def test_wild080_wild080_v1_xml(mode, save_output, output_format):
"""
Consistency of governing type declarations between locally-declared
elements and lax wildcards in a content model No violation of Element
Declarations Consistent with a skip wildcard
"""
assert_bindings(
schema="saxon... | 5,341,666 |
def test_try_decorator():
"""Test try and log decorator."""
# for pydocstyle
@try_decorator("oops", default_return="failed")
def fn():
raise Exception("expected")
assert fn() == "failed" | 5,341,667 |
def start_session(web_session=None):
"""Starts a SQL Editor Session
Args:
web_session (object): The web_session object this session will belong to
Returns:
A dict holding the result message
"""
new_session = SqleditorModuleSession(web_session)
result = Response.ok("New SQL Edit... | 5,341,668 |
def show_box(box_data):
"""from box_data produce a 3D image of surfaces and display it"""
use_color_flag=True
reverse_redshift_flag=True
(dimx,dimy,dimz)=box_data.shape
print box_data.shape
mycolor='black-white'
if use_color_flag:
mycolor='blue-red'
mycolor='RdBu'
#need to set color ... | 5,341,669 |
async def error_middleware(request: Request, handler: t.Callable[[Request], t.Awaitable[Response]]) -> Response:
"""logs an exception and returns an error message to the client
"""
try:
return await handler(request)
except Exception as e:
logger.exception(e)
return json_response(... | 5,341,670 |
def init_mobility_accordion():
"""
Initialize the accordion for mobility tab.
Args: None
Returns:
mobility_accordion (object): dash html.Div that contains individual accordions
"""
accord_1 = init_accordion_element(
title="Mobility Index",
id='id_mobility_index',
... | 5,341,671 |
def per_image_whiten(X):
""" Subtracts the mean of each image in X and renormalizes them to unit norm.
"""
num_examples, height, width, depth = X.shape
X_flat = X.reshape((num_examples, -1))
X_mean = X_flat.mean(axis=1)
X_cent = X_flat - X_mean[:, None]
X_norm = np.sqrt( np.sum( X_cent * X... | 5,341,672 |
def test_is_read_values_any_allowed_cdf_single(
cursor, make_user_roles, new_cdf_forecast, other_obj):
"""That that a user can (and can not) perform the specified action"""
info = make_user_roles('read_values', other_obj, True)
authid = info['user']['auth0_id']
obj = new_cdf_forecast(org=info['o... | 5,341,673 |
def fill_defaults(data, vals) -> dict:
"""Fill defaults if source is not present"""
for val in vals:
_name = val['name']
_type = val['type'] if 'type' in val else 'str'
_source = val['source'] if 'source' in val else _name
if _type == 'str':
_default = val['default']... | 5,341,674 |
def crossValPlot(skf,classifier,X_,y_):
"""Code adapted from:
"""
X = np.asarray(X_)
y = np.asarray(y_)
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
f,ax = plt.subplots(figsize=(10,7))
i = 0
for train, test in skf.split(X, y):
probas_ = cl... | 5,341,675 |
def delete_product(info):
"""*
"""
# get objectid
import pdb; pdb.set_trace()
params = 'where={"name": "%s"}' % info['name']
res = requests.get(CLASSES_BASE_URL + 'products', headers=RAW_HEADERS,
params=params)
if res.status_code == 200:
record = json.loads(res... | 5,341,676 |
def static_shuttle_between():
"""
Route endpoint to show real shuttle data within a certain time range at once.
Returns:
rendered website displaying all points at once.
Example:
http://127.0.0.1:5000/?start_time=2018-02-14%2015:40:00&end_time=2018-02-14%2016:02:00
"""
start_tim... | 5,341,677 |
def read_data(inargs, infiles, ref_cube=None):
"""Read data."""
clim_dict = {}
trend_dict = {}
for filenum, infile in enumerate(infiles):
cube = iris.load_cube(infile, gio.check_iris_var(inargs.var))
if ref_cube:
branch_time = None if inargs.branch_times[filenum] == 'default... | 5,341,678 |
async def create_account(*, user):
"""
Open an account for a user
Save account details in json file
"""
with open("mainbank.json", "r") as f:
users = json.load(f)
if str(user.id) in users:
return False
else:
users[str(user.id)] = {"wallet": 0, "bank": 0}
with open... | 5,341,679 |
def commonpath(paths):
"""Given a sequence of path names, returns the longest common sub-path."""
if not paths:
raise ValueError('commonpath() arg is an empty sequence')
if isinstance(paths[0], bytes):
sep = b'\\'
altsep = b'/'
curdir = b'.'
else:
sep = '\\'
... | 5,341,680 |
def test_set_container_uid_and_pod_fs_gid():
"""
Test specification of the simplest possible pod specification
"""
assert api_client.sanitize_for_serialization(make_pod(
name='test',
image='jupyter/singleuser:latest',
cmd=['jupyterhub-singleuser'],
port=8888,
run_... | 5,341,681 |
def reshape(x, shape):
""" Reshape array to new shape
This is a parallelized version of the ``np.reshape`` function with the
following limitations:
1. It assumes that the array is stored in `row-major order`_
2. It only allows for reshapings that collapse or merge dimensions like
``(1, 2... | 5,341,682 |
def update_optimizer_lr(optimizer, lr):
"""
为了动态更新learning rate, 加快训练速度
:param optimizer: torch.optim type
:param lr: learning rate
:return:
"""
for group in optimizer.param_groups:
group['lr'] = lr | 5,341,683 |
async def test_kafka_provider_metric_unavailable(aiohttp_server, loop):
"""Test the resilience of the Kafka provider when the name of a metric taken from a
Metric resource is not found.
"""
columns = ["id", "value"]
rows = [["first_id", [0.42, 1.0]]]
kafka = await aiohttp_server(make_kafka("my_t... | 5,341,684 |
def test_create_extended(setup_teardown_file):
"""Create an extended dataset."""
f = setup_teardown_file[3]
grp = f.create_group("test")
dset = grp.create_dataset('foo', (63,))
assert dset.shape == (63,)
assert dset.size == 63
dset = f.create_dataset('bar', (6, 10))
assert dset.shape =... | 5,341,685 |
def clean_json(data_type: str):
"""deletes all the data from the json corresponding to the data type.
data_type is a string corresponding to key of the dictionary "data_types",
where the names of json files for each data type are stored."""
# check if correct data type
if not data_type in json_files... | 5,341,686 |
def get_state(module_instance, incremental_state, key_postfix):
""" Helper for extracting incremental state """
if incremental_state is None:
return None
full_key = _get_full_key(module_instance, key_postfix)
return incremental_state.get(full_key, None) | 5,341,687 |
def get_lenovo_urls(from_date, to_date):
"""
Extracts URL on which the data about vulnerabilities are available.
:param from_date: start of date interval
:param to_date: end of date interval
:return: urls
"""
lenovo_url = config['vendor-cve']['lenovo_url']
len_p = LenovoMainPageParser(l... | 5,341,688 |
def PrintTabular(rows, header):
"""Prints results in LaTeX tabular format.
rows: list of rows
header: list of strings
"""
s = r'\hline ' + ' & '.join(header) + r' \\ \hline'
print(s)
for row in rows:
s = ' & '.join(row) + r' \\'
print(s)
print(r'\hline') | 5,341,689 |
def get_object_attributes(DirectoryArn=None, ObjectReference=None, ConsistencyLevel=None, SchemaFacet=None, AttributeNames=None):
"""
Retrieves attributes within a facet that are associated with an object.
See also: AWS API Documentation
Exceptions
:example: response = client.get_object_at... | 5,341,690 |
def normalize_batch_in_training(x, gamma, beta,
reduction_axes, epsilon=1e-3):
"""
Computes mean and std for batch then apply batch_normalization on batch.
# Arguments
x: Input tensor or variable.
gamma: Tensor by which to scale the input.
beta: Tens... | 5,341,691 |
def supercell_scaling_by_target_atoms(structure, min_atoms=60, max_atoms=120,
target_shape='sc', lower_search_limit=-2, upper_search_limit=2,
verbose=False):
"""
Find a the supercell scaling matrix that gives the most cubic supercell fo... | 5,341,692 |
def itemAPIEndpoint(categoryid):
"""Return page to display JSON formatted information of item."""
items = session.query(Item).filter_by(category_id=categoryid).all()
return jsonify(Items=[i.serialize for i in items]) | 5,341,693 |
def graph_response_function(
func: Callable,
start: int = 0.001,
stop: int = 1000,
number_of_observations: int = 1000000,
):
"""
Generates a graph for the passed in function in the same style as the log
based graphs in the assignment.
Args:
func: The function to ... | 5,341,694 |
def command(settings_module,
command,
bin_env=None,
pythonpath=None,
*args, **kwargs):
"""
run arbitrary django management command
"""
da = _get_django_admin(bin_env)
cmd = "{0} {1} --settings={2}".format(da, command, settings_module)
if pythonpat... | 5,341,695 |
def read_input(fpath):
"""
Read an input file, and return a list of tuples, each item
containing a single line.
Args:
fpath (str): File path of the file to read.
Returns:
list of tuples:
[ (xxx, xxx, xxx) ]
"""
with open(fpath, 'r') as f:
data = [... | 5,341,696 |
def get_parquet_lists():
"""
Load all .parquet files and get train and test splits
"""
parquet_files = [f for f in os.listdir(
Config.data_dir) if f.endswith(".parquet")]
train_files = [f for f in parquet_files if 'train' in f]
test_files = [f for f in parquet_files if 'test' in f]
... | 5,341,697 |
def test_masked_values():
"""Test specific values give expected results"""
data = np.zeros((2, 2), dtype=np.float32)
data = np.ma.masked_array(data, [[True, False], [False, False]])
input_cube = set_up_variable_cube(
data, name="snow_fraction", units="1", standard_grid_metadata="uk_ens",
)
... | 5,341,698 |
def find_level(key):
"""
Find the last 15 bits of a key, corresponding to a level.
"""
return key & LEVEL_MASK | 5,341,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.