content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def scrollableChild(x,y,l,e = None):
""" Finds a child of l that is scrollable.
Useful when there is a scrollable element in another scrollable element """
if e is None:
e = getXmlElement(l)
if e is None:
# Unexpected scroll...
return None
else:
bounds = B... | ad89c96063448b36b2c1acd5445af2e359eac7d0 | 3,603,700 |
def extract_lod_cmd(lod):
"""
Extract only one LoD for a dataset.
To use on datasets having more than one LoD for the city objects.
For each city object, it keeps only the LoD passed as parameter,
if a city object doesn't have this LoD then it is deleted.
"""
def processor(cm):
utils... | 9099e534652e96785a6169b40b5ec350b0961eaf | 3,603,701 |
import math
def line_intersect(pt1, pt2, ptA, ptB):
"""
Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html
this returns the intersection of Line(pt1,pt2) and Line(ptA,ptB)
returns a tuple: (xi, yi, valid, r, s), where
(xi, yi) is the intersection
r is the scalar multiple such ... | 73ffd9674302f3be7b0edd9cdddd95df198919cb | 3,603,702 |
import html
def dash_higher_derivatives_problem(
solver: HigherDerivativesSolver,
render_latex_url: str = r"https://render.githubusercontent.com/render/math?math",
):
"""
Helper function to print higher derivatives problem.
"""
assert isinstance(
solver, HigherDerivativesSolver
),... | 6dadc04b8682a597d5ab0fb5e28c5c10562c0d5b | 3,603,703 |
def find_last_index(doc):
"""
Returns: int
The last cursor index (loc) of the template document.
"""
body = extract_body(document=doc)
contents = body["content"]
last_index = contents[-1]["endIndex"]
return last_index - 1 | 1e0e9412d21c2f5ae1541ba698ec6e1e36eb1205 | 3,603,704 |
def getLeftWheelCost(robotState, leftTorque):
"""
:type robotState: numpy.ndarray
"""
v = robotState[3]
omega = robotState[4]
return abs(leftTorque * ((v + (b*omega)) / r)) | 316c4ac1288c11453a9d5c159185dd0398b1c0bd | 3,603,705 |
def ihfft(a, n=None, axis=-1, norm=None):
"""Computes the inverse FFT of a signal that has Hermitian symmetry.
Parameters
----------
a : array_like
Input array.
n : int, optional
Length of the inverse FFT, the number of points along transformation axis in the
input to use. I... | 3378b51b35e536ca3c523f51fbd29fefee201686 | 3,603,706 |
from geonode.contrib.exif.utils import exif_extract_dict
def document_detail(request, docid):
"""
The view that show details of each document
"""
document = None
try:
document = _resolve_document(
request,
docid,
'base.view_resourcebase',
_PE... | dbd14a7773758d5d913d74abaaaca614250cef50 | 3,603,707 |
def get_rel_path_translations_csv(lang=None):
"""Return the path to the file containing the extra phrases."""
return get_rel_path_phrases(dir_name=_DIR_PHRASES_CSV, lang=lang) | 5f0369bfde4fdbc6e22e8b43f8d9cf064d9f58ba | 3,603,708 |
def qubitoperator_to_pauli_sum(qubit_op: QubitOperator) -> cirq.PauliSum:
"""
Convert QubitOperator to PauliSum object.
Args:
qubit_op (QubitOperator): operator to convert.
Returns:
pauli_sum (PauliSum): cirq PauliSum object.
Raises:
TypeError: if qubit_op is not a QubitOp... | 19076f09a5d04ea37379a7627e915678dd3c3bda | 3,603,709 |
def de_sort(vals, inds):
""" De-sort an array of values vals that were sorted according to the indices inds.
Args:
vals (ndarray): a 1-D array to de-sort.
inds (ndarray of int): the sorting indices.
Returns:
ndarray: the de-sorted array.
"""
# Create the de-sorted structu... | 4f79e82a9ddaf0f727bdb183eda56201ea3cb2ec | 3,603,710 |
def render_icon(icon):
"""
Render a Bootstrap glyphicon icon
"""
return '<span class="glyphicon glyphicon-{icon}"></span>'.format(icon=icon) | 4fcc501cbea07d3dbe99f35f63dc39c8f629c4c4 | 3,603,711 |
import types
def task__package_mkdir_deb_iso_root() -> types.TaskDict:
"""Create the Debian packages root directory on the ISO."""
return targets.Mkdir(
directory=constants.REPO_DEB_ROOT, task_dep=['_package_mkdir_iso_root']
).task | 55eddf3fc3f24b5e016d66064e6c9f90cea1e318 | 3,603,712 |
import sys
import xml
import urllib
def rss_fetch():
"""This function fetches the new items, returning it."""
items = {}
def add_item(pubDate, title, link):
nonlocal items
idx = float(parsedate_to_datetime(pubDate).timestamp())
while idx in items:
idx = idx + 0.1
... | b7c3573e06a10e7a8cb8168caf28572eca3483bc | 3,603,713 |
def _add_bias_category(row):
"""A function to add the bias category based on the bias motivation. To be
used with pandas.DataFrame.apply().
"""
row['BIAS_CATEGORY'] = _BIAS_CATEGORY_MAP.get(row['BIAS_DESC'],
'MultipleBias')
return row | c5d680243aee53eee06882ddd997a8d08e92027a | 3,603,714 |
def new_trident(game_state):
"""
A composite component representing a Sword item.
"""
c = Composite()
set_item_components(c, game_state)
set_melee_weapon_component(c)
c.set_child(Description("Trident",
"A long stick with a with three sharp points at one end."
... | 925e40882876def4dda52cab2d5407d0fbcece4b | 3,603,715 |
def level_updates_from_semester_results(semester, level_up_score_thresholds=None):
"""
Returns a list of LevelUpRecords for users whose level should be updated.
First 5 competitors from each level get a levelling boost (results_table_level + 1) for the
next semester.
Optionally define custom level-... | 6a42f2e229aa31546ad9a06728e5df7e9212859d | 3,603,716 |
import binascii
def hex_to_bytes(hex_repn: str) -> bytes:
"""
Convert a hexidecimal string representation of
a block of bytes into a Pyton bytes object.
This function is the inverse of bytes_to_hex.
hex_to_bytes('F803') -> b'\xf8\x03'
"""
return binascii.unhexlify(hex_repn) | 2c456a353e1cce75998d1b2dd9b077af962ee41d | 3,603,717 |
import re
def get_text_url_base(content):
"""Return base URL to full text based on the content of the landing page.
Parameters
----------
content : str
The content of the landing page for an rxiv paper.
Returns
-------
str or None
The base URL if available, otherwise None... | c679e9e1e8b074f7fea3aaf9eb256542e20a4d7d | 3,603,718 |
def calculateMatchValue(incompleteObject, knownObject):
"""Calculate an integer match value, scoring +1 for each match"""
matchvalue = 0
for catkey, catval in incompleteObject.items():
if knownObject[catkey] == catval:
matchvalue += 1
return matchvalue | bd0efa089fa9edc2e290a46ca7e18b3d22bd1594 | 3,603,719 |
def LCS1(a, b, i, j):
""" LCS recursion """
if i >= len(a) or j >= len(b):
return 0
elif a[i] == b[j]:
return 1 + LCS1(a, b, i+1, j+1)
else:
return max(LCS1(a, b, i+1, j), LCS1(a, b, i, j+1)) | 0b1819ee67dd6fc60e66b8c2b83f79c062a149db | 3,603,720 |
def HRNR(noisy_stft, TSNR_spectrum, TSNR_gains, noise_estimation, NL="max"):
"""
Reconstructs the signal by re-adding phase components to the magnitude estimate
:param noisy_stft: stft of original noisy signal
:param TSNR_spectrum: clean stft returned by TSNR
:param TSNR_gains: gains of each stft fr... | e6256dc3b03824de194548c3803bbbfc56c3311b | 3,603,721 |
import os
def noxcptRmDir(sDir, oXcptRet = False):
"""
No exceptions os.rmdir wrapper.
"""
oRet = True;
try:
os.rmdir(sDir);
except:
oRet = oXcptRet;
return oRet; | e1611ecd30927ef73d53a773d8ccc4bcb29df8cb | 3,603,722 |
def range_factory(policy, sym):
"""Factory function for creating MLS range objects."""
if not enabled(policy):
raise exception.MLSDisabled
if isinstance(sym, Range):
assert sym.policy == policy
return sym
elif isinstance(sym, qpol.qpol_mls_range_t):
return Range(policy,... | e8efe9592a5d4a5caa46c929053f8450ec657436 | 3,603,723 |
def get_contents_dir(node):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
for n in sorted(node.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (n.get_csig(), n.name))
return ''.join(content... | 147d26ae5fca9540a081feef495dfa4bb0fca8eb | 3,603,724 |
def is_complete(p):
"""
Determine if the logged optimization was completed
"""
l = find_line(p, "Optimization Done")
return l is not None | 7575793e95d9225b99580f512c0490f5ca42bc2b | 3,603,725 |
import subprocess
def _check_networking() -> CheckLevels:
"""
Error if the Docker network is not set up correctly.
"""
highest_level = CheckLevels.NONE
# Image for a container which sleeps for a long time.
tiny_image = 'luca3m/sleep'
client = docker_client()
docker_for_mac = bool(clien... | 6c8a279569db13581bd33693cc90920416d1bb1d | 3,603,726 |
def in_top_k(predictions, targets, k):
"""Returns whether the ``targets`` are in the top ``k`` ``predictions``.
# Arguments
predictions: A tensor of shape batch_size x classes and type float32.
targets: A tensor of shape batch_size and type int32 or int64.
k: An int, number of top eleme... | 2b0af6ec66e135bf9a93174af0cbf7d43ab07ee7 | 3,603,727 |
def hoop_thickness(P_i, P_o_min, D_o, sig_y_d):
"""Return the minimum (note not nominal) wall thickness for internal pressure
containment.
Considers:
- Allowable hoop stress
- Worst case maximum pressure difference
- Appropriate wall thickness theory, i.e. thick or thin
:param float P_i: I... | 20317e1fceafe10c24ad877c7d5160cf179960a0 | 3,603,728 |
from typing import List
from typing import Tuple
def mix_encoding_pairs(encodings: List[np.ndarray],
encodings_name: List[str]) \
-> Tuple[np.ndarray, List[str]]:
"""
Mixes each elements of the encodings two by two, by adding the encodings
together and returning them, with their resul... | 4d47af1c6523ecf469edc183026dbad22039fa10 | 3,603,729 |
def remove_stopwords(words, stoplist):
""" Remove stop words
Parameter arguments:
words = list of words e.g. ['.', 'The', 'boy', 'is', 'playing', '.']
return:
list of tokens
['boy', 'is', 'playing']
"""
return [token for token in words if not (token.startswith(PUNCT) or token in stoplis... | 9ab9ee2b44ce5e73c5545991deb45118903dd6ba | 3,603,730 |
def norm_matrix(R):
"""Normalize rotation matrix.
Parameters
----------
R : array-like, shape (3, 3)
Rotation matrix with small numerical errors
Returns
-------
R : array, shape (3, 3)
Normalized rotation matrix
"""
R = np.asarray(R)
c2 = R[:, 1]
c3 = norm_v... | c4b4ebef51fa315d655dd7d599b583ae18d512b3 | 3,603,731 |
def DMux8Way(i: Bit, s: Bus3) -> Bus8:
"""
8-way demultiplexor
{a, b, c, d, e, f, g, h} = {in, 0, 0, 0, 0, 0, 0, 0} if sel == 000
, {0, in, 0, 0, 0, 0, 0, 0} if sel == 001
, ...
, {0, 0, 0, 0, 0, 0, 0, in} if sel == 111
```
+------------------+--+ i
| | ... | 63f2d91a54cc220e79289fe045ebd2db763a1548 | 3,603,732 |
def get_args() -> Namespace:
"""Method to create and configure a argument parser"""
parser: ArgumentParser = ArgumentParser(prog='python osc_tools.py',
formatter_class=RawTextHelpFormatter)
subparsers = parser.add_subparsers(title='These are the available OSC com... | 0dc76cec968adc1b0a119a4edd2ff47a67c247c5 | 3,603,733 |
import os
import sys
def _prepend_path(env):
"""
Make sure the PATH contains the location where the Python binary
lives. This makes sure cli tools installed in a virtualenv work.
"""
if env is None:
env = os.environ
env = dict(env)
new = os.path.dirname(sys.executable)
path = e... | 7e5f8c59a5f24fc5b603e437db80f11464715aea | 3,603,734 |
import sys
def configure():
"""Parse command line options and integrate with settings.
"""
init_logging()
if config.xml_debug:
PrintReminder.yellow(
'XML debug file at %s' % config.XML_DEBUG_FILENAME)
config.xml_debug_fh = open(config.XML_DEBUG_FILENAME, 'w', 0)
... | 87428300c76e2628f8ba1b2124a233fe2dd2f8fc | 3,603,735 |
def padding_attention_mask(from_tensor, to_mask, *, dtype):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: A Tensor of shape [batch_size, heads, from_seq_length, to_seq_length].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Te... | b929376254529644e71fd9ddc371240dc1eaab08 | 3,603,736 |
def get_model_parallel_group():
"""Get the model parallel group the caller rank belongs to."""
assert _MODEL_PARALLEL_GROUP is not None, \
'model parallel group is not initialized'
return _MODEL_PARALLEL_GROUP | 5372c3662c4a3907326b52237594e941d8dc0935 | 3,603,737 |
import numpy
def blackBodySpectrum(TemplateSpectrum=None, **kwargs):
""" Returns a blackbody function over the given wavelength """
"""
inputs:
wl : wavelength array
Assumed to be in units of cm, unless specified by wlUnits kwarg
nu : frequency array
... | e99dc61e250744f2b39184999f42690206637f15 | 3,603,738 |
def calculate_fracture_starting_position(shape, seed):
"""Choose a random starting position along the x or y axis (random choice).
Parameters
----------
shape : tuple of int
Number of rows and columns in the grid
seed : int
Seeds the random number generator, so that a particular ran... | 8d69180624cf4afc9c51258e12fd1e34b0d1d10c | 3,603,739 |
def two_way_merge(array1, array2):
"""
Given two sorted arrays, merge them into a single sorted array.
This is a very simple operation but is a precursor to k-way merge.
We compare each element at the beginning of each array and remove smaller one and add it to the merged array.
If one of the array... | 6d1a4779634809b7ff63159928af668596f5c00e | 3,603,740 |
import torch
def fake_image_tensor(H, W, C) -> torch.Tensor:
""" Fake image tensor """
torch.manual_seed(0)
return torch.rand(C, H, W) | 3cf09924a856ff46240804c6f4ceea65ce70410c | 3,603,741 |
def __detect_pipeline(pet: PETGraphX, root: CUNode, children_cache=None, dep_cache=None) -> float:
"""Calculate pipeline value for node
:param pet: PET graph
:param root: current node
:param children_cache: used to cache intermediate children
:param dep_cache: used to cache intermediate dependencie... | 01fc172758db7a4ee23a989066019985cea63d84 | 3,603,742 |
def wavelength_to_energy(wavelength: float):
"""Conversion from photon wavelength (angstroms) to photon energy (eV)"""
return 1.2398 / wavelength * 1e4 | fc067b9fd9cae68103742e8998b6aa0117d906d0 | 3,603,743 |
def openTypeOS2TypoDescenderFallback(info):
"""
Fallback to *descender*.
"""
return getAttrWithFallback(info, "descender") | 740f32214fc5396c7272810225d4408300afb167 | 3,603,744 |
def parser_add_optgroup_from_def(parser, defn, exclusive=False, prefix=None):
"""Add an entire option group from a definition in a custom format
Parameters
----------
parser : argparser instance
defn : tuple
Option group spec. Complicated beast. Grep source code for syntax examples.
exclu... | 08cf69d9374389508f0b104e972d17942aec6c27 | 3,603,745 |
import pathlib
def featurizer(tmpdir):
"""Generate a featurizer for tests."""
node_storage = LocalModelStorage(pathlib.Path(tmpdir))
node_resource = Resource("sparse_feat")
context = ExecutionContext(node_storage, node_resource)
return CountVectorsFeaturizer(
config=CountVectorsFeaturizer.... | b7461a8ab23523ff418b332eab5ad96dc404ac6f | 3,603,746 |
def compute_content_cost(a_C, a_G):
"""
Computes the content cost
Arguments:
a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C
a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G
R... | 139f71dc038d143d1de4738d4d0646322256ba71 | 3,603,747 |
import random
def generate_graph(rule_dict, rule_list):
"""
Create a new graph from the VRG at random
:param rule_dict: List of unique VRG rules
:return: newly generated graph
"""
node_counter = 1
# non_terminals = set()
non_terminals = {} # now a dictionary, key: non-terminal id, va... | 68cd97b56958266d7b9ba65571a9146b021de89f | 3,603,748 |
from typing import List
def get(sp: str, *args, **kwargs) -> List[List[int]]:
"""Wrapper function for sparsity patterns
Args:
sp (str): type of sparsity pattern, e.g.,
- 'diag' -- Diagonal matrix
- 'dense' -- Dense matrix
- 'nodiag' -- Dense without main diagonal e... | 3636f2f7d3c83724eb1bafb832f464e8b4d1e3cf | 3,603,749 |
from typing import Iterable
def iterate(iterable, progress_bar=None, text='', echo=1, echo_items=False):
"""
:type iterable: Iterable
:type progress_bar: ProgressBar
:type text: str
:type echo: bool or int or ProgressBar
:type echo_items: bool or list[str]
:rtype: Iterable
"""
return Iterable(inner=list(iter... | 261edb6bb841b89a3248c7ab3530a55d385fcce0 | 3,603,750 |
def chebgrid3d(x, y, z, c):
"""
Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
This function returns the values:
.. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)
where the points `(a, b, c)` consist of all triples formed by taking
`a` from `x`,... | 01a07cddcacd9fbe7564ff3edc83d1bab8f13f2a | 3,603,751 |
import argparse
from basis import base
def _parser_options():
"""Parses the options and arguments from the command line."""
#We have two options: get some of the details from the config file,
pdescr = "1D Quantum Potential Solver."
parser = argparse.ArgumentParser(parents=[base.bparser], description=p... | 505f0bd60beea778e18c6c64dc9b7c1e525ff47f | 3,603,752 |
def gen_wind_speed(interval):
"""
Generate the wind speed graph.
:params interval: update the graph based on an interval
"""
total_time = get_current_time()
df = get_wind_data(total_time - 200, total_time)
trace = go.Scatter(
y=df["Speed"],
line={"color": "#42C4F7"},
... | 375c4fccbf6e942a6f2a6b24fbc92343fe3921eb | 3,603,753 |
import string
import random
import logging
def random_pass():
"""Function to create random RDS database password"""
try:
letters = string.ascii_letters
numbers = string.digits
special_chars = string.punctuation
dummy_phrase = (''.join(random.choice(letters + numbers + special_... | b6aaf00069a269e09b2d8d96251741c54709bffa | 3,603,754 |
from typing import Callable
from typing import Any
def is_empty_() -> Callable[[Observable[Any]], Observable[bool]]:
"""Determines whether an observable sequence is empty.
Returns:
An observable sequence containing a single element
determining whether the source sequence is empty.
"""
... | 9dc1f2e0de088d2026293943b53a81f3ce3680ef | 3,603,755 |
import os
def makedirs(name, exist_ok=False, **kwargs):
"""
Make the directories in the given path. The ``exist_ok`` argument was
added in python 3.2+.
"""
if not (exist_ok and os.path.exists(name)):
os.makedirs(name, **kwargs)
return name | aabea356ed392eb26117f25b0918e80b1dd6a5eb | 3,603,756 |
def api_burst_call(request):
"""API burst call"""
if request.method == 'POST':
if request.user.is_authenticated():
now = timezone.now()
lastcall = request.user.profile.lastcall
if now - timezone.timedelta(days=5) > lastcall:
if now.weekday() == 4 or no... | 6d253c43f3fd67b9845d7f563b80938063694023 | 3,603,757 |
def query_header_jwt_required(fn):
"""
A decorator to protect a query resolver.
If you decorate an resolver with this, it will ensure that the requester
has a valid access token before allowing the resolver to be called. This
does not check the freshness of the access token.
"""
@wraps(fn)... | a483617ffd73a20978bcce3b13c36f0f05d32845 | 3,603,758 |
import threading
def concurrent_map(func, data):
"""
Similar to the bultin function map(). But spawn a thread for each argument
and apply `func` concurrently.
Note: unlike map(), we cannot take an iterable argument. `data` should be an
indexable sequence.
"""
N = len(data)
result = [... | 5fb482055699087ca7f7b3b95b7d8c425894882f | 3,603,759 |
from typing import Dict
from typing import Any
def _node_type_from_group_spec(
group_spec: Dict[str, Any], is_head: bool
) -> Dict[str, Any]:
"""Converts CR group spec to autoscaler node type."""
if is_head:
# The head node type has no workers because the head is not a worker.
min_workers ... | 950d74fec20bf61c42e1497df5d168a55d7eb71b | 3,603,760 |
def pack_quotes(quotes, **kwargs):
"""
:param quotes: a list of BeautifulSoup tags containing quotes, and quote details
:return: a dictionary of packaged quotes
"""
packed_quotes = {}
for group in quotes:
raw = group.select_one(kwargs.get('quotetag'))
raw_quote = raw.string
... | 011382f79572fedd0c40f10952d71c77ba25ae37 | 3,603,761 |
import os
from shutil import copyfile
def get_best_config(result_folder):
"""
Select winning config, copy its yaml file into result_folder
and returns parsed winning args
"""
ids = [str(el) for el in range(10)]
dirs = [el for el in os.listdir(result_folder) \
if os.path.isdir(os.p... | 73ad3d68f79cd20d6715dd0300f196a4b3104e31 | 3,603,762 |
def handleRespReadMultHR(payload):
""" Handles a MODBUS response of multiple holding registers reading (fn code 3). """
values = payload[1:]
tmp = []
while True:
try:
req = READ_QUEUE["HoldingRegister"].pop(0)
value = int.from_bytes(values[:2], byteorder="big")
... | eb4ee35b9fbb0b4f9b076b07848cafe95acddea5 | 3,603,763 |
def van_vleck_weisskopf(νeval, ν, γ, δ):
"""Complex Van Vleck-Weisskopf line shape function.
νeval GHz frequency at which line shape is evaluated
ν GHz center frequency of line
γ GHz width parameter of line
δ - overlap parameter of line
Returned value is u... | f2f221196fbe911d4582cfc74bf260bb87ce7db0 | 3,603,764 |
def exists_management_key_with_priority_zero(
active_management_keys, new_management_keys, management_keys_to_revoke
):
"""
Checks if a management key of priority zero would be present if the management keys will be updated according
to the given parameters.
Parameters
----------
active_man... | e4bff322bf4cb9d4b6ccc002f277a5af63e993e4 | 3,603,765 |
from typing import Tuple
from typing import Dict
from typing import Any
def multiview() -> Tuple["MultiViewMount", ComponentConstructor]:
"""Dynamically add components to a layout on the fly
Since you can't change the component functions used to create a layout
in an imperative manner, you can use ``mult... | 3ce29da959f1e692a0e0754d3d585130551b1bd3 | 3,603,766 |
import glob
def create_df():
"""Return a Pandas Dataframe containing the path to every Garmin
.TCX file and its date in the local time zone---instead of the UTC
time standard."""
lst_files = glob.glob(path_to_garmin_files + '*.tcx')
lst_dates = [get_date_from_filename(f) for f in lst_files]
df... | 085be3b525c85653a4e61bef262bb5999962974e | 3,603,767 |
def get_str_volume_list():
"""Return a list of string representations of all volumes."""
return [volume.string_representation for volume in get_volume_list()] | 1fc5fa33ea180ef3967732e61420e0a8ba24d362 | 3,603,768 |
import numpy
def create_empty_trace(trace, channel):
"""
Utility to create an empty trace, similar to another trace.
Parameters
----------
trace: obspy.core.Trace
Trace that is source of most metadata, including array length.
channel: String
Channel name for created Trace.
... | 46f90f7ac79683a1e34cbd0340c5787941951fcc | 3,603,769 |
def simulate_episode(org_ep, model_ep, maze_params_ep, dyna_params_ep, episode_ep, run_ep, diagnostics_instance_ep):
"""
Function for simulating a single episode.
:param org_ep: an organization instance containing all information about the organization
:param model_ep: model instance for planning
:p... | 94df4ea9529ed5da7b9e4a87bcda2dbd78658de1 | 3,603,770 |
import os
def get_files_recursively(directory):
"""
Get a list of the absolute paths of all the files present in a direcory, recursively
"""
files = []
for base_path, _, sub_files in os.walk(directory):
# make relative paths
if directory.endswith("/"):
files += [ os.pat... | 03ff3967b8061232386910c36f6a80a806fca50a | 3,603,771 |
import re
def is_valid_username(field):
"""
Checks if it's an alphanumeric + underscore, lowercase string, at least
two characters long, and starts with a letter, ends with alphanumeric
"""
return re.match(r"[a-z][0-9a-z_]*[a-z0-9]$", field) is not None | b4c870951715e103d58d1187703276dbb21e84cf | 3,603,772 |
import os
def create_path(path):
"""
This function receives a path and creates the directory in the case it doesn't exist
Arg:
csvfile (Path): path to a file
Return:
created_path: absolute Path to a created file
"""
# Split the path in
# dir and csvfile pair
... | dee201e7df29779a986230d897a17402777c0dd5 | 3,603,773 |
def distance_from_earth(R, z, theta, Rsun=8.2*u.kpc):
"""Convert radii, height and angle to a distance to the Earth using trig.
Parameters
----------
R : `float/array`
Galactocentric radius
z : `float/array`
Height above Galactic plane
theta : `float/array`
Azimuthal ang... | e134caf8b9121b51f74cb1179b22c1696f6bb40d | 3,603,774 |
from transitleastsquares import transitleastsquares
import glob
import os
def get_lk(TIC, path_plots='.', interactive=False, detrend=True, window=1501,
gp_detrend=False, from_fits=False, path_fits=None, noTLS=False, tofile=False,
tojuliet=False):
"""
Performs the computation for each sta... | 786d8c924bdcdc9584aa135b4a100ca4f1740c7e | 3,603,775 |
from typing import List
from typing import Tuple
def calculate_mark(data: List[Tuple[str, float]], weight: float) -> float:
""" Returns the average of all the marks in data with weights
:param: data: the List of entries of data. Each entry is in the form
(description, mark)
:weight: the weight of... | 49f911894f73515ff0073b29b83ee2cb95c02e10 | 3,603,776 |
from typing import OrderedDict
def transform_container_group(result):
"""Transform a container group to table output. """
return OrderedDict([('Name', result['name']),
('ResourceGroup', result['resourceGroup']),
('Status', _format_status(result)),
... | 2ccd013e8f645563481624b3076251a9cacdb4a0 | 3,603,777 |
def optional_interfaces(args, *interfaces):
"""Return a tuple with possible optional interfaces
:param args: a list of reactive interfaces
:param *interfaces: list of strings representing possible reactive
interfaces.
:returns: [list of reactive interfaces]
"""
return args + tuple(ri fo... | 33fc406fc93559d955793c18e9ee146c789ca587 | 3,603,778 |
import math
def weight(name, shape, init='he', range=None):
""" Initializes weight.
:param name: Variable name
:param shape: Tensor shape
:param init: Init mode. xavier / normal / uniform / he (default is 'he')
:param range:
:return: Variable
"""
initializer = tf.constant_initializer()... | 9762ecf2e38acf0960e0c22b65bc0676c684e856 | 3,603,779 |
def list_available_drivers(device_address=None):
"""
Returns a list of known drivers/packages for qwiic devices.
:param device_address: A list with an I2C address or addresses. If no value
was given, the I2C bus will be scanned and the address(es) of the
connected qwiic devi... | 1df8633d0db9b5b5f997ee810bce1cbe7c78da4d | 3,603,780 |
from donkeycar.parts.controller import get_js_controller as get_controller
def get_js_controller(cfg):
"""
myconfig.py上にて指定されたCONTROLLER_TYPE値にあわせて
ジョイスティックコントローラパーツを生成し、
オブジェクトを返却するファクトリ関数。
引数:
cfg config.py/myconfig.py にて指定された定義をインスタンス変数として
参照できるオブジェクト
戻り値
ctr ジョイ... | 5d63b67a2bceb23332599dd7402ca191891fe0c3 | 3,603,781 |
def rowSum_A(X, norm = False):
"""
[Added 22/10/2018]
Computes rowSum**2 for dense array efficiently, instead of using einsum
"""
n = len(X)
s = 0
for i in range(n):
s += X[i]**2
if norm:
s **= 0.5
return s | cd6b147fb171094d3a4a2e77c1d5e63b07a6e560 | 3,603,782 |
def get_shorthands(flat_search_config):
""" Convert flattened keys to shorthand notations for serialization str.
"""
shorthands = {}
for k in flat_search_config:
if not any(k.endswith(s) for s in RESERVED_SUFFIXES):
route = k.split(ROUTE_STR)
shorthand = ''
fo... | 74ec79dba294621c64e37427996d8382abba8212 | 3,603,783 |
import re
def get_name(view):
"""
Return a name for the view.
If view has a name attribute, use that, otherwise use the view's class name, with 'CamelCaseNames' converted to 'Camel Case Names'.
"""
# If we're looking up the name of a view callable, as found by reverse,
# grok the class insta... | 8cd2848d0166da45da4ee01e62c81bedd3a2067a | 3,603,784 |
import hashlib
def md5hash(fname):
"""Get md5 hash of a file using hashlib"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest() | fb0c1a7c79a5d9d6101aca9cd13f56fd914c457e | 3,603,785 |
def Rx(t):
"""
Generates the unitary rotation matrix about the X axis on the Bloch sphere.
"""
Sx = np.array([[0, 1], [1, 0]])
return expm(-1j * t * Sx / 2.0) | 5c3db7c663b3f97e08ea9f2be85e373cf8bd70f8 | 3,603,786 |
def _jit_rouse_homologs(N, N_tot, tether_list, loop_list, L, b, D, Aex, rx, ry,
rz, t, t_save, x0=None):
"""
"Inner loop" of rouse_homologs.
Some typing stuff: needs N, N_tot as int, needs tether_list/loop_list as
dtype == int64, and uses loop_list.shape[0] to get num_loops. Thi... | 53e6e54edd59bf385f98977f3e847103e3388eba | 3,603,787 |
def simplest_clique():
"""
Answer to "what is the simplest clique".
"""
return render_html("The simplest clique is an edge.") | d49217d7d627d6ff15c16bf0d2cbb6dd93d23acc | 3,603,788 |
def all_bits_list(vals, width=16):
"""Convert list of values into a list of bits in those values"""
return flatten_list([to_bit_list(val, width) for val in vals]) | 76a780ac78e423b9d2d6a691a87bec4e5fdb892c | 3,603,789 |
import math
def find_divisors(n):
"""
Find divisors of n
"""
#div = []
count = 0
sqrt_n = int(math.sqrt(n))
if sqrt_n**2==n:
count += 1
#div.append(sqrt_n)
for d in range(1, sqrt_n):
if n%d==0:
#div.append(d)
#div.append(n//d)
... | 8d6d0406024dae195c0f13db60e0a65bee93dd6c | 3,603,790 |
from ooiservices.app.uframe.status_tools import get_uid_digests
def build_uid_cache():
""" Force update of asset information.
"""
try:
uid_digests = get_uid_digests(refresh=True)
print '\n Completed compiling uid digests information.'
print '\n Number of digests: ', len(uid_digests... | 7f1e073b9018b8e89185ed11bb17cdb7fd9800e2 | 3,603,791 |
import numpy
def _diff_rasters(
a_raster_path, b_raster_path, target_diff_raster_path):
"""Calculate a-b.
Args:
a_raster_path (str): raster A, same nodata and size as B
b_raster_path (str): raster B
target_diff_raster_path (str): result of A-B accounting for nodata.
Retur... | 7f926861d80478b1773fc16188957f68935eb9ad | 3,603,792 |
def df_dx_func(x_id, s_x, corn_x, A):
"""
Computes derivatives to make the bicubic interpolation
When a query point is in the left or rightmost bin of the x axis, it
automatically ignores the knots that would have gone outside array
boundaries in the computation (this is done by a mask and tf.where,... | d3ed05359444960f59b0e3bbda4f8c3c68501aaa | 3,603,793 |
import random
def power_method(A, niter, y0=None, random_state=None):
"""Power iteration method. Definition 5.12."""
y0 = random.get_start_vector(d=A.shape[0], y0=y0, random_state=random_state)
x0 = nolina.normalise(y0)
for _ in range(niter):
y0 = A @ x0
sigma = -1 if np.dot(y0, x0) < ... | be3953630ec977d13dbd9724e5d17cae7b91be3b | 3,603,794 |
import sys
def map_annotations(experiment, sample, meta_dir, cv_map):
"""
Maps NCBI SRA annotations to controlled vocabularies.
This function creates both a JSON and tab delimited metadata file that
maps metadata from NCBI to known controlled vocabulary terms. The purpose
of this is to help ensur... | cca25408225658cbdca30c5e738acaa6d5c2c707 | 3,603,795 |
import subprocess
def get_md5sum(filename, remote_server=None):
"""Returns the md5 checksum of the given file."""
try:
command = ["md5sum", filename]
if remote_server is not None:
command = ["ssh", remote_server] + command
check = subprocess.run(command, stdout=subprocess.... | 29613662ecf8ec14093f3cee1a7d9fa57aeaa86a | 3,603,796 |
def _has_all(series, values, exclusive=False):
""" Returns the index of rows from series containing all of the given
values.
Parameters
----------
series : pandas.Series
The data to be queried
values : list-like
The values to be tested
Returns
-------
index : panda... | 805df8708d7e00ecbaf76ebdd99ce599e0ea004c | 3,603,797 |
import importlib
def load_plugin(name):
"""
:param name:
"""
return importlib.import_module(f"plugins.{name}", ".").run | 5631f51672dd8a4597a49b4336584e769577ff09 | 3,603,798 |
def sfn_execute(session, name, input_={}):
"""Start executing a StepFunction
Args:
session (Session): Boto3 session
name (str): Name of the StepFunction to execute
input_ (Json): Json input data for the first state to process
Returns:
(str): ARN of the state machine executi... | 65d469ee281fc952ff51f9341f2b8b5da3be8764 | 3,603,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.