content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def standardize_ants_data(ants_data, subject_ID_col):
""" Takes df from ANTs output and stadardizes column names for both left and right hemi
"""
ants_useful_cols = ['Structure Name']
ants_to_std_naming_dict = {}
ants_to_std_naming_dict['Structure Name'] = subject_ID_col #'SubjID'
for roi in ant... | 5,329,900 |
def make_gridpoints(bbox, resolution=1, return_coords=False):
"""It constructs a grid of points regularly spaced.
Parameters
----------
bbox : str, GeoDataFrame or dict.
Corresponds to the boundary box in which the grid will be formed.
If a str is provided, it should be in '(S,W,N,E)' f... | 5,329,901 |
def import_certbot_cert_version(
c, domain_certs_path, certificate_version, server_url_root=DEFAULT_SERVER_ROOT
):
"""
!!! HEY THIS PROBABLY HAPPENS ON UNENCRYPTED TRAFFIC !!!
imports a particular version of a certificate
eg, if a folder has a family of certs numbered like this:
/domain-cer... | 5,329,902 |
def removeElement_2(nums, val):
"""
Using one loop and two pointers
Don't preserve order
"""
# Remove the elment from the list
i = 0
j = len(nums) - 1
count = 0
while i < j:
if nums[i] == val:
while j > i and nums[j] == val:
j -= 1
pr... | 5,329,903 |
def decrypt_ballot_shares(
request: DecryptBallotSharesRequest = Body(...),
scheduler: Scheduler = Depends(get_scheduler),
) -> DecryptBallotSharesResponse:
"""
Decrypt this guardian's share of one or more ballots
"""
ballots = [
SubmittedBallot.from_json_object(ballot) for ballot in req... | 5,329,904 |
def returnHumidity(dd):
""" Returns humidity data if it exists in the dictionary"""
rh = []
if 'RH' in dd:
rh = dd['RH']
elif 'RH1' in dd:
rh = dd['RH1']
else:
# Convert the dew point temperature to relative humidity
Pmb = dd['airpres']/10 # hPa to mb
... | 5,329,905 |
def fixture_penn_chime_raw_df_no_beta(penn_chime_setup) -> DataFrame:
"""Runs penn_chime SIR model for no social policies
"""
p, simsir = penn_chime_setup
n_days = simsir.raw_df.day.max() - simsir.raw_df.day.min()
policies = [(simsir.beta, n_days)]
raw = sim_sir(
simsir.susceptible,
... | 5,329,906 |
def _verify_manifest_signature(manifest, text, digest):
"""
Verify the manifest digest and signature
"""
format_length = None
format_tail = None
if 'signatures' in manifest:
for sig in manifest['signatures']:
protected_json = _jose_decode_base64(sig['protected'])
... | 5,329,907 |
def create_hierarchy(
src_assets: List[Asset],
dst_assets: List[Asset],
project_src: str,
runtime: int,
client: CogniteClient,
subtree_ids: Optional[List[int]] = None,
subtree_external_ids: Optional[List[str]] = None,
subtree_max_depth: Optional[int] = None,
):
"""
Creates/update... | 5,329,908 |
def build_and_save_entity_inputs(
save_entity_dataset_name,
X_entity_storage,
data_config,
dataset_threads,
tokenizer,
entity_symbols,
):
"""Create entity features.
Args:
save_entity_dataset_name: memmap filename to save the entity data
X_entity_storage: storage type for... | 5,329,909 |
def ETL_work():
""" ETL page"""
return render_template("ETL_work.html") | 5,329,910 |
def find_by_key(data, target):
"""Search for target values in nested dict"""
for key, value in data.items():
if isinstance(value, dict):
yield from find_by_key(value, target)
elif key == target:
yield value | 5,329,911 |
async def test_setup_error_no_station(get_fuel_prices, hass):
"""Test the setup with specified station not existing."""
with assert_setup_component(2, sensor.DOMAIN):
assert await async_setup_component(
hass,
sensor.DOMAIN,
{
"sensor": [
... | 5,329,912 |
def advanced_perm_check_function(*rules_sets, restrictions=None):
"""
Check channels and permissions, use -s -sudo or -a -admin to run it.
Args:
*rules_sets: list of rules, 1d or 2d,
restrictions: Restrictions must be always met
Returns:
message object returned by calling given f... | 5,329,913 |
def worker_id():
"""Return a predefined worker ID.
Returns:
int: The static work id
"""
return 123 | 5,329,914 |
def get_urls(spec):
"""Small convenience method to construct the URLs of the Jupyter server."""
host_url = f"http{'s' if spec['routing']['tls']['enabled'] else ''}://{spec['routing']['host']}"
full_url = urljoin(
host_url,
spec["routing"]["path"].rstrip("/"),
)
return host_url, full_... | 5,329,915 |
def resubs(resubpairs,target):
"""takes several regex find replace pairs [(find1, replace1), (find2,replace2), ... ]
and applies them to a target on the order given"""
return resubpair[0].sub(resubpair[1],target)
for resubpair in resubpairs:
target = resub(resubpair,target)
return target | 5,329,916 |
def time_profile(func):
"""Time Profiled for optimisation
Notes:
* Do not use this in production
"""
@functools.wraps(func)
def profile(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} : {time.time() - start}")
ret... | 5,329,917 |
def visualize_net_layers(model_path, weights_path, snapshot_iter, out_dir_path):
"""
:param: model_path is the full path of a mode.deploy_prototxt
:param: weights_path is the full path of caffenet weights or some snapshot
:type mode: Mode
"""
makedirs_ok(out_dir_path)
caffe = import_c... | 5,329,918 |
async def create_guid(data: GuidIn) -> Type[GuidOut]:
"""
Create a record w/o specifying a guid.
Also cleans up expired records & caches the new record.
"""
guid = uuid.uuid4().hex
validated = data.dict()
try:
await create_guid_record(guid, validated['name'], validated['expire'])
... | 5,329,919 |
def exp_for(iterable, filename, display = False):
"""
Run an experiment for words in given iterable and save its
results to PATH_RESULTS/filename. If display is set to True, also
print output to screen.
The output is formated as follows:
[word]RESULT_SEP[size]RESULT_SEP[n+x]RESULT_SEP[diff wit... | 5,329,920 |
def arg_parse():
"""
Parse arguments to the detect module
"""
parser = argparse.ArgumentParser(description='YOLO v3 Detection Module')
parser.add_argument("--bs", dest="bs", help="Batch size", default=1)
parser.add_argument("--confidence", dest="confidence", help="Object Confidence to filter pre... | 5,329,921 |
def test_me_rec():
""" test_me_rec """
res = rec(10)
assert res == 0 | 5,329,922 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Securitas platform."""
alarms = []
if int(hub.config.get(CONF_ALARM, 1)):
for item in hub.Installations:
current_state: CheckAlarmStatus = hub.update_overview(
item, no_throttle=True
... | 5,329,923 |
def remove_useless_lines(text):
"""Removes lines that don't contain a word nor a number.
Args:
text (string): markdown text that is going to be processed.
Returns:
string: text once it is processed.
"""
# Useless lines
useless_line_regex = re.compile(r'^[^\w\n]*$', re.MULTILINE | re.UNICODE)
processed_text... | 5,329,924 |
def get_candidate(word):
"""get candidate word set
@word -- the given word
@return -- a set of candidate words
"""
candidates = set()
candidates |= meanslike(word)
candidates |= senselike(word)
# remove '_' and '-' between words --> candidates is a LIST now
candidates = [w.replac... | 5,329,925 |
def _build_proxy_response(response: RawResponse, error_handler: callable) -> dict:
"""Once the application completes the request, maps the results into the format required by
AWS.
"""
try:
if response.caught_exception is not None:
raise response.caught_exception
messag... | 5,329,926 |
def parse_and_execute(config: dict) -> Dict[str, Any]:
"""Validate, parse and transform the config. Execute backends based
on the transformed config to perform I/O operations.
If `prompt` and/or `default` contains a macro, it will be expanded.
:param config: The original config
:type config: dict
... | 5,329,927 |
def reduce_any(input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
Wrapper around the tf.reduce_any to handle argument keep_dims
"""
return reduce_function(tf.reduce_any, input_tensor, axis=axis,
keepdims=keepdims, name=name,
... | 5,329,928 |
def _dict_merge(
dct: MutableMapping[str, Any], merge_dct: MutableMapping[str, Any]
) -> None:
"""Recursive dictionary merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dc... | 5,329,929 |
def get_customer_profile_ids():
"""get customer profile IDs"""
merchantAuth = apicontractsv1.merchantAuthenticationType()
merchantAuth.name = constants.apiLoginId
merchantAuth.transactionKey = constants.transactionKey
CustomerProfileIdsRequest = apicontractsv1.getCustomerProfileIdsRequest()
Cus... | 5,329,930 |
def download_flexibility_data(
es=None, fpath="", sz_path="C:/Program Files/7-Zip/7z.exe"
):
"""Downloads the NREL EFS flexibility data for the specified electrification
scenarios.
:param set/list es: The electrification scenarios that will be downloaded. Can
choose any of: *'Reference'*, *'Med... | 5,329,931 |
def recip(curvelist):
"""
Take the reciprocal of the y values of the curve or list of curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.recip(curves[1])
>>> pydvif.create_plot(curves, legend=True, stylename='ggplot')
:param curvelist: The curve or list of curves
:type curvelist... | 5,329,932 |
def compare_alignments_(prediction: List[dict], ground_truth: List[dict], types: List[str]) -> (float, float, float):
"""
Parameters
----------
prediction: List of dictionaries containing the predicted alignments
ground_truth: List of dictionaries containing the ground truth alignments
types: Li... | 5,329,933 |
def shim_unpack(
unpack_fn, # type: TShimmedFunc
download_dir, # type str
tempdir_manager_provider, # type: TShimmedFunc
ireq=None, # type: Optional[Any]
link=None, # type: Optional[Any]
location=None, # type Optional[str],
hashes=None, # type: Optional[Any]
progress_bar="off", #... | 5,329,934 |
def xavier_uniform(x):
"""Wrapper for torch.nn.init.xavier_uniform method.
Parameters
----------
x : torch.tensor
Input tensor to be initialized. See torch.nn.init.py for more information
Returns
-------
torch.tensor
Initialized tensor
"""
return init.xavier_unifor... | 5,329,935 |
def _get_interpreters_win(): # pyzo_in_leo.py
"""
Monkey-patch pyzo/util/interpreters._get_interpreters_win.
This patched code fixes an apparent pyzo bug.
Unlike shutil.which, this function returns all plausible python executables.
Copyright (C) 2013-2019 by Almar Klein.
"""
import ... | 5,329,936 |
def create_test_data(site, start=None, end="now", interval=5, units='minutes' , val=50, db='test_db', data={}):
"""
data = {'R1':[0,0,0,..],'R2':[0,0,123,12,...]...} will not generate date but use fixed data set
if val is not set random data will be generated if data is not existing
"""
... | 5,329,937 |
def make_album (artist_name, album_name, number_track = ''):
"""
Storing information in a dictionnary about artist (name, album, nb of
tracks optionnaly)
"""
album = {
'artist_name' : artist_name.title(),
'album_name' : album_name.title(),
}
if number_track:
album['n... | 5,329,938 |
def test_ghz():
"""Generates a GHZ state and checks that the correct correlations (noise reductions) are observed
from the samples
See Eq. 5 of https://advances.sciencemag.org/content/5/5/eaaw4530
"""
# Set up the circuit
np.random.seed(42)
n = 10
vac_modes = 1
copies = 1000
sq_r... | 5,329,939 |
def delete_version(session, package_name, version):
"""
Parameters
----------
session : :class:`sqlalchemy.orm.session.Session`
package_name : str
The NuGet name of the package - the "id" tag in the NuSpec file.
version : str
"""
msg = "db.delete_version({}, {})"
logger.debu... | 5,329,940 |
def Nmin(e, dz, s, a, a_err):
"""Estimates the minimum number of independent structures
to detect a difference in dN/dz w/r to a field value given
by dNdz|field = a +- a_err, at a statistical significance s,
using a redshift path of dz per structure"""
e = np.array(e).astype(float)
dz = np.array... | 5,329,941 |
def remove_punctuation(list_of_string, item_to_keep=""):
"""
Remove punctuation from a list of strings.
Parameters
----------
- list_of_string : a dataframe column or variable containing the text stored as a list of string sentences
- item_to_keep : a string of punctuation signs you want t... | 5,329,942 |
def save_sp500_tickers(force_download=False):
"""Get the S&P 500 tickers from Wikipedia
Parameters
----------
force_download : bool
if True, force redownload of data
Returns
-------
tickers : pandas.DataFrame
The S&P500 tickers data
"""
resp... | 5,329,943 |
def get_search_keywords(testcase):
"""Get search keywords for a testcase."""
crash_state_lines = testcase.crash_state.splitlines()
# Use top 2 frames for searching.
return crash_state_lines[:2] | 5,329,944 |
def make_protein_index(proteins):
"""Indexes proteins
"""
prot_index = {}
skip = set(['sp', 'tr', 'gi', 'ref', ''])
for i, p in enumerate(proteins):
accs = p.accession.split('|')
for acc in accs:
if acc in skip:
continue
prot_index[ac... | 5,329,945 |
def jvp_solve_Hz(g, Hz, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER):
""" Gives jvp for solve_Hz with respect to eps_vec """
# construct the system matrix again and the RHS of the gradient expersion
A = make_A_Hz(info_dict, eps_vec)
ux = spdot(info_dict['Dxb'], Hz)
uy = sp... | 5,329,946 |
def questions(difficulty):
"""This function branches to the desired difficulty.
It takes a string specifiying the difficulty as
an argument and returns nothing."""
easy_difficulty = 4 #This number means that in easy
medium_difficulty = 6 #difficulty four questions will be asked
hard_difficulty = 8
if dif... | 5,329,947 |
def encode(X: Union[tf.Tensor, np.ndarray], encoder: keras.Model, **kwargs) -> tf.Tensor:
"""
Encodes the input tensor.
Parameters
----------
X
Input to be encoded.
encoder
Pretrained encoder network.
Returns
-------
Input encoding.
"""
return encoder(X,... | 5,329,948 |
async def test_simulation_is_not_injected_when_not_simulating():
"""
Make sure the simulation is not instantiated when running in non-simulation mode.
"""
with pytest.raises(Exception):
i = await _get_container(False, True, True)
i.get('simulation_runner') | 5,329,949 |
def _raiden_cleanup(request, raiden_apps):
""" Helper to do cleanup a Raiden App. """
def _cleanup():
for app in raiden_apps:
try:
app.stop(leave_channels=False)
except RaidenShuttingDown:
pass
# Two tests in sequence could run a UDP serve... | 5,329,950 |
def _step2(input):
"""
_step2 - function to apply step2 rules
Inputs:
- input : str
- m : int
Measurement m of c.v.c. sequences
Outputs:
- input : str
"""
# ational -> ate
if input.endswith('ational') and _compute_m(input[:-7]) > 0:
return input[:-1 * len('ational')] + 'ate'
# tional -> tion
elif in... | 5,329,951 |
def test_check_duplicates():
"""test check duplicates"""
d = {
"col1": [1, 2, 3, 4, 5, 6, 7],
"col2": ["Value 1", "Value 1", "", " ", "Value 5", "Value 6", "Value 7"],
"col4": [1, 2, 3, 4, 4, np.nan, np.nan],
}
df = pd.DataFrame(data=d)
print(df)
dfdupes = check_duplicate... | 5,329,952 |
def _toposort(data):
"""Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceding set... | 5,329,953 |
def compute_annualized_volatility(srs: pd.Series) -> float:
"""
Annualize sample volatility.
:param srs: series with datetimeindex with `freq`
:return: annualized volatility (stdev)
"""
srs = hdataf.apply_nan_mode(srs, mode="fill_with_zero")
ppy = hdataf.infer_sampling_points_per_year(srs)
... | 5,329,954 |
async def on_ready():
"""
on_ready() will display a message when the bot is connected to Discord.
"""
print(f'{bot.user} has successfully connected to Discord') | 5,329,955 |
def json_sanitized(value, stringify=stringified, dt=str, none=False):
"""
Args:
value: Value to sanitize
stringify (callable | None): Function to use to stringify non-builtin types
dt (callable | None): Function to use to stringify dates
none (str | bool): States how to treat `No... | 5,329,956 |
def rescan_organization_task(task, org, allpr, dry_run, earliest, latest):
"""A bound Celery task to call rescan_organization."""
meta = {"org": org}
task.update_state(state="STARTED", meta=meta)
callback = PaginateCallback(task, meta)
return rescan_organization(org, allpr, dry_run, earliest, latest... | 5,329,957 |
def python(cc):
"""Format the character for a Python string."""
codepoint = ord(cc)
if 0x20 <= codepoint <= 0x7f:
return cc
if codepoint > 0xFFFF:
return "\\U%08x" % codepoint
return "\\u%04x" % codepoint | 5,329,958 |
def stop_execution(execution_id):
"""
Stop the current workflow execution.
swagger_from_file: docs/stop.yml
"""
name = execution_id # str | the custom object's name
body = kubernetes.client.V1DeleteOptions() # V1DeleteOptions |
grace_period_seconds = 56 # int | The duration in seconds bef... | 5,329,959 |
def reshape_signal_batch(signal):
"""Convert the signal into a standard batch shape for use with cochleagram.py
functions. The first dimension is the batch dimension.
Args:
signal (array): The sound signal (waveform) in the time domain. Should be
either a flattened array with shape (n_samples,), a row ... | 5,329,960 |
def tryallmedoids(dmat, c, weights=None, potential_medoid_inds=None, fuzzy=True, fuzzyParams=('FCM', 2)):
"""Brute force optimization of k-medoids or fuzzy c-medoids clustering.
To apply to points in euclidean space pass dmat using:
dmat = sklearn.neighbors.DistanceMetric.get_metric('euclidean').pairwise(p... | 5,329,961 |
def deleteFactoid(appStore, key, number):
"""
Delete a factoid.
@type appStore: C{axiom.store.Store}
@type key: C{unicode}
@param key: Factoid key
@type number: C{int} or C{None}
@param number: The factoid index to delete or C{None} to delete all
factoids associated with C{key}
... | 5,329,962 |
def human_timedelta(s: Union[int, float]) -> str:
"""Convert a timedelta from seconds into a string using a more sensible unit.
Args:
s: Amount of seconds
Returns:
A string representing `s` seconds in an easily understandable way
"""
if s >= MONTH_SECONDS:
return f"{round(s... | 5,329,963 |
def rate_cell(cell, board, snake, bloom_level=4):
""" rates a cell based on proximity to other snakes, food, the edge of the board, etc """
cells = []
# Get all the cells of "bloom_level" number of circles surrounding the given cell.
for x in range(-bloom_level, bloom_level+1):
for y in range(-... | 5,329,964 |
def clean_tmp_data_from_device(device, remove_page_data=True, remove_pids_data=True):
"""Removes collected pagedata from connected android device
:param remove_page_data: True if page data has to be removed, False if not
:param remove_pids_data: True if pids data has to be removed, False if not
:return... | 5,329,965 |
def edges_are_same(a, b):
"""
Function to check if two tuple elements (src, tgt, val) correspond
to the same directed edge (src, tgt).
Args:
tuple_elements : a = (src, val, val) and b = (src, val, val)
Returns:
True or False
"""
if a[0:2] == b[0:2]:
return True
... | 5,329,966 |
def misc3d():
"""Miscellaneous 3D sizes."""
yield from default_length_params("misc3d", lengths['misc3d'], 1) | 5,329,967 |
def conv_mrf(A, B):
"""
:param A: conv kernel 1 x 120 x 180 x 1 (prior)
:param B: input heatmaps: hps.batch_size x 60 x 90 x 1 (likelihood)
:return: C is hps.batch_size x 60 x 90 x 1
"""
B = tf.transpose(B, [1, 2, 3, 0])
B = tf.reverse(B, axis=[0, 1]) # [h, w, 1, b], we flip kernel to get c... | 5,329,968 |
def get_alert_by_id_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""Get alert by id and return outputs in Demisto's format
Args:
client: Client object with request
args: Usually demisto.args()
Returns:
Outputs
"""
_id = args.get('id')
headers = argToLi... | 5,329,969 |
def close_issues() -> list[res.Response]:
"""Batch close issues on GitHub."""
settings = _get_connection_settings(CONFIG_MANAGER.config)
try:
github_service = ghs.GithubService(settings)
except ghs.GithubServiceError as gse:
return [res.ResponseFailure(res.ResponseTypes.RESOURCE_ERROR, g... | 5,329,970 |
def _invert_lambda(node: tn.Node) -> tn.Node:
"""Invert a diagonal lambda matrix. """
tensor = node.get_tensor()
assert _is_diagonal_matrix(tensor)
diagonal = tensor.diagonal()
return tn.Node(np.diag(1/diagonal)) | 5,329,971 |
def test_with_list_value():
"""Verify that urlencode works with list value."""
d = {'a': {"b": [1, 2, 3]}}
expected = "a[b][]=1&a[b][]=2&a[b][]=3"
assert urllib.unquote(urlencode(d)) == expected | 5,329,972 |
def map_field_name_to_label(form):
"""Takes a form and creates label to field name map.
:param django.forms.Form form: Instance of ``django.forms.Form``.
:return dict:
"""
return dict([(field_name, field.label)
for (field_name, field)
in form.base_fields.items()]) | 5,329,973 |
def teststrip(path1):
"""
Compare the results from serial running to the results from parallel
running to judge whether the results from parallel running is right
or not. The results are gotten by stripe decomposition
Parameters
----------
path1: the path of the folder
Returns
----... | 5,329,974 |
def solve_compound_rec(
recurrence_func: Callable,
parameter_list: List[float],
std_of_compound_dist: float,
max_mRNA_copy_number: int,
recursion_length: int,
index_compound_parameter: int = 3,
compounding_distribution: str = "normal",
decimal_precision: int = 100,
) -> List[float]:
... | 5,329,975 |
def create_brand():
"""
Creates a new brand with the given info
:return: Status of the request
"""
check = check_brand_parameters(request)
if check is not None:
return check
name = request.json[NAME]
brand = Brand.query.filter(Brand.name == name).first()
if brand is not Non... | 5,329,976 |
def test_trace_parent_wrong_version_255(caplog):
"""Version FF or 255 is explicitly forbidden"""
header = "ff-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-03"
with caplog.at_level("DEBUG", "elasticapm.utils"):
trace_parent = TraceParent.from_string(header)
record = caplog.records[0]
ass... | 5,329,977 |
def test_draw_arrow_uniform():
"""
Draw arrows using the same radius for all arrows.
The radius is taken is example property here,
to test if uniform values are properly arrayfied.
"""
reset()
draw_arrows([(0,0,0), (1,0,1)], [(1,0,0), (1,0,1)], radius=0.1) | 5,329,978 |
def print_board(board):
"""prints the state of the board"""
print(f'{get_square_representation(board[0][0])} | {get_square_representation(board[0][1])} | {get_square_representation(board[0][2])}\n'
'---------\n'
f'{get_square_representation(board[1][0])} | {get_square_representation(board[1]... | 5,329,979 |
def purge_reports():
"""Delete expired reports."""
GeneralReport.objects.filter(is_verified=False, date_created__lte=time_threshold(hours=24)).delete() | 5,329,980 |
def update(args):
"""Traverse third-party repos / submodules and emit version-strings"""
failures = []
ver = "///< This file is autogenerated by 'scripts/xnvme_3p.py'\n"
ver += "const char *xnvme_3p_ver[] = {\n"
for project, err in traverse_projects(args):
print("project: %s, success: %r" ... | 5,329,981 |
def feature_contained(boundary: geo, **kwargs):
"""Analyse containment for all features within a single-layer vector file according to a Geometry
and return multiple GeoJSON files."""
geom, prop = kwargs["geom"], kwargs["prop"]
if isinstance(geom, geo.Polygon):
prop["valid"] = boundary.contains(... | 5,329,982 |
def compute(n=26):
""" Computes 2 to the power of n and returns elapsed time"""
start = time.time()
res = 0
for i in range(2**n):
res += 1
end = time.time()
dt = end - start
print(f'Result {res} in {dt} seconds!')
return dt | 5,329,983 |
def _real_to_rational(expr, tolerance=None, rational_conversion='base10'):
"""
Replace all reals in expr with rationals.
Examples
========
>>> from sympy import Rational
>>> from sympy.simplify.simplify import _real_to_rational
>>> from sympy.abc import x
>>> _real_to_rational(.76 + .... | 5,329,984 |
def insert_videos(video_lst):
""" id (auto) | video_id | name | views | likes | comments | date"""
crawler = ApiCrawler()
db = DBConnector()
values = []
for video_id in video_lst:
name, view_count, like_count, comment_count, date = crawler.get_stats(video_id)
value = tuple([video_i... | 5,329,985 |
def run(block, epsilon, ratio, prng, alpha=2, beta=1.2, gamma=1.0, theta=None, verbose=False):
"""Run HDPView
1st phase, divide blocks.
2nd phase, perturbation.
Prepare parameters and execute HDPView
Args:
block (CountTable): block
epsilon (float): privacy budget
... | 5,329,986 |
def test_qubit_state_bra():
"""Test sum_i alpha_i <i| for TLS"""
i = IdxSym('i')
alpha = IndexedBase('alpha')
alpha_i = alpha[i]
hs_tls = LocalSpace('tls', basis=('g', 'e'))
term = alpha_i * BasisKet(FockIndex(i), hs=hs_tls).dag()
expr = KetIndexedSum.create(
term, IndexOverFockSp... | 5,329,987 |
def wait_for_view(class_name):
"""
Waits for a View matching the specified class. Default timeout is 20 seconds.
:param class_name:the {@link View} class to wait for
:return:{@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout
"""
return get_... | 5,329,988 |
def test_list_unsigned_int_min_length_4_nistxml_sv_iv_list_unsigned_int_min_length_5_2(mode, save_output, output_format):
"""
Type list/unsignedInt is restricted by facet minLength with value 10.
"""
assert_bindings(
schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsigne... | 5,329,989 |
def clear_session():
"""
Clears all non-login, non-csrf security keys from the session.
NOTE: this must be in the views.py even though it doesn't have
a route, because it needs access to the session object.
"""
required_keys = ['_user_id', '_fresh', '_flashes', '_id', 'csrf_token']
session_k... | 5,329,990 |
def make_v2_environ(event: dict, environ: dict):
"""
Create environ object from HTTP API Gateway event.
Note: This function mutates the incoming eviron object.
"""
qs = event['queryStringParameters']
environ['REQUEST_METHOD'] = event['requestContext']['http']['method']
environ['PATH_INF... | 5,329,991 |
def _create_table():
"""helper for crc calculation"""
table = []
for i in range(256):
k = i
for _ in range(8):
if k & 1:
k = (k >> 1) ^ 0xEDB88320
else:
k >>= 1
table.append(k)
return table | 5,329,992 |
def average_syllables(verses):
"""
Takes a list of verses
Returns the mean number of syllables among input verses
"""
verse_count = len(verses)
syll_counts = list(map(count_syllables, verses))
syll_count = sum(syll_counts)
return syll_count / verse_count | 5,329,993 |
def _create_subplots_if_needed(ntotal,
ncols=None,
default_ncols=1,
fieldorder='C',
avoid_single_column=False,
sharex=False,
sharey=Fa... | 5,329,994 |
def template_file_counter(session, templates, fetch_count=False):
"""Create template file counter."""
file_counts = {}
default_count = None
if fetch_count:
file_counts = TemplatesDAO.query_file_counts(session=session, templates=templates)
default_count = 0
def counter(template: Temp... | 5,329,995 |
def print_json(raw_output):
"""Format raw_output as json, print it and exit"""
print(json.dumps(raw_output))
sys.exit(0) | 5,329,996 |
def _init_matrices_nw(aln1, aln2, gap_open_penalty, gap_extend_penalty):
"""initialize score matrix and traceback matrix for global alignment
Parameters
----------
aln1 : list
list of activities, which is the first sequence to be aligned
aln2 : list
list of activities, which is the ... | 5,329,997 |
def parse_path_params(end_point_path):
"""Parse path parameters."""
numeric_item_types = ['Lnn', 'Zone', 'Port', 'Lin']
params = []
for partial_path in end_point_path.split('/'):
if (not partial_path or partial_path[0] != '<' or
partial_path[-1] != '>'):
continue
... | 5,329,998 |
def read_pid_stat(pid="self"):
"""
Returns system process stat information.
:param pid: The process ID.
:returns: The system stat information.
:rtype: dict
"""
with open("/proc/%s/stat" % (pid,), "rb") as f:
stat = f.readline().split()
return {
"utime": int(stat[13]),
... | 5,329,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.