content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mk_sd_graph(pvalmat, thresh=0.05):
"""
Make a graph with edges as signifcant differences between treatments.
"""
digraph = DiGraph()
for idx in range(len(pvalmat)):
digraph.add_node(idx)
for idx_a, idx_b, b_bigger, p_val in iter_all_pairs_cmp(pvalmat):
if p_val > thresh:
... | 38,700 |
def body2hor(body_coords, theta, phi, psi):
"""Transforms the vector coordinates in body frame of reference to local
horizon frame of reference.
Parameters
----------
body_coords : array_like
3 dimensional vector with (x,y,z) coordinates in body axes.
theta : float
Pitc... | 38,701 |
def plotme_single_f1(np_mat, ynames, title):
"""
np_mat - N rows by C columns, all values to plot (real valued)
ynames - C items, strings naming the C columns of np_mats
title - 1 title for the plot
"""
# https://stackoverflow.com/questions/8230638/parallel-coordinates-plot-in-matplotlib
import matp... | 38,702 |
def ccompile(source_file_path):
"""Compiles C source code into object code."""
command = "cc -c {source_code} -o {object_code}".format(
source_code=source_file_path,
object_code=__source_to_object_name(source_file_path))
execute(command) | 38,703 |
def negloglikelihoodZTNB(args, x):
"""Negative log likelihood for zero truncated negative binomial."""
a, m = args
denom = 1 - NegBinom(a, m).pmf(0)
return len(x) * np.log(denom) + negloglikelihoodNB(args, x) | 38,704 |
def combine(m1, m2):
"""
Returns transform that combines two other transforms.
"""
return np.dot(m1, m2) | 38,705 |
def _acg_bound(nsim, k1, k2, lam, mtop = 1000):
# John T Kent, Asaad M Ganeiber, and Kanti V Mardia.
# A new unified approach forthe simulation of a wide class of directional distributions.
# Journal of Computational andGraphical Statistics, 27(2):291–301, 2018.
"""
Sampling appro... | 38,706 |
def anonymise_eeg(
original_file: str,
destination_file: str,
field_name: str = '',
field_surname: str = '',
field_birthdate: str = '',
field_sex: str = '',
field_folder: str = '',
field_centre: str = '',
field_comment: str = ''
):
"""Anonymise an .eeg file.
Args:
or... | 38,707 |
def melspecgrams_to_specgrams(logmelmag2 = None, mel_p = None, mel_downscale=1):
"""Converts melspecgrams to specgrams.
Args:
melspecgrams: Tensor of log magnitudes and instantaneous frequencies,
shape [freq, time], mel scaling of frequencies.
Returns:
specgrams: Tensor of log magnitudes... | 38,708 |
def ligandScore(ligand, genes):
"""calculate ligand score for given ligand and gene set"""
from scipy.stats.mstats import gmean
import numpy as np
if ligand.ligand_type == "peptide" and isinstance(ligand.preprogene, str):
# check if multiple genes needs to be accounted for
if isinstanc... | 38,709 |
def eval(x):
"""Evaluates the value of a variable.
# Arguments
x: A variable.
# Returns
A Numpy array.
# Examples
```python
>>> from keras import backend as K
>>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
>>> K.eval(kvar)
array(... | 38,710 |
def triple_in_shape(expr: ShExJ.shapeExpr, label: ShExJ.tripleExprLabel, cntxt: Context) \
-> Optional[ShExJ.tripleExpr]:
""" Search for the label in a shape expression """
te = None
if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)):
for expr2 in expr.shapeExprs:
te = triple_i... | 38,711 |
def test_reusability_query():
"""Test that limiting to open reusability works."""
reader = EuropeanaSearchReader(os.environ['EUROPEANA_API_KEY'], 'Python', reusability='open')
count = 0
for record in reader:
assert record.id
for right in record.rights:
assert right in ['http:... | 38,712 |
def poly_learning_rate(base_lr, curr_iter, max_iter, power=0.9):
"""poly learning rate policy"""
lr = base_lr * (1 - float(curr_iter) / max_iter) ** power
return lr | 38,713 |
def parent_path(xpath):
"""
Removes the last element in an xpath, effectively yielding the xpath to the parent element
:param xpath: An xpath with at least one '/'
"""
return xpath[:xpath.rfind('/')] | 38,714 |
def change_project_description(project_id):
"""For backwards compatibility: Change the description of a project."""
description = read_request()
assert isinstance(description, (str,))
orig = get_project(project_id)
orig.description = description
orig.lastUpdated = datetime.datetime.utcnow()
... | 38,715 |
def run_test_reset():
""" Tests the reset method of the Line class. """
m1t.run_test_reset() # This runs OUR tests.
# ------------------------------------------------------------------
# One ADDITIONAL test (or set of tests).
# ------------------------------------------------------------------
... | 38,716 |
def run_all(examples_main_path):
"""
Helper function to run all the test cases
:arg: examples_main_path: the path to main examples directory
"""
# test cases to run
test_cases = [TestExample1,
TestExample2,
TestExample3,
TestExample4,
... | 38,717 |
def delete_user(user_info: dict):
"""
Delete the cognito user
"""
user_pool_id = ssm.get_parameter(Name=f"/ecommerce/{ENVIRONMENT}/users/user-pool/id")["Parameter"]["Value"]
cognito = boto3.client("cognito-idp")
# Delete the user
cognito.admin_delete_user(
UserPoolId=user_pool_id,
... | 38,718 |
def get_queue(queue):
"""
:param queue: Queue Name or Queue ID or Queue Redis Key or Queue Instance
:return: Queue instance
"""
if isinstance(queue, Queue):
return queue
if isinstance(queue, str):
if queue.startswith(Queue.redis_queue_namespace_prefix):
return Queue.... | 38,719 |
def test_ij2bl():
"""Test ij2bl function"""
# test < 256 antennas
i = 1
j = 2
assert aipy_extracts.ij2bl(i, j) == 515
# test > 256 antennas
i = 2
j = 257
assert aipy_extracts.ij2bl(i, j) == 71938
# test case where i > j
i = 257
j = 2
assert aipy_extracts.ij2bl(i, j)... | 38,720 |
def ptttl_to_samples(ptttl_data, amplitude=0.5, wavetype=SINE_WAVE):
"""
Convert a PTTTLData object to a list of audio samples.
:param PTTTLData ptttl_data: PTTTL/RTTTL source text
:param float amplitude: Output signal amplitude, between 0.0 and 1.0.
:param int wavetype: Waveform type for output si... | 38,721 |
def read_output_ascii(
path: Union[Path, str]
) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]:
"""Read an output file (raw ASCII format)
Args:
path (str): path to the file
Return:
list: The contents of the output file as a :py:class:`list` containing
four... | 38,722 |
def AliasPrefix(funcname):
"""Return the prefix of the function the named function is an alias of."""
alias = __aliases[funcname][0]
return alias.prefix | 38,723 |
def run_command(*cmd_args, **kargs):
"""
Shell runner helper
Work as subproccess.run except check is set to true by default and
stdout is not printed unless the logging level is DEBUG
"""
logging.debug("Run command: " + " ".join(map(str, cmd_args)))
if not dry_run:
if "check" not in ... | 38,724 |
def test_md021_bad_multiple_spacing_left():
"""
Test to make sure this rule does trigger with a document that
contains an Atx Closed Heading with multiples spaces at the start.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
"scan",
"test/resources/rules/md0... | 38,725 |
def connect(
sender: QWidget,
signal: str,
receiver: QObject,
slot: str,
caller: Optional[FormDBWidget] = None,
) -> Optional[Tuple[pyqtSignal, Callable]]:
"""Connect signal to slot for QSA."""
# Parameters example:
# caller: <clientes.FormInternalObj object at 0x7f78b5c230f0>
# sen... | 38,726 |
def get_detection_input(batch_size=1):
"""
Sample input for detection models, usable for tracing or testing
"""
return (
torch.rand(batch_size, 3, 224, 224),
torch.full((batch_size,), 0).long(),
torch.Tensor([1, 1, 200, 200]).repeat((batch_size, 1)),
torch... | 38,727 |
def build_tables(ch_groups, buffer_size, init_obj=None):
""" build tables and associated I/O info for the channel groups.
Parameters
----------
ch_groups : dict
buffer_size : int
init_obj : object with initialize_lh5_table() function
Returns
-------
ch_to_tbls : dict or Table
... | 38,728 |
def segmentspan(revlog, revs):
"""Get the byte span of a segment of revisions
revs is a sorted array of revision numbers
>>> revlog = _testrevlog([
... 5, #0
... 10, #1
... 12, #2
... 12, #3 (empty)
... 17, #4
... ])
>>> segmentspan(revlog, [0, 1, 2, 3, 4])
17
>>... | 38,729 |
def is_stateful(change, stateful_resources):
""" Boolean check if current change references a stateful resource """
return change['ResourceType'] in stateful_resources | 38,730 |
def get_osusername():
"""Get the username of the current process."""
if pwd is None:
raise OSError("get_username cannot be called on Windows")
return pwd.getpwuid(os.getuid())[0] | 38,731 |
def get_session_from_webdriver(driver: WebDriver, registry: Registry) -> RedisSession:
"""Extract session cookie from a Selenium driver and fetch a matching pyramid_redis_sesssion data.
Example::
def test_newsletter_referral(dbsession, web_server, browser, init):
'''Referral is tracker for... | 38,732 |
def parse_argv():
""" Retrieve fields from sys.argv """
if len(sys.argv) == 2:
main_file = sys.argv[1]
with open(main_file) as main_file_handle:
main_code = main_file_handle.read()
return sys.argv[0], {main_file: main_code}, main_file, main_code, None, None, None, None
# ... | 38,733 |
def test_role_delete_not_found(api_client, create_test_users):
"""Test role deletion no longer exists."""
group = Group.objects.get(name="OFA Admin")
api_client.login(username="test__ofa_admin", password="test_password")
response = api_client.delete(f"/v1/roles/{group.id}/")
assert response.status_c... | 38,734 |
def initialize(args):
"""Initializes a list of repositories from a specified repos.yaml,
and returns the commands to add to your crontab.
Sets up local file storage for tracking repositories.
"""
tracked_repos = [
_create_single_tracked_repo(
repo=repo['repo'],
cront... | 38,735 |
def paper() -> Tuple[str]:
"""
Use my paper figure style.
Returns
-------
Tuple[str]
Colors in the color palette.
"""
sns.set_context("paper")
style = { "axes.spines.bottom": True,
"axes.spines.left": True,
"axes.spines.right": False,
"a... | 38,736 |
def _get_diff_text(old, new):
"""
Returns the diff of two text blobs.
"""
diff = difflib.unified_diff(old.splitlines(1), new.splitlines(1))
return "".join([x.replace("\r", "") for x in diff]) | 38,737 |
def update_dragged_position():
"""Update the position of dragged block to put it under the cursor."""
global blocks
for block in blocks:
if block.clicked: #Only for clicked blocks
pos = pygame.mouse.get_pos()
block.x,block.y = pos[0] - block.width//2, pos[1] - block.height//2... | 38,738 |
def alma_query(tab, make_figure=True, xsize=5, nlabel=3, min_size=4, cmap='jet_r', rerun_query=True, query_kwargs={'public':False, 'science':False, 'get_html_version':True}):
"""
Query ALMA archive around the HST data
"""
import time
import urllib
import numpy as np
import matplotlib.pyplot ... | 38,739 |
def check_coordinate_systems_identical(lcs_a, lcs_b, abs_tol=1e-9):
"""Check if 2 local coordinate systems are identical within a tolerance.
Parameters
----------
lcs_a :
First local coordinate system
lcs_b :
Second local coordinate system
abs_tol :
Absolute tolerance (D... | 38,740 |
def _make_train_sets(psms, test_idx):
"""
Parameters
----------
psms : list of PsmDataset
The PsmDataset to get a subset of.
test_idx : list of list of numpy.ndarray
The indicies of the test sets
Yields
------
PsmDataset
The training set.
"""
train_set = ... | 38,741 |
def GetStatus(operation):
"""Returns string status for given operation.
Args:
operation: A messages.Operation instance.
Returns:
The status of the operation in string form.
"""
if not operation.done:
return Status.PENDING.name
elif operation.error:
return Status.ERROR.name
else:
retu... | 38,742 |
def add_arch_migrate(migrators: MutableSequence[Migrator], gx: nx.DiGraph) -> None:
"""Adds rebuild migrators.
Parameters
----------
migrators : list of Migrator
The list of migrators to run.
"""
print(
"========================================"
"=======================... | 38,743 |
def get_args(args):
"""Get the script arguments."""
description = "tvtid - Feteches the tv schedule from client.dk"
arg = argparse.ArgumentParser(description=description)
arg.add_argument(
"-d",
"--date",
metavar="datetime",
type=lambda s: datetime.strptime(s, "%Y-%m-%d"... | 38,744 |
def ft2m(ft):
"""
Converts feet to meters.
"""
if ft == None:
return None
return ft * 0.3048 | 38,745 |
def show_colors(*, nhues=17, minsat=10, unknown='User', include=None, ignore=None):
"""
Generate tables of the registered color names. Adapted from
`this example <https://matplotlib.org/examples/color/named_colors.html>`__.
Parameters
----------
nhues : int, optional
The number of break... | 38,746 |
def get_all_lights(scene, include_light_filters=True):
"""Return a list of all lights in the scene, including
mesh lights
Args:
scene (byp.types.Scene) - scene file to look for lights
include_light_filters (bool) - whether or not light filters should be included in the list
Returns:
(list)... | 38,747 |
def test_mother_replace_after_specified_time(set_up_mother):
"""
Should check if mother should be replaced
"""
# Given:
bee_mother = BeeMother.objects.all()
# When:
for mother in bee_mother:
BeeMotherService.set_mother_age(mother)
BeeMotherService.set_mother_active(mother)
... | 38,748 |
def captured_templates(app):
"""Determines which templates were rendered and what variables were passed to the template"""
recorded = []
def record(sender, template, context, **extra):
recorded.append((template, context))
template_rendered.connect(record, app)
try:
yield recorded
... | 38,749 |
def get_df(path):
"""Load raw dataframe from JSON data."""
with open(path) as reader:
df = pd.DataFrame(load(reader))
df['rate'] = 1e3 / df['ms_per_record']
return df | 38,750 |
def _format_distribution_details(details, color=False):
"""Format distribution details for printing later."""
def _y_v(value):
"""Print value in distribution details."""
if color:
return colored.yellow(value)
else:
return value
# Maps keys in configuration to... | 38,751 |
def test_2d_unit_spacing():
"""Test write_netcdf with a 2D grid with unit spacing."""
(x, y) = np.meshgrid(np.arange(5.), np.arange(4.))
spacing = _get_raster_spacing((y, x))
assert_equal(spacing, 1.) | 38,752 |
def remove_repository(repo_name: str):
"""
Summary:
deletes a repository
Parameters:
repo_name (str): the repository name
Returns:
None
"""
repository = get_repo(repo_name)
delete_repo(repository) | 38,753 |
async def async_get_relation_id(application_name, remote_application_name,
model_name=None,
remote_interface_name=None):
"""
Get relation id of relation from model.
:param model_name: Name of model to operate on
:type model_name: str
:... | 38,754 |
def main():
"""Read input and print output"""
queens = []
for row in range(8):
for col, square in enumerate(input()):
if square == '*':
queens.append((row, col))
if len(queens) != 8:
print("invalid")
return
for i in queens:
for j in quee... | 38,755 |
def get_timeseries_references(session_id, search_value, length, offset, column, order):
"""
Gets a filtered list of timeseries references.
This function will generate a filtered list of timeseries references belonging to a session
given a search value. The length, offset, and order of the list can also... | 38,756 |
def get_current_version():
"""Get current version"""
base_dir = os.path.abspath(os.path.dirname(__file__))
version_file = os.path.join(base_dir, "evaluations", "__init__.py")
with open(version_file, 'r') as opened_file:
return re.search(
r'^__version__ = [\'"]([^\'"]*)[\'"]', opened_... | 38,757 |
def runTestQ4():
"""
Exhibits the powers of Q4.
"""
matrixA = generateEvilMatrix(5)
print("Q4: Now entering the matrix:")
printEvilMatrix(matrixA)
print() | 38,758 |
def twos(l):
"""
>>> list(twos(['a', 'b'])) == [('a', 'b')]
True
>>> list(twos(['a'])) == []
True
>>> list(twos(['a', 'b', 'c', 'd'])) == [('a', 'b'), ('c', 'd')]
True
>>> list(twos(['a', 'b', 'c', 'd', 'e'])) == [('a', 'b'), ('c', 'd')]
True
"""
it = iter(l)
while True:
... | 38,759 |
def check_argc(required_argc):
"""
Bail with a message unless the number of command line arguments (including
the name of this script) is equal to required_arc.
"""
if len(sys.argv) != required_argc:
print("Incorrect number of arguments passed to command line.")
print("Required numbe... | 38,760 |
def mxprv_from_bip39_mnemonic(
mnemonic: Mnemonic, passphrase: str = "", network: str = "mainnet"
) -> bytes:
"""Return BIP32 root master extended private key from BIP39 mnemonic."""
seed = bip39.seed_from_mnemonic(mnemonic, passphrase)
version = NETWORKS[network].bip32_prv
return rootxprv_from_see... | 38,761 |
def setup_ebook_home(args, conf):
"""
Setup user's ebook home, config being set with this order of precedence:
- CLI params
- ENV vars
- saved values in ogre config
- automatically created in $HOME
"""
ebook_home = None
# 1) load CLI parameters (if available)
try:
eb... | 38,762 |
def translate_text(
text: str, source_language: str, target_language: str
) -> str:
"""Translates text into the target language.
This method uses ISO 639-1 compliant language codes to specify languages.
To learn more about ISO 639-1, see:
https://www.w3schools.com/tags/ref_language_codes.as... | 38,763 |
def preprocess_log(file):
"""
preprocess_log() -> pyplot diagram
This method will return a 'running log' of the above 'preprocess' method
"""
with open("reports/preprocess.txt", "w") as preprocess_file:
print("+----- PREPROCESSING LOGGER -----+", file=preprocess_file)
print(
... | 38,764 |
def evt_cache_staged_t(ticket):
""" create event EvtCacheStaged from ticket ticket
"""
fc_keys = ['bfid' ]
ev = _get_proto(ticket, fc_keys = fc_keys)
ev['cache']['en'] = _set_cache_en(ticket)
return EvtCacheStaged(ev) | 38,765 |
def _ProtobufDefinitionToFields(message_class):
"""Flattens the fields in a protocol buffer definition.
For example, given the following definition:
message Point {
required int32 x = 1;
required int32 y = 2;
optional string label = 3;
}
message Polyline {
repeated Point point... | 38,766 |
def _get_setup_keywords(pkg_data: dict, keywords: dict) -> Dict:
"""Gather all setuptools.setup() keyword args."""
options_keywords = dict(
packages=list(pkg_data),
package_data={pkg: list(files)
for pkg, files in pkg_data.items()},
)
keywords['options'].update(opt... | 38,767 |
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5]... | 38,768 |
def setplot(plotdata=None):
#--------------------------
"""
Specify what is to be plotted at each frame.
Input: plotdata, an instance of pyclaw.plotters.data.ClawPlotData.
Output: a modified version of plotdata.
"""
from clawpack.visclaw import colormaps, geoplot
from numpy im... | 38,769 |
def load_spider_tables(filenames: str) -> Dict[str, Schema]:
"""Loads database schemas from the specified filenames."""
examples = {}
for filename in filenames.split(","):
with open(filename) as training_file:
examples.update(process_dbs(json.load(training_file)))
return examples | 38,770 |
def extract_float_arrays(blockids: str, data: bytes) -> Dict[str, array]:
"""Extracts float arrays from raw scope, background trace, and recorder
zoom binary data (block ids a, A, b, B, x, y, Y in the DLC pro 'Scope,
Lock, and Recorder Binary Data' format).
Args:
blockids: String of requested b... | 38,771 |
def rotate_image(path):
"""Rotate the image from path and return wx.Image."""
img = Image.open(path)
try:
exif = img._getexif()
if exif[ORIENTATION_TAG] == 3:
img = img.rotate(180, expand=True)
elif exif[ORIENTATION_TAG] == 6:
img = img.rotate(270, expand=True... | 38,772 |
def predict():
"""Predict endpoint.
Chooses model for prediction and predcits
bitcoin price for the given time period.
@author: Andrii Koval, Yulia Khlyaka, Pavlo Mospan
"""
data = request.json
if data:
predict = bool(data["predict"])
if predict:
if predictor.p... | 38,773 |
def test__get_query_monitoring_data():
"""
`query_monitoring_url` can potentially fail, be sure we don't raise when the
endpoint is not reachable
"""
couchbase = Couchbase('couchbase', {}, {})
couchbase._get_query_monitoring_data({'query_monitoring_url': 'http://foo/bar'}) | 38,774 |
def splice_imgs(img_list, vis_path):
"""Splice pictures horizontally
"""
IMAGE_WIDTH, IMAGE_HEIGHT = img_list[0].size
padding_width = 20
img_num = len(img_list)
to_image = Image.new('RGB',
(img_num * IMAGE_WIDTH + (img_num - 1) * padding_width,
... | 38,775 |
def create_segmented_colormap(cmap, values, increment):
"""Create colormap with discretized colormap.
This was created mainly to plot a colorbar that has discretized values.
Args:
cmap: matplotlib colormap
values: A list of the quantities being plotted
increment: The increment used... | 38,776 |
def print_divider():
"""Helper function for test_stochastic_sample (below).
Print a dashed line to break up output."""
print("---------------------------------------------") | 38,777 |
def division_series_logs():
"""
Pull Retrosheet Division Series Game Logs
"""
s = get_text_file(gamelog_url.format('DV'))
data = pd.read_csv(StringIO(s), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data | 38,778 |
def test_output_length_violation(
assert_errors,
assert_error_text,
parse_ast_tree,
tuple_param,
mode,
default_options,
return_like,
):
"""Testing that classes and functions in a module work well."""
tree = parse_ast_tree(mode(generator.format(return_like, tuple_param)))
visitor... | 38,779 |
def scalar_gen(lib, val):
"""
Generates different kinds of scalar-like arrays that contain the given
value.
"""
# pure scalar values
yield lib.array(val)
# ()-shape arrays
yield lib.full((), val)
for ndim in range(1, LEGATE_MAX_DIM + 1):
# singleton arrays
yield lib.f... | 38,780 |
def release_date(json):
"""
Returns the date from the json content in argument
"""
return json['updated'] | 38,781 |
def init_embedding_from_graph(
_raw_data, graph, n_components, random_state, metric, _metric_kwds, init="spectral"
):
"""Initialize embedding using graph. This is for direct embeddings.
Parameters
----------
init : str, optional
Type of initialization to use. Either random, or spectral, by ... | 38,782 |
def basic_hash_table():
"""Not empty hash table."""
return HashTable(1) | 38,783 |
def run_summaries(metrics, session=None):
"""Execute summary ops for py_metrics.
Args:
metrics: A list of py_metric.Base objects.
session: A TensorFlow session-like object. If it is not provided, it will
use the current TensorFlow session context manager.
Raises:
RuntimeError: If .tf_summaries... | 38,784 |
def generate_batch_para(doc_ids, word_ids, batch_size, num_skips, window_size):
"""
batch generator for Skip-Gram Model(Distributed Representation of Word Vecotors)
:param doc_ids: list of document indices
:param word_ids: list of word indices
:param batch_size: number of words in each mini-batch
... | 38,785 |
def scan_by_key(key, a, dim=0, op=BINARYOP.ADD, inclusive_scan=True):
"""
Generalized scan by key of an array.
Parameters
----------
key : af.Array
key array.
a : af.Array
Multi dimensional arrayfire array.
dim : optional: int. default: 0
Dimension along which th... | 38,786 |
def local_luminance_subtraction(image, filter_sigma, return_subtractor=False):
"""
Computes an estimate of the local luminance and removes this from an image
Parameters
----------
image : ndarray(float32 or uint8, size=(h, w, c))
An image of height h and width w, with c color channels
filter_sigma : ... | 38,787 |
def clean_up_to_bram36(top, site):
""" Cleans up BRAM36 BEL to match Verilog model.
Also checks BRAM36 signal sources for sanity (e.g. can be merged) and
then masks/renames signals to match Verilog model.
"""
bel = site.maybe_get_bel('RAMB36E1')
assert bel is not None
for idx in range(15)... | 38,788 |
def createBank():
"""Create the bank.
Returns:
Bank: The bank.
"""
return Bank(
123456,
'My Piggy Bank',
'Tunja Downtown'
) | 38,789 |
def str_to_bool(param):
"""
Convert string value to boolean
Attributes:
param -- inout query parameter
"""
if param.upper() == 'TRUE':
return True
elif param.upper() in ['FALSE', None]:
return False
else:
raise InputValidationError(
'Invalid query... | 38,790 |
def create_parser():
"""
Creates the argparse parser with all the arguments.
"""
parser = argparse.ArgumentParser(
description='Management CLI for mock PCRF',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Add subcommands
subparsers = parser.add_subparsers(title='subc... | 38,791 |
def ProtoFlags(*ss):
"""
add the command options for protoc
Args:
ss : a variable number of string objects
ss may contain multiple string objects, each object can contain multiple options
one option may be:
1. option may contains $WORKSPACE, $OUT Macros value
R... | 38,792 |
def fetch_log_messages(attempt_id: Optional[int] = None,
task_id: Optional[int] = None,
min_severity: Optional[int] = None):
"""
Fetch log messages from the database.
:param attempt_id:
Fetch only log messages associated with one particular task executi... | 38,793 |
def parse_arguments():
"""Argument parser for extract_branch_length"""
parser = argparse.ArgumentParser(
description="extract_branch_length.py: extract the branch length of the "
" common ancestor of a set of species"
)
parser.add_argument(
"-t",
"--tree",
help="I... | 38,794 |
def part_1_solution_2(lines):
"""Shorter, but not very readable.
A good example of "clever programming" that saves a few lines of code, while
making it unbearably ugly.
Counts the number of times a depth measurement increases."""
return len([i for i in range(1, len(lines)) if lines[i] > lines[i - 1]... | 38,795 |
def get_lifecycle_configuration(bucket_name):
"""
Get the lifecycle configuration of the specified bucket.
Usage is shown in usage_demo at the end of this module.
:param bucket_name: The name of the bucket to retrieve.
:return: The lifecycle rules of the specified bucket.
"""
s3 = get_s3()... | 38,796 |
def compute_reward(ori, new, target_ids):
"""
Compute the reward for each target item
"""
reward = {}
PE_dict = {}
ori_RI, ori_ERI, ori_Revenue = ori
new_RI, new_ERI, new_Revenue = new
max_PE, min_PE, total_PE = 0, 0, 0
for item in target_ids:
PE = new_Revenue[item] - ori_Revenue[item]
# Eq. (3) in paper... | 38,797 |
def new_log():
"""Show only lines since the last time the log was echoed."""
if os.path.exists("lnt.log"):
lines = {line for line in open("lnt.log", 'r').readlines()}
else:
lines = set()
with hide('warnings'):
get('/srv/lnt/install/lnt.log', 'lnt.log', )
new_lines = {line for... | 38,798 |
def _compute_aspect_ratios_slow(dataset: Any, indices: Any = None) -> Any:
"""Compute the aspect ratios."""
print(
"Your dataset doesn't support the fast path for "
"computing the aspect ratios, so will iterate over "
"the full dataset and load every image instead. "
"This might ... | 38,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.