content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def PopupNonBlocking(*args, title=None, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None,
text_color=None,
auto_close=False, auto_close_duration=None, non_blocking=True, icon=None,
line_width=None, font=None, no_titlebar=False, grab... | 52,300 |
def wait_for_schedule_to_load(driver):
"""
Checks if some elements exist on the page to see if the page is loaded
:param driver: webdriver
:return: nothing
"""
# Check if the email field is on the page (in case we're on the login page) and check if the dashboard/schedule
# title element e... | 52,301 |
def get_head(client):
"""get_head(client_socket) -> (head_str, body_u8)
Create a byte buffer, recv once and check if the response filled the
buffer. If it didn't, search for \r\n\r\n (HTTP body start). If found, split
the byte buffer at that point and return the decoded head, and raw body.
If it di... | 52,302 |
def pinnuts(f, M, Madapt, theta0, delta=0.6, epsilon=None):
"""
Implements the multinomial Euclidean Hamiltonian Monte Carlo sampler
described in Betancourt (2016).
Runs Madapt steps of burn-in, during which it adapts the step size
parameter epsilon, then starts generating samples to return.
N... | 52,303 |
def dump_source(object, **kwds):
"""write object source to a NamedTemporaryFile (instead of dill.dump)
Loads with "import" or "dill.temp.load_source". Returns the filehandle.
>>> f = lambda x: x**2
>>> pyfile = dill.temp.dump_source(f, alias='_f')
>>> _f = dill.temp.load_source(pyfile)
>>> _f(4)
... | 52,304 |
async def remove_role_requirement(reaction_role: _ReactionRole, ctx: _Context, abort_text: str) -> _Tuple[bool, bool]:
"""
Returns: (success: bool, aborted: bool)
"""
role_requirement = await inquire_for_role_requirement_remove(ctx, reaction_role.role_requirements, abort_text)
if role_requirement:
... | 52,305 |
def get_predicates():
"""
I'm not quite sure how to best get at all the predicates and tag them as relations with id's
"""
"""
results = GolrAssociationQuery(
rows=0,
facet_fields=['relation']
).exec()
facet_counts = results['facet_counts']
relations = facet_c... | 52,306 |
def test_gaussian(_x_data, height, center, sigma):
"""Ensures that gaussian function in pybaselines.utils is correct."""
assert_array_almost_equal(
utils.gaussian(_x_data, height, center, sigma),
gaussian(_x_data, height, center, sigma)
) | 52,307 |
def study_dir(study_name: str) -> str:
"""(Deprecated) old name for storage directory
Args:
study_name: storage name
Returns:
Absolute path of storage directory
Warnings:
Deprecated in favor of :func:`storage_dir`
"""
return storage_dir(study_name) | 52,308 |
def wait_for_metadata_processing(server):
"""Wait for async metadata processing to complete."""
attempts = 0
while True:
busy = False
for section in server.library.sections():
tl = section.timeline()
if tl.updateQueueSize > 0:
busy = True
... | 52,309 |
def to_adjacent_matrix(m, threshold=5e-3):
"""given a numeric dxd matrix, convert it adjcent matrix
Args:
m: dxd ndarray
threshold: (Default value = 5e-3)
Returns:
dxd binary adjacent matrix
"""
m_ = m.copy()
m_[np.where(abs(m) > threshold)] = 1
# otherwise make it zer... | 52,310 |
def printUsage():
"""Usage: python parseSrcmlForTypedata <path_to_srcML_file>"""
print(printUsage.__doc__) | 52,311 |
def hour_min_to_sec(hm):
"""Convert string in format hh:mm to seconds"""
h, m = re.match(r'(\d{1,2}):(\d{2})', hm).groups()
return 3600 * (int(h) + float(m) / 60.) | 52,312 |
def generate_DML_queries(cursor, dml_mod_values):
"""Generate insert, upsert, update, delete DML statements.
For each table in the database that cursor is connected to, create 4 DML queries
(insert, upsert, update, delete) for each mod value in 'dml_mod_values'. This value
controls which rows will be affected.... | 52,313 |
def benchmark_deploy(config_path=_BENCHMARK_CONF_PATH):
"""Deploys benchmark bundle for specified workload.
Params:
config_path: path to benchmark config if YAML format
"""
check_arg_not_blank(config_path, 'config_path')
conf = BenchmarkConfig(config_path=config_path)
_setup_fabri... | 52,314 |
def create_target(hosts, name=None, comment=None):
""" In short: Create a target.
The client uses the create_target command to create a new target.
"""
if name is None:
name = hosts
root = etree.Element("create_target")
tree_name = etree.SubElement(root, "name")
tree_comment = etre... | 52,315 |
def get_slow_queries(**kwargs):
"""Simple function to construct and pass the args
for a redis LRANGE query on the slow_queries log."""
pipe = redis.pipeline()
resp = {}
hash_key='SLOW_QUERIES'
# minus 1 from the actual integer passed for row limit
pipe.lrange(hash_key, 0, kwargs['row_limit... | 52,316 |
def getEscInfo(esc_record):
"""Extracts ESC information from a ESC record.
Args:
esc_record: A ESC record (dict of schema |EscSensorRecord|)).
Returns:
A tuple of:
esc_point: A (longitude, latitude) tuple.
esc_info: A |EscInformation| tuple.
"""
esc_install_params = esc_record['installati... | 52,317 |
def crcremainder(data, key):
"""
crcremainder Function
Function to calculate the CRC
remainder of a CRC message.
Contributing Author Credit:
Shaurya Uppal
Available from: geeksforgeeks.org
Parameters
----------
data: string of bits
The bit-str... | 52,318 |
def test_method_nesting(server):
"""Test that we correctly nest namespaces"""
def handler(message):
return {
"jsonrpc": "2.0",
"result": True if message.params[0] == message.method else False,
"id": 1,
}
server._handler = handler
assert server.nest.te... | 52,319 |
def cancel_experiment(exp_name: str, runs_to_cancel: List[Run], namespace: str) -> Tuple[List[Run], List[Run]]:
"""
Cancel experiment with a given name by cancelling runs given as a parameter. If given experiment
contains more runs than is in the list of runs - experiment's state remains intact.
:param... | 52,320 |
def merge_nn_dicts(
peaks, n_neighbors, peaks_in_chunk_idx_list, knn_indices_list, knn_distances_list
):
"""merge together peaks_in_chunk_idx_list and knn_indices_list
to build final graph
Args:
peaks (_type_): array of peaks
n_neighbors (_type_): number of neighbors
peaks_in_ch... | 52,321 |
def bytes_to_PCM_16bits(bytes, start=0, end=None):
"""
Transform audio file to a format readable by scipy, ie. uncompressed PCM 16-bits.
Support transformation from any format supported by ffmpeg.
"""
try:
audiofile = AudioSegment.from_file(bytes)
except Exception as e:
raise Exc... | 52,322 |
def main():
"""
Entry point of script.
"""
CONFIG = parse_cmdline_args()
maxLinks = CONFIG['links']
ccAlgo = CONFIG['cc_algo']
testDir = CONFIG['test']
testDir = testDir.rstrip('/') # remove a trailing '/', if present
# Use scale if specified, otherwise resort to defaults [1x, 10x, ... | 52,323 |
def clear_sb_jobs_vars():
"""
Invlidates caches related to site-based jobs.
"""
orca.clear_columns('jobs')
orca.clear_columns(
'buildings',
[
'site_based_jobs',
'vac_job_spaces',
'sb_edu_jobs'
]) | 52,324 |
def plotLogLogSpatialSpectra(file, wn, uk):
"""
Generate a loglog plot of a 1D spatial signal
:param file: output fn name
:param wn: frequency [1D numpy array]
:param uk: transformed u: uk = FFT(u). [1D numpy array]
:return: -
"""
ax = plt.gca()
fig = plt.gcf()
# Show lines
plt.loglog(wn, uk,... | 52,325 |
def backup_exists(filename):
""" Return True if backup exists and no_dupes is set """
path = cfg.nzb_backup_dir.get_path()
return path and os.path.exists(os.path.join(path, filename + ".gz")) | 52,326 |
def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000):
"""
Preprocess CIFAR10 dataset
:return:
"""
global keras
if keras is None:
import keras
from keras.datasets import cifar10
from keras.utils import np_utils
# These values are specific to CIFAR10
img_rows = 32
... | 52,327 |
def create_log_group_arn(logs_client, hosted_zone_test_name):
"""Return ARN of a newly created CloudWatch log group."""
log_group_name = f"/aws/route53/{hosted_zone_test_name}"
response = logs_client.create_log_group(logGroupName=log_group_name)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 2... | 52,328 |
def main():
"""Main."""
update_display() | 52,329 |
def _make_filetags(attributes, default_filetag = None):
"""Helper function for rendering RPM spec file tags, like
```
%attr(0755, root, root) %dir
```
"""
template = "%attr({mode}, {user}, {group}) {supplied_filetag}"
mode = attributes.get("mode", "-")
user = attributes.get("user", "-"... | 52,330 |
def button_callback(update: Update, context: CallbackContext) -> Union[None, str]:
"""Обработчик запросов обратного вызова"""
query = update.callback_query
query.answer()
message = query.data.split()
return callbacks[message[0]](update=update, context=context, query=query, message=message) | 52,331 |
def docs(open_browser=True):
"""
Generage Sphinx HTML documentation, including API docs.
Args:
open_browser: Open browser automatically after building docs
"""
local('rm -f docs/dmp_cli.rst')
local('rm -f docs/modules.rst')
local('rm -f docs/dmp_cli*')
local('sphinx-apidoc -o do... | 52,332 |
def has_banking_permission(data):
""" CHecks to see if the user hs the correct permission. Based on Castorr91's Gamble"""
if not Parent.HasPermission(data.User, CESettings.BankingPermissions, CESettings.BankingPermissionInfo):
message = CESettings.PermissionResp.format(data.UserName, CESettings.Banking... | 52,333 |
def calc_temps(start='start_date'):
"""min, max, avg temp for start range"""
start_date = datetime.strptime('2016-08-01', '%Y-%m-%d').date()
start_results = session.query(func.max(Measurements.tobs), \
func.min(Measurements.tobs),\
func.avg(Measur... | 52,334 |
def reindex(tensor, shape, displacement=.5):
"""
Re-color the given tensor, by sampling along one axis at a specified frequency.
.. image:: images/reindex.jpg
:width: 1024
:height: 256
:alt: Noisemaker example output (CC0)
:param Tensor tensor: An image tensor.
:param list[int... | 52,335 |
def test(ctx):
"""
Dispatch tests task
"""
ctx.run("python manage.py test") | 52,336 |
async def init():
"""
Main init method of {NAME}
"""
# Do here your combined factory stuff...
@shared.mod_loader("{NAME}", "stage:combined_factory:blocks")
async def load_combined_factories():
pass
# ... and do here manual block registering ...
@shared.mod_loader("{NAME}", "sta... | 52,337 |
def test_dal_getitem_access():
"""
Verify `__getitem__` is identical to `__getattr__`
"""
expected = "foo"
class SampleService(Service):
def sample_method(self):
return expected
dm = _BaseDataManager()
dm.register_services(sample=SampleService())
with dm.context()... | 52,338 |
def seq_to_matrix(seq, letter_to_index=None):
"""Convert a list of characters to an N by 4 integer matrix
Parameters
----------
seq : list
list of characters A,C,G,T,-,=; heterozygous locus is separated by semiconlon. '-' is filler
for heterozygous indels; '=' is homozygous deletions
... | 52,339 |
def m(id, part = None):
"""
Provide any measure (that we know of) about this design. This acts as a
central registry for measures to not clutter the global namespace. "m" for "measure".
Most numbers can be adjusted, allowing customization beyond the rather simple parameters in
the OpenSCAD Customi... | 52,340 |
def plot(
title: str,
body_system: Body_System,
x_start: float = -1,
x_end: float = 1,
y_start: float = -1,
y_end: float = 1,) -> None:
"""
Utility function to plot how the given body-system evolves over time.
No doctest provided since this function does not have a return value.... | 52,341 |
def GetGPUMemoryUsageStats():
"""Get GPU memory usage stats from CUDAContext/HIPContext. This requires flag
--caffe2_gpu_memory_tracking to be enabled"""
from caffe2.python import workspace, core
workspace.RunOperatorOnce(
core.CreateOperator(
"GetGPUMemoryUsage",
[],
... | 52,342 |
def from_jsonable(return_type: typing.Any, obj: typing.Any) -> typing.Any:
"""Return an instance of the specified 'return_type' that has been
constructed based on the specified 'obj', which is a composition of python
objects as would result from JSON deserialization by the 'json' module.
"""
return ... | 52,343 |
def cleanup_log_dir(log_dir):
"""
Create log directory and remove old files.
Parameters
----------
log_dir : str
Path to log directory.
"""
try:
shutil.rmtree(os.path.join(log_dir))
except Exception:
print("Unable to cleanup log_dir...")
os.makedirs(log_dir, ... | 52,344 |
def _convert_symbol(op_name, inputs, attrs,
identity_list=None,
convert_map=None):
"""Convert from mxnet op to nnvm op.
The converter must specify some conversions explicitly to
support gluon format ops such as conv2d...
Parameters
----------
op_name : st... | 52,345 |
def non_parametric_double_ml_learner(df: pd.DataFrame,
feature_columns: List[str],
treatment_column: str,
outcome_column: str,
debias_model: Union[RegressorMixin, None] = N... | 52,346 |
def convert_image_cv2_to_cv(image, depth=cv.IPL_DEPTH_8U, channels=1):
"""
Converts an OpenCV2 wrapper of an image to an OpenCV1 wrapper.
Source: http://stackoverflow.com/a/17170855
Args:
image: image used by OpenCV2
depth: depth of each channel of the image
... | 52,347 |
def create_targetmd_input(cvs, stringpath, steps_per_point=10000, kappa=10000.0, backwards=False):
"""
Units info https://plumed.github.io/doc-v2.4/user-doc/html/_u_n_i_t_s.html
default kj/mol for energy, A for distance.
Spring constant has unit Energy units per Units of the CV
:param args:
:par... | 52,348 |
def split_game_path(path):
"""Split a game path into individual components."""
# filter out empty parts that are caused by double slashes
return [p for p in path.split('/') if p] | 52,349 |
def assert_allclose(
actual: numpy.float32, desired: numpy.float64, rtol: float, atol: float
):
"""
usage.sklearn: 1
"""
... | 52,350 |
def group_requirement(ctx: Any, institution: str, requirement_id: str) -> dict:
"""
group_requirement : NUMBER GROUP groups qualifier* label? ;
groups : group (logical_op group)*; // But only OR should occur
group : LP
(block
| blocktype
|... | 52,351 |
async def test_config_flow_already_configured_weather(hass):
"""Test already configured."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_LATITUDE: TEST_LATITUDE,
CONF_LONGITUDE: TEST_LONGITUDE,
},
unique_id=f"{TEST_LATITUDE}-{TEST_LONGITUDE}",
)... | 52,352 |
def create_complete_dag(workbench: Workbench) -> nx.DiGraph:
"""creates a complete graph out of the project workbench"""
dag_graph = nx.DiGraph()
for node_id, node in workbench.items():
dag_graph.add_node(
node_id,
name=node.label,
key=node.key,
versio... | 52,353 |
def read_geojson_metadata(geojson_file, start_epoch, end_epoch, date_field, date_format):
"""Reads metadata from geojson file from an input directory
and returns a list of wkt strings for points within the given time range
:param geojson_file: input geojson file
:param start_epoch: start of time... | 52,354 |
def read_single_disk(image_id):
""" Stores a single image to disk.
Parameters:
---------------
image_id integer unique ID for image
Returns:
----------
image image array, (32, 32, 3) to be stored
label associated meta data, int label
"""
... | 52,355 |
def try_get_balance(agent_config: AgentConfig, wallet: Wallet, type_: str) -> int:
"""
Try to get wallet balance.
:param agent_config: agent config object.
:param wallet: wallet object.
:param type_: type of ledger API.
:retun: token balance.
"""
try:
if type_ not in DEFAULT_LE... | 52,356 |
def test_ospf_ecmp_tc17_p0(request):
"""
Verify OSPF ECMP.
Verify OSPF ECMP with max path configured as 2 (Edge having 2 uplink ports)
"""
tc_name = request.node.name
write_test_header(tc_name)
tgen = get_topogen()
# Don't run this test if we have any failure.
if tgen.routers_have_... | 52,357 |
def test_self_iat_hook_success():
"""Test hook success in single(self) thread"""
pythondll_mod = [m for m in windows.current_process.peb.modules if m.name.startswith("python") and m.name.endswith(".dll")][0]
RegOpenKeyEx = [n for n in pythondll_mod.pe.imports['advapi32.dll'] if n.name == function_to_hook][0... | 52,358 |
def say_wait(phrase):
""" Say the given phrase out load. This will run on the current thread. """
_voice.Speak(phrase) | 52,359 |
def ravel(a, order='C'):
"""Returns a flattened array.
It tries to return a view if possible, otherwise returns a copy.
This function currently does not support the ``order = 'K'`` option.
Args:
a (cupy.ndarray): Array to be flattened.
order ({'C', 'F', 'A'}):
Read the ele... | 52,360 |
def find_kwic(item, regexes, shell_nouns):
"""This function takes the location of a vertically annotated text of COCA/COHA
and transforms it to the form [['word', 'lemma', 'POS'], ['word2', 'lemma2', 'POS2'], ...]
As a second argument the regex objects to be used in the search are passed
(they are built outside thi... | 52,361 |
def is_numeric(value: str):
"""Return True if given value is a number"""
return value.isdigit() | 52,362 |
def migrate():
"""Make migrations and run them."""
_execute_django_command('makemigrations')
_execute_django_command('migrate') | 52,363 |
def mixed(operations, paths, _fs=None):
"""Decorates a function that supports multiple types of action.
:param operations: The list of operations (e.g. ["readlink"]).
:param paths: The paths to match (e.g. ["/<file>", "/<file>.txt"]).
:param _fs: An optional _DiazedFileSystem instance (mostly for testi... | 52,364 |
def fatal(msg):
"""Prints a FATAL message and exit with status code 1
Args:
msg (:obj:`str`): Error message to print
Raises:
SystemExit
"""
print("[FATAL] %s" % str(msg), file=sys.stderr)
sys.exit(1) | 52,365 |
def bladeTELoss(w, t, Temp, alpha, beta, rho, C, K, Y):
"""Thermoelastic calculations for blades
Invoked for upper joint only (there is no lower blade)
w = angular frequency
t = blade thickness
Temp = temperature
alpha = coeff of thermal expansion
beta = temp dependence of Young's modulus
... | 52,366 |
def pretty_snp_association(association):
"""
Prints association stats in roughly the same format as STOPGAP for a cluster of SNPs
Args: GeneSNP_Association
Returntype: String
"""
snp = association.snp
gene_name = association.gene.name
gene_id = association.gene.id
score = association.score
results = [sn... | 52,367 |
def test_cryptosystem_char():
"""Can we properly use the cryptosystem?"""
keys = generate_keypair()
(pub, sec) = (keys['pub'], keys['sec'])
mes1 = """a"""
cipher = encryption(mes1, pub)
mes2 = decryption(cipher, sec)
assert mes1 == mes2 | 52,368 |
def nb_Genes(w, device="cpu"):
"""
========================================================================== \n
Return the number of selected genes from the matrix w \n
#----- INPUT \n
w : (Tenso... | 52,369 |
def S_IMODE(mode):
"""Return the portion of the file's mode that can be set by
os.chmod().
"""
return mode & 0o7777 | 52,370 |
def sync(loop, func, *args, **kwargs):
"""
Run coroutine in loop running in separate thread.
"""
if not loop._running:
try:
return loop.run_sync(lambda: func(*args, **kwargs))
except RuntimeError: # loop already running
pass
e = threading.Event()
main_ti... | 52,371 |
def test_agent_check_pass():
"""
Test consul agent check pass
"""
consul_url = "http://localhost:1313"
key = "cluster/key"
mock_result = "test"
mock_http_result = {"status": 200, "dict": mock_result}
mock_http_result_false = {"status": 204, "dict": mock_result}
mock_url = MagicMock(... | 52,372 |
def storage_initial_constraint_rule(backend_model, node, tech):
"""
If storage is cyclic, allow an initial storage to still be set. This is
applied to the storage of the final timestep/datestep of the series as that,
in cyclic storage, is the 'storage_previous_step' for the first
timestep/datestep.
... | 52,373 |
def get_hform_298k_thermp(output_string):
"""
Obtains deltaHf from thermp output
"""
# Line pattern containing the DeltaHf value at 298 K
dhf298_pattern = ('h298 final' +
app.one_or_more(app.SPACE) +
app.capturing(app.FLOAT))
dhf298 = float(apf.last_c... | 52,374 |
def confirm_date(config, datestring) :
"""copy points (active fire and confirmed burn points to fire_events table"""
db_date = db_date_string(image_date_time(datestring))
print db_date
vt.execute_active_fire_2_events(config, db_date)
vt.execute_threshold_2_events(config, db_date) | 52,375 |
def filter_peaks_width(peakdic, width_range):
"""
Filter a dictionary of peaks by peak range width.
- peakdic: Dictionary of peaks per sequence (chromosome)
- with_range: Tuple with the minimum and maximum peak
peak width to keep. Other peaks will be discarded
"""
minim, maxim = width_r... | 52,376 |
def scrape_course(data):
"""Initializes the course if it doesn't exist and returns a list of
("instructor", data) pairs."""
print " " + data['url']
instructors = []
coursesoup = BeautifulSoup(requests.get(data['url']).text)
ratingstab = coursesoup.find(id="tab-ratings")
floatdivs = ratingsta... | 52,377 |
def send_tp(mcr, x, y, z, a, b, player):
"""
Send the telepor command using mcr. 'x', 'y' 'z'
are cartesian coordinates, 'a' and 'b' are angles.
"""
tp_parameters = [str(i) for i in ["/tp", player, x, y, z, a, b]]
mc_command = ' '.join(tp_parameters)
resp = mcr.command(mc_command)
... | 52,378 |
def f2suff(forfile, opath, suff):
"""
Construct output filename in opath with new suffix
Parameters
----------
forfile : str
Fortran90 file name
opath : str
Relative output path.
Script assumes output path: dirname(forfile)/opath
suff : str
Suffix of input fi... | 52,379 |
def ori_smooth(directions,frames_per_second=None,return_missing=False):
"""smooth orientations using an RTS smoother
This treats orientations as XYZ positions
"""
dt = 1.0/frames_per_second
A = np.array([[1, 0, 0, dt, 0, 0],
[0, 1, 0, 0, dt, 0],
[0, 0, 1, 0, 0, ... | 52,380 |
def compile_array(data: Sequence[float], format="xyseb") -> array.array:
"""Gather point components from input data.
Format codes:
- ``x`` = x-coordinate
- ``y`` = y-coordinate
- ``s`` = start width
- ``e`` = end width
- ``b`` = bulge value
- ``v`` = (x, y [,z])... | 52,381 |
def nms(bboxes, iou_threshold, sigma = 0.3, method = 'nms'):
""" function to implement non-maximal suppression / softmax non-maximal supression of bboxes """
""" takes bboxes with the shape of (num_of_box, 6), where 6 => (xmin, ymin, xmax, ymax, score, class) """
# remove duplicates in classes
... | 52,382 |
def hls_to_hex(h, l, s):
"""Converts a (hue, lightness, saturation) tuple to a "#rrbbgg" string.
Args:
h, l, s: the HLS values
Returns:
a hex string
"""
return rgb_to_hex(*hls_to_rgb(h, l, s)) | 52,383 |
def get_run_info_hiseq( instrument_model, application_version, tree ):
"""
Helper function to get some info about the sequencing runs.
Args:
tree: xml tree
Returns:
dict: basic statistics about run, like date, instrument, number of lanes, flowcell ID, read lengths, etc.
"""
run_... | 52,384 |
def seconds_to_hhmmssms(seconds):
"""Parses the number of seconds after midnight and returns the corresponding HH:MM:SS.f-string.
Args:
seconds (float): number of seconds after midnight.
Returns:
str: the corresponding HH:MM:SS.f-string.
"""
int_seconds = int(seconds)
ms = roun... | 52,385 |
def sample_with_probs(model, x, steps, temperature=1.0, sample=False, top_k=None, first_sentence=False):
"""
A modified version of sample from mingpt.util that also returns probability of each sentence
and allow end with first sentence complete
"""
block_size = model.get_block_size()
model.eval(... | 52,386 |
def expression(processor, composer, searcher):
# type: (Parser, Compiler, scanner.Scanner) -> Tuple[Parser, Compiler]
"""Compiles expression."""
return parse_precedence(processor, composer, searcher, Precedence.PREC_ASSIGNMENT) | 52,387 |
def get_games_results(game_name: str, web: str = "all"):
"""
Get games results from spiders
:param game_name:
:param web:
:return: list of games, obtained from spiders.
"""
games = []
not_formatted_games = []
time.sleep(get_random_delay())
if web == "eneba":
not_formatted... | 52,388 |
def plot_pr_curve(y_true, y_pred, title=None):
"""
Convenience function for plotting precision recall curve
@param: y_true - ground truth
@type: array like
@param: y_pred_train - predictions
@type: array like
"""
precision, recall, _ = precision_recall_curve(y_true, y_pred)
avg_prec... | 52,389 |
def matrix_from_interactions(interactions, mapping, default=0.0):
"""Generate numpy matrices from interaction dictionary
:param interactions: dictionary read from WORDOM avgpsn
:param mapping: residuemap, preserves residue names
:param default: default interaction
:return: tuple of interaction stre... | 52,390 |
def _generate_dataset(path: str, name: str,
dataset_creator: HDF5CreatorAbstract,
save_intermediate: bool = False,
force: bool = False):
"""Generate a dataset from a group of dMRI subjects with multiple bundles.
All bundles are merged as a single... | 52,391 |
def to_flags(value):
"""Return a (flags, ednsflags) tuple which encodes the rcode.
*value*, an ``int``, the rcode.
Raises ``ValueError`` if rcode is < 0 or > 4095.
Returns an ``(int, int)`` tuple.
"""
if value < 0 or value > 4095:
raise ValueError('rcode must be >= 0 and <= 4095')
... | 52,392 |
def layer(W):
""" Single layer of the variational classifier.
Args:
W (array[float]): 2-d array of variables for one layer
"""
qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0)
qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1)
qml.CNOT(wires=[0, 1]) | 52,393 |
def map_mix_query_attr_to_ch(mixing_query):
"""Map the mixing query attributes (tip_angle and phase) to the channel index.
If the attribute is defined for the channel use the defined value else set it to 0.
Args:
spectral_dimension: A list SpectralDimension objects.
index: The index of the ... | 52,394 |
def flat_iterator(nml):
"""Iterator that returns the adress of an element as a 2-tuple,
along with the element """
for key, value in nml.items():
for inner_key, inner_value in value.items():
yield (key, inner_key), inner_value | 52,395 |
def record_activations(outputs, model, epoch, data_input, x_test, y_test,
batchsize=32, record_all_flag=False, rec_test_flag=False,
specific_records=[]):
"""
extracts and records the layer activations for an epoch and stores them in ooutput object
outputs: outpu... | 52,396 |
def test_init():
""" Tests init function """
_ = behavior_tree.BT([], behavior_list) | 52,397 |
def FuseGTestH(gtest_root, output_dir):
"""Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
output_file = open(os.path.join(output_dir, GTEST_H_OUTPUT), "w")
processed_files = set() # Holds all gtest headers we've processed.
def ProcessFile(gtest_header_path):
"""Processes ... | 52,398 |
def nn_iter(indices, distances, black=None):
"""Helper method to unpack nearest neighbors lists.
Args:
indices (list): neighbor indices.
distances (list): neighbor distances.
black (list): black list.
Returns:
list(tuple)
"""
for idx, dist in zip(indices, distances)... | 52,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.