content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_solution(board):
"""Saves the board state to the global variable 'solutions'"""
global solutions
saved_board = copy.deepcopy(board)
solutions.append(saved_board) | 5,293,300 |
def mean(samps):
"""
Find the mean point forecasts.
"""
return np.mean(samps, axis=0) | 5,293,301 |
def merge_data(path_data, filename_participants):
"""
Merge the different datasets.
:param path_data: string
:param filename_participants: string
:return: dataframe, dictionary
"""
d = {}
d_features = {}
for i in os.listdir(path_data):
path0 = os.path.join(path_data, i)
... | 5,293,302 |
def all():
"""
Returns all W2S Scenarios in [GWh/a]
:return:
"""
sc = (read("szenarien_w2s.xlsx")
.pipe(start_pipeline)
.pipe(NaNtoZero)
.pipe(format_df)
.pipe(convert_PJ_to_GWH)
)
return sc | 5,293,303 |
def test_download_cache_hit(mocker):
"""Check that download is not repeated on cache hit."""
data = b"Hello, world"
data_checksum = "4ae7c3b6ac0beff671efa8cf57386151c06e58ca53a78d83f36107316cec125f"
cached_path = cache_path(f"downloads/{data_checksum}")
# Tidy up from a previous test, if applicable... | 5,293,304 |
def validate_attach_as(attach_type):
"""
Ensure that we recognize the attach type
"""
if not attach_type in kv.ATTACH_AS_TYPES :
raise ValidationError("Attach type '{0}' is not supported."
" Valid options are: {1}".format(attach_type, kv.ATTACH_AS_TYPES)) | 5,293,305 |
def eval_two_span(
val_data: data.DataLoader,
model: transformers.PreTrainedModel,
loss_func: nn.modules.loss._Loss,
dev: torch.device=None
) -> float:
"""Evaluate a two span edge probing model.
Args:
val_data: validation dataset.
model: Edge probing mode... | 5,293,306 |
def gen_tensorflow_client_string(generated_tensor_data, model_name):
"""
Generate TensorFlow SDK in Python.
Args:
generated_tensor_data: Example is {"keys": [[1.0], [2.0]], "features": [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]]}
"""
code_template = """#!/usr/bin/env python
import reques... | 5,293,307 |
def test_createlib_library_template_is_python(emitter, store_mock, tmp_path, monkeypatch):
"""Verify that the template used to create a library is valid Python code."""
env = get_templates_environment("charmlibs")
newlib_content = env.get_template("new_library.py.j2").render(lib_id="test-lib-id")
compil... | 5,293,308 |
def wrapper(args):
""" Commandline wrapper for main()
"""
inloc = io.validate_file_for_reading(args.i) if args.i else sys.stdin
outloc = io.validate_file_for_writing(args.out) if args.out else sys.stdout
# Get filelist
filelist_df = io.load_filelist(inloc)
inloc.close()
# Get ta... | 5,293,309 |
def get_column(path, c=0, r=1, sep='\t'):
""" extracts column specified by column index
assumes that first row as a header
"""
try:
reader = csv.reader(open(path, "r"), delimiter=sep)
return [row[c] for row in reader] [r :]
except IOError:
print('list_rows: file "'+path +... | 5,293,310 |
def part2(lines):
"""
>>> part2(load_example(__file__, "24"))
19
"""
return run(lines, Part2) | 5,293,311 |
def get_example_comments():
""" returns example comments on a submission. """
user1 = 24601
user2 = 42
user_ids_to_uuids = {user1: uuid.uuid4(), user2: uuid.uuid4()}
user_ids_to_names = {user1: 'Atlassian_bot', user2: 'Cool_McJones_ASE'}
return {'tester_messages': [
{
'body_m... | 5,293,312 |
def add_md_padding(data, endian='big'):
"""Merkle-Damgard padding
Args: data(string)
Returns: data+padding(string)
"""
size = len(data) & 0x3f # len_in_bytes % 64
if size < 56:
size = 56 - size
else:
size = 120 - size
p = bytes(b'\x80') + bytes(b'\x00'*63)
p = p[:si... | 5,293,313 |
def list_fridge():
"""
List all items in the frigde.
:return: dict with all items and amounts
:rtype: dict
"""
return MOCK_FRIDGE | 5,293,314 |
def evaluate_hessian_val(A, point, direction):
"""
Returns the value of Hessian function in the given direction.
"""
hess_p = (A - np.diag((A.dot(point)).dot(point.T))).dot(direction)
return np.sum(hess_p * direction) | 5,293,315 |
def show_yolo_test_batch(image_list, label_list, cat_colors, vmin=-1.0, vmax=1.0):
"""
Show batch of images with predicted bboxes.
:param image_list: batch of images as list
:param label_list: test data generator label, as list:
Each labels batch 'list item' containing 5 lis... | 5,293,316 |
def frustrated_loop(graph, num_cycles, R=float('inf'), cycle_predicates=tuple(),
max_failed_cycles=100, planted_solution=None, seed=None):
"""Generate a frustrated-loop problem.
A generic frustrated-loop (FL) problem is a sum of Hamiltonians, each generated
from a single "good" loop, as... | 5,293,317 |
def create_sprent_table(cxn, data):
"""Create Genbank loci data table."""
data.to_sql('sprent_data', cxn, if_exists='replace', index=False)
cxn.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS
sprent_data_genus ON sprent_data (genus);
""") | 5,293,318 |
def _projection_unit_simplex(x: jnp.ndarray) -> jnp.ndarray:
"""Projection onto the unit simplex."""
s = 1.0
n_features = x.shape[0]
u = jnp.sort(x)[::-1]
cssv = jnp.cumsum(u) - s
ind = jnp.arange(n_features) + 1
cond = u - cssv / ind > 0
idx = jnp.count_nonzero(cond)
threshold = cssv[idx - 1] / idx.a... | 5,293,319 |
def channel_id_str_to_bytes(channel_id_str):
"""
Args:
channel_id_str: string representation of channel id
Returns:
bytes representation of channel id
"""
assert type(channel_id_str) in [str, bytes]
if isinstance(channel_id_str, bytes):
return channel_id_str
qid_byte... | 5,293,320 |
def truncate_sql_table(connection,table_name):
"""Runs truncate table SQL command and commits changes to database.
Args:
connection: pyodbc.connect() object, Connection to use for truncate
tableName: string, Fully qualified SQL table name (make sure this is the table you wan... | 5,293,321 |
def cli():
"""Demonstrate logging concepts."""
root_log = logging.root
root_log.setLevel(logging.DEBUG)
format_dict = collections.OrderedDict()
format_dict['name'] = 's'
format_dict['levelno'] = 's'
format_dict['levelname'] = 's'
format_dict['pathname'] = 's'
format_dict['filename']... | 5,293,322 |
def compiled(
model: tf.keras.Model,
loss=None,
metrics=None,
optimizer=None,
run_eagerly: Optional[bool] = None,
# steps_per_execution: Optional[int] = None,
) -> tf.keras.Model:
"""Mutate model in-place by compiling and return the model for convenience."""
model.compile(
loss=l... | 5,293,323 |
def list_type_versions(Type=None, TypeName=None, Arn=None, MaxResults=None, NextToken=None, DeprecatedStatus=None):
"""
Returns summary information about the versions of a type.
See also: AWS API Documentation
Exceptions
:example: response = client.list_type_versions(
Type='RESOURC... | 5,293,324 |
def load_items(connection: BaseDatabaseWrapper, **kwargs) -> None:
"""
This function provides a way to load items into memory
on server startup from the target database.
It unregisters itself to ensure that it is only run
once per startup.
:param connection: a Django BaseDatabaseWrapper object... | 5,293,325 |
def vtkVariantExtract(v, t=None):
"""
Extract the specified value type from the vtkVariant, where the type is
in the following format: 'int', 'unsigned int', etc. for numeric types,
and 'string' or 'unicode string' for strings. You can also use an
integer VTK type constant for the type. Set the ty... | 5,293,326 |
def _create_region_groups(const_regions, psvs, genome, max_dist=1000):
"""
Groups closeby const regions if they have the same CN even if there is a region with a different CN between them.
"""
psv_ix = 0
n_psvs = len(psvs)
# Key: copy_num, value: list of PloidyRegionsGroups.
groups = collec... | 5,293,327 |
def _LoadConfigModule(name: str, path: str):
"""Loads a script from external file specified by path.
Unprefixed path is looked for in the current working directory using
regular file open operation. This should work with relative config paths.
Args:
name: Name of the new module.
path: Path to the .py ... | 5,293,328 |
def _parse_icq(fileobj):
"""Parse a International Comet Quarterly (ICQ) format file."""
df = pd.read_fwf(fileobj, colspecs=list(ICQ_COLUMNS.values()),
names=ICQ_COLUMNS.keys(), header=None)
return df | 5,293,329 |
def IperfTCP(target_src, target_dst, dst, length, window=None):
"""Convenience method for starting a TCP IperfSet.
See IperfSet for more details.
Args:
target_src: A single host or list of hosts.
target_dst: A single host or list of hosts (1:1 with target_src).
dst: A single address/hostname or a li... | 5,293,330 |
def test_get_alerts(requests_mock):
"""
Given -
We want to get alerts list.
When -
Running get_alerts function.
Then -
The alerts list should be returned.
"""
api_raw_response = util_load_json('test_files/get_alerts_raw_response.json')
requests_mock.post(BASE_URL +... | 5,293,331 |
def plot_riemann(states, s, riemann_eval, t, fig=None, color='b', layout='horizontal',conserved_variables=None):
"""
Take an array of states and speeds s and plot the solution at time t.
For rarefaction waves, the corresponding entry in s should be tuple of two values,
which are the wave speeds that bou... | 5,293,332 |
def highlight_genes(axis, genes, y_posn):
"""Show gene regions with background color and a text label."""
# Rotate text in proportion to gene density
ngenes = len(genes)
text_size = ('small' if ngenes <= 6 else 'x-small')
if ngenes <= 3:
text_rot = 'horizontal'
elif ngenes <= 6:
... | 5,293,333 |
def find_in_list(list_one, list_two):
"""Find and return an element from list_one that is in list_two, or None otherwise."""
for element in list_one:
if element in list_two:
return element
return None | 5,293,334 |
def getElementById(idName: str, fileName: str) -> List[Tuple[int, str]]:
"""Returns first matching tag from an HTML/XML document"""
nonN: List[str] = []
with open(fileName, "r+") as f:
html: List[str] = f.readlines()
for line in html:
nonN.append(line.replace("\n", ""))
patt... | 5,293,335 |
def skip_after(timeout: int or float):
"""
Creates an async pool with an associated timeout, but
without raising a TooSlowError exception. The pool
is simply cancelled and code execution moves on
"""
assert timeout > 0, "The timeout must be greater than 0"
mgr = TaskManager(timeout,... | 5,293,336 |
def read_peak_correlations(file_name):
"""
Read in the custom peak correlation Excel file provided by JAX.
"""
df = pd.DataFrame(pd.read_excel(file_name))
tab = Table.from_pandas(df) #read(file_name, format="ascii.csv")
# tab.rename_column('\ufeffMm_chr', 'Mm_chr')
new_tab = Table(names=('... | 5,293,337 |
def load_pickle(fname):
"""Loads a pickle file to memory.
Parameters
----------
fname : str
File name + path.
Returns
-------
dict/list
Data structure of the input file.
"""
assert fname, 'Must input a valid file name.'
if sys.version_info[0] == 2:
retu... | 5,293,338 |
def check_worker_ticker_interval(log_path, min_interval):
"""
check the time interval between dm-worker updates when the queue is empty
log_path: dm-worker-log path
min_interval: min interval
"""
logs = []
with open(log_path, "r") as f:
for line in f.readlines()[::-1]:
i... | 5,293,339 |
def sample(model, block_size, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike an... | 5,293,340 |
def explore_result_coverage_detail():
"""Get coverage detail info
Get coverage detail info loading from disk
:return: a list, each element is dict map in list, if coverage file not exist,
will return [],for example:
[{
"fileName": "1.jpg",
"sampleNum": 5,
... | 5,293,341 |
def gradient_dx(fx: tf.Tensor) -> tf.Tensor:
"""
Function to calculate gradients on x-axis of a 3D tensor using central finite difference.
It moves the tensor along axis 1 to calculate the approximate gradient, the x axis,
dx[i] = (x[i+1] - x[i-1]) / 2
:param fx: shape = (batch, m_dim1, m_dim2, m_d... | 5,293,342 |
def docs():
"""
Build docs with sphinx
"""
if os.path.exists( "/usr/local/bin/sphinx-build" ) or os.path.exists( "/usr/bin/sphinx-build" ):
print( "[ INFO ] Build documentation " )
DOCS_BUILD = "sphinx-build -b html -d {tmp} {source} {out}"
DOCS_TMP = os.path.join( TMP_PATH, "doc... | 5,293,343 |
def test_absent():
"""
Test to ensure key absent from redis.
"""
name = "key_in_redis"
ret = {"name": name, "changes": {}, "result": True, "comment": ""}
mock = MagicMock(side_effect=[False, True, True])
mock_t = MagicMock(return_value=False)
with patch.dict(redismod.__salt__, {"redis.... | 5,293,344 |
def form_edit_permissions(formId):
"""Set form permissions of a particular user to an array.
POST request, with body: (either userId or email is required.)
{
"userId": "cm:cognitoUserPool:.....",
"email": "a@b.com",
"permissions": ["Responses_Edit", "Responses_View", ""] or string. -- should have all ... | 5,293,345 |
def _real_freq_filter(rfft_signal, filters):
"""Helper function to apply a full filterbank to a rfft signal
"""
nr = rfft_signal.shape[0]
subbands = filters[:, :nr] * rfft_signal
return subbands | 5,293,346 |
def _strip_extension(name, ext):
"""
Remove trailing extension from name.
"""
ext_len = len(ext)
if name[-ext_len:] == ext:
name = name[:-ext_len]
return name | 5,293,347 |
def node_clique_number(G,nodes=None,cliques=None):
""" Returns the size of the largest maximal clique containing
each given node.
Returns a single or list depending on input nodes.
Optional list of cliques can be input if already computed.
"""
if cliques is None:
if nodes is not None:
... | 5,293,348 |
def usage(fd=stderr):
"""
Display usage information.
"""
fd.write(__doc__.strip() + "\n")
fd.flush()
return | 5,293,349 |
def start(server_url, key, mode, game_id, bot):
"""Start a game with all the required parameters.
Args:
server_url (str): The server's URL.
key (str): A valid API key.
mode (str): The game mode, "training" or "competition".
game_id (str): a valid game id, when playing in competi... | 5,293,350 |
def xonsh_execer(monkeypatch):
"""Initiate the Execer with a mocked nop `load_builtins`"""
execer = Execer(unload=False)
monkeypatch.setattr(XSH, "execer", execer)
yield execer | 5,293,351 |
def test_create_issue_in_creation(mock_category, mock_send, mock_exists):
# def test_create_issue_in_creation(mock_send, mock_exists):
"""Do nothing if not created but issue during creation."""
pnf = Pnf()
vsp = Vsp()
vendor = Vendor()
vsp._identifier = "1232"
vsp.create_csar = MagicMock(return_... | 5,293,352 |
def str_to_list(s):
# type: (str) -> List[str]
"""Convert string to list."""
if isinstance(s, str):
return s.split(',')
return s | 5,293,353 |
def get_online_seed_from_cam_sal_seg(cam: torch.Tensor, sal: torch.Tensor,
seg_prob: torch.Tensor, cls_in_label: torch.Tensor,
cam_thresh: float, sal_thresh: float, ignore_label: int) -> torch.Tensor:
"""Get online seed from CAM, saliency and... | 5,293,354 |
def check_parameter(**kwargs):
"""Check dtype of the function's parameters.
Parameters
----------
kwargs : Type or Tuple[Type]
Map of each parameter with its expected dtype.
Returns
-------
_ : bool
Assert if the array is well formatted.
"""
# get the frame and the... | 5,293,355 |
def part1(data):
"""
>>> part1(read_input())
192
"""
return sum(is_valid(passport) for passport in data) | 5,293,356 |
def minimize(func, x0, args=(), *, method, tol=None, options=None):
"""Minimization of scalar function of one or more variables.
This API for this function matches SciPy with some minor deviations:
- Gradients of ``fun`` are calculated automatically using MindSpore's autodiff
support when required.
... | 5,293,357 |
def get_network(name, batch_size):
"""Get the symbol definition and random weight of a network"""
dtype = 'float32'
input_shape = (batch_size, 3, 224, 224)
output_shape = (batch_size, 1000)
if "resnet" in name:
n_layer = int(name.split("-")[1])
mod, params = relay.testing.resnet.get... | 5,293,358 |
def web_template() -> Callable[[Request, str], _TemplateResponse]:
"""Create a dependency which may be injected into a FastAPI app."""
def _template(request: Request, page: str, context: Dict = {}) -> _TemplateResponse:
"""Create a template from a request"""
context["request"] = request
... | 5,293,359 |
def core_number(G):
"""Returns the core number for each vertex.
A k-core is a maximal subgraph that contains nodes of degree k or more.
The core number of a node is the largest value k of a k-core containing
that node.
Parameters
----------
G : NetworkX graph
A graph or directed gr... | 5,293,360 |
def write_config(csv_filename, output, reflow_workflows_path, workflow):
"""Write config.json to path with workflow and samples files"""
rf = os.path.join(reflow_workflows_path, workflow)
config = {"program": rf, "runs_file": os.path.basename(csv_filename)}
json_filename = os.path.join(output, CONFIG_JS... | 5,293,361 |
def create_meeting(
client,
name: str,
description: str = None,
title: str = None,
duration: int = 60000, # duration in mins ~6 weeks
):
"""Create a Zoom Meeting."""
body = {
"topic": title if title else f"Situation Room for {name}",
"agenda": description if description else... | 5,293,362 |
def hours(datetime):
"""
Returns the hours component for the given datetime value, in local time.
"""
return datetime.hour() | 5,293,363 |
def create_work_packages(
inputs: List[Tuple[str, bool]],
work_package_size: int,
number_of_workers: int,
already_processed: List[str] = []
) -> Tuple[List[List[str]], List[str]]:
"""Create the work packages for the worker processes.
Args:
inputs (List[Tuple[str, bool]])... | 5,293,364 |
def compute_checksum(filename):
"""Computes the MD5 checksum of the contents of a file.
filename: string
"""
cmd = 'md5sum ' + filename
return pipe(cmd) | 5,293,365 |
def clean_text(
raw_text,
fix_unicode=True,
to_ascii=False,
lower=True,
no_line_breaks=True,
no_urls=True,
no_emails=True,
no_phone_numbers=True,
no_numbers=False,
no_digits=False,
no_currency_symbols=True,
no_punct=False,
... | 5,293,366 |
def read(path):
"""Read an injection .txt file into .content."""
reset()
g[CONTENT] = open(path, encoding="utf-8").read().splitlines()
scan() | 5,293,367 |
def _get_s3_provider():
"""
Gets S3 Config Provider
:return: Instance of S3ConfigProvider
:rtype: S3ConfigProvider
"""
return S3ConfigProvider(
bucket=CONFIG_PROVIDERS['s3']['bucket'],
config_base=CONFIG_PROVIDERS['s3']['base']
) | 5,293,368 |
def compile_html(
input_path,
html_path=None,
*,
props=None,
precision=None,
title=None,
div_id=None,
inline_js=None,
svelte_to_js=None,
js_path=None,
js_name=None,
js_lint=None
):
"""Compile Svelte or JavaScript to HTML.
Arguments:
input_path: path to ... | 5,293,369 |
def is_path_fully_cached(path):
"""Returns true if all the bytes of the path are cached, false otherwise"""
rc, stdout, stderr = exec_process("hdfs cacheadmin -listDirectives -stats -path %s" % path)
assert rc == 0
caching_stats = stdout.strip("\n").split("\n")[-1].split()
# Compare BYTES_NEEDED and BYTES_CAC... | 5,293,370 |
def run_gr1x_slugs_comparison(slugsin_file):
"""Check that both solvers return same winning set."""
print('compare for: {f}'.format(f=slugsin_file))
slugs_winning_set_file = 'winning_set_bdd.txt'
slugs_strategy_file = 'slugs_strategy.txt'
gr1x_strategy_file = 'gr1x_strategy.txt'
utils.snapshot_v... | 5,293,371 |
def find_camera_tracking_pts_topics():
"""
Returns list of all tracking_pts topics associated with a camera
"""
topic_list = find_topics_w_ending('tracking_pts')
topic_list = [topic for topic in topic_list if 'camera' in topic.split('/')]
return topic_list | 5,293,372 |
def get_batch_size(dataset: tf.data.Dataset,
optimization_batch_size: int = BATCH_AUTO_TUNE) -> int:
"""Computes optimization batch size for processing steps in batches.
Args:
dataset: episodes or steps dataset.
optimization_batch_size: user-provided hint for the batch size.
Returns:
... | 5,293,373 |
def get_uuid_from_url(url: str) -> str:
""" Strip the URL from the string. Returns the UUID. """
return url.split('/')[-1] | 5,293,374 |
def _generate_cli_args(n):
"""Generate n args."""
random.seed(42)
yielded = set()
for _ in range(n):
to_yield = " ".join(
[
"--level " + str(random.choice([1, 2, 3])),
random.choice(["", "--subpackages"]),
random.choice(["", "--modul... | 5,293,375 |
def texFrac(frac):
""" Tex render for Fractions"""
return ["\\frac{" , str(frac._num) , "}{" , str(frac._denom) , "}"] | 5,293,376 |
def build_plot_video(results, unique_id, json_data_dict):
"""Builds and writes a combined video of the plot of the knee angle and the angle video
Args:
results: dictionary of the downloaded files {'file_name': file}
unique_id: the uuid that was given to the video
json_data_dict: dictiona... | 5,293,377 |
def repeated_hindsight_gumbel_estimation(
universe, probabilities, values, num_samples, normalize, repetitions):
"""Uses Hindsight Gumbel Estimation multiple times with different Gumbels."""
# Use the same samples for each repetition!
results = ppswor_samples(universe, probabilities, num_samples)
all_sampl... | 5,293,378 |
def get_progress_string(tag, epoch, minibatch, nbatches, cost, time,
blockchar=u'\u2588'):
"""
Generate a progress bar string.
Arguments:
tag (string): Label to print before the bar (i.e. Train, Valid, Test )
epoch (int): current epoch to display
minibatch (i... | 5,293,379 |
def init_logging_config():
"""
Initiates the logging configuration
"""
logging.basicConfig(level=logging.INFO)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')
console.setFormatter(formatter)
... | 5,293,380 |
def calcRingCentroidNormal(atomCoords):
""" extract aromatic ring geometric info from a numpy array """
a1 = atomCoords[0]
a2 = atomCoords[1]
a3 = atomCoords[2]
centroid = averageCoords(atomCoords)
plane = calcPlane(a1, a2, a3)
v1 = vector(centroid, a1)
v2 = vector(centroid, a2)
nor... | 5,293,381 |
def flip_horizontal(original: Image) -> Image:
"""Written by: Cameron Legree
Student No. 101153496
Returns a copy of an image flipped along a horiontal line centered in the
image. orginal_image must be loaded prior to passing it through the
function.
>>>flip_horizontal(miss_sullivan.png... | 5,293,382 |
def span_to_label(tokens: List[str],
labeled_spans: dict,
scheme: Optional[str] = 'BIO') -> List[str]:
"""
Convert spans to label
:param tokens: a list of tokens
:param labeled_spans: a list of tuples (start_idx, end_idx, label)
:param scheme: labeling scheme, in ... | 5,293,383 |
def test_attribute_9():
"""serialization of linefeed in attribute value"""
_run_xml(
source_xml = SOURCE_XML,
transform_xml = """<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<result>
<!-- linefeed must ... | 5,293,384 |
def expand_markup(abbr: str, config: Config) -> str:
"""
Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that
produces structured output like HTML) and outputs it according to options
provided in config
"""
return stringify_markup(markup_abbreviation(abbr, config), config) | 5,293,385 |
def plot_episodes(data_it, nepisode, fname_tmpl, **kwargs):
"""Plots the episode.
Args:
data_it: Episode iterators.
nepisode: Int. Number of episodes to plot.
fname_fmpl: String. Output file name template.
"""
for i, e in zip(range(nepisode), data_it):
plot_one_episode(e, fname_tmpl.format(i), ... | 5,293,386 |
def build_args():
"""
Constructs command line arguments for the vulndb tool
"""
parser = argparse.ArgumentParser(
description="Fully open-source security audit for project dependencies based on known vulnerabilities and advisories."
)
parser.add_argument(
"--no-banner",
a... | 5,293,387 |
def test_moths():
"""Test module moths.py by downloading
moths.csv and testing shape of
extracted data has 41 rows and 4 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = moths(test_path)
try:
assert x_train.shape == (41, 4)
except:
shutil.rmtree(test_path)
raise() | 5,293,388 |
def withinStdDevRange(a, b):
"""Returns the percent of samples within the std deviation range a, b"""
if b < a:
return 0;
if a < 0:
if b < 0:
return (withinStdDev(-a) - withinStdDev(-b)) / 2;
else:
return (withinStdDev(-a) + withinStdDev(b)) / 2;
else:
return (withinStdDev(b) - with... | 5,293,389 |
def commit_email():
"""Receive web hook from github and generate email."""
# Only look at push events. Ignore the rest.
event = flask.request.headers['x-github-event']
logging.info('Received "{0}" event from github.'.format(event))
if event != 'push':
logging.info('Skipping "{0}" event.'.fo... | 5,293,390 |
def unimodal_converter(data):
"""
Returns ground truth labels when data is split modally to text and image
data: dataframe object
"""
for column in ["string", "numeric"]:
unimodal_image, unimodal_text = [], []
for i in range(len(data)):
temp_val = data.loc... | 5,293,391 |
def convert_ids_to_tokens(inv_vocab, ids):
"""Converts a sequence of ids into tokens using the vocab."""
output = []
for item in ids:
output.append(inv_vocab[item])
return output | 5,293,392 |
def print_prepr (* args) :
"""Print `portable_repr` of all `args`"""
print (* (portable_repr (a) for a in args)) | 5,293,393 |
def get_app_template_dirs(dirname, app_label=None, model_name=None):
"""
Return an iterable of paths of directories to load app templates from.
dirname is the name of the subdirectory containing templates inside
installed applications.
Derived from django.template.utils.get_app_template_dirs
H... | 5,293,394 |
async def remove_device(
ws_client: aiohttp.ClientWebSocketResponse, device_id: str, config_entry_id: str
) -> bool:
"""Remove config entry from a device."""
await ws_client.send_json(
{
"id": 1,
"type": "config/device_registry/remove_config_entry",
"config_entry_... | 5,293,395 |
def build_senator_details(details):
"""Build the test data for a senator."""
data = build_us_details(details)
data['terms'][-1]['state_rank'] = details[5]
data['terms'][-1]['class'] = details[6]
data['terms'][-1]['url'] = details[7]
data['terms'][-1]['phone'] = details[8]
return data | 5,293,396 |
def normalize(y: ndarray, max_value: float) -> ndarray:
"""
Performs normalization of given values
:param y: ndarray - numpy array of histogram values derived from TCSPC method
:param max_value: float - maximal value in given data
:return: ndarray - numpy array of normalized histogram values derived... | 5,293,397 |
def load_obj(path):
"""
return the python object saved in the given path
:param path: the path to be loaded
:return:
"""
logger = logging.getLogger("load_obj")
retry_count = 3
while retry_count > 0:
try:
with open(path, 'rb') as f:
return pickle.load(... | 5,293,398 |
def start_purpled():
"""
Helper for starting the "purpled" backend
"""
# check if purpled exists in path
exe = shutil.which("purpled", path=os.getcwd())
if exe is None:
exe = shutil.which("purpled")
if exe is None:
# does not exist, stop here
return
###########
... | 5,293,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.