content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_name(tree, from_='name'):
"""
Get the name (token) of the AST node.
:param tree ast:
:rtype: str|None
"""
# return tree['name']['name']
if 'name' in tree and isinstance(tree['name'], str):
return tree['name']
if 'parts' in tree:
return djoin(tree['parts'])
i... | 15,100 |
def pcaTable(labels,vec_mean,vec_std,val_mean,val_std):
"""Make table with PCA formation mean and std"""
header="\\begin{center}\n\\begin{tabular}{| l |"+" c |"*6+"}\\cline{2-7}\n"
header+="\\multicolumn{1}{c|}{} & \\multicolumn{2}{c|}{PC1} & \multicolumn{2}{c|}{PC2} & \multicolumn{2}{c|}{PC3} \\... | 15,101 |
def render_reference_page(conn: Connection, reference: str) -> str:
"""Create HTML section that lists all notes that cite the reference."""
sql = """
SELECT note, Bibliography.html,Notes.html FROM Citations
JOIN Notes ON Citations.note = Notes.id
JOIN Bibliography ON Bibliogr... | 15,102 |
def update_addresses():
"""
Update all AutoAddresses
"""
global _all_auto_addresses
for address in _all_auto_addresses:
address.update_address() | 15,103 |
def normalize_bridge_id(bridge_id: str):
"""Normalize a bridge identifier."""
bridge_id = bridge_id.lower()
# zeroconf: properties['id'], field contains semicolons after each 2 char
if len(bridge_id) == 17 and sum(True for c in "aa:bb:cc:dd:ee:ff"
if c == ":"):
... | 15,104 |
def describe_cached_iscsi_volumes(VolumeARNs=None):
"""
Returns a description of the gateway volumes specified in the request. This operation is only supported in the cached volume gateway types.
The list of gateway volumes in the request must be from one gateway. In the response, AWS Storage Gateway return... | 15,105 |
def pyc_file_from_path(path):
"""Given a python source path, locate the .pyc.
See http://www.python.org/dev/peps/pep-3147/
#detecting-pep-3147-availability
http://www.python.org/dev/peps/pep-3147/#file-extension-checks
"""
import imp
has3147 = hasattr(imp, 'get_tag'... | 15,106 |
def get_bytes_per_data_block(header):
"""Calculates the number of bytes in each 128-sample datablock."""
N = 128 # n of amplifier samples
# Each data block contains N amplifier samples.
bytes_per_block = N * 4 # timestamp data
bytes_per_block += N * 2 * header['num_amplifier_channels']
# ... | 15,107 |
def recovered():
"""
Real Name: b'Recovered'
Original Eqn: b'INTEG ( RR, 0)'
Units: b'Person'
Limits: (None, None)
Type: component
b''
"""
return integ_recovered() | 15,108 |
def Mux(sel, val1, val0):
"""Choose between two values.
Parameters
----------
sel : Value, in
Selector.
val1 : Value, in
val0 : Value, in
Input values.
Returns
-------
Value, out
Output ``Value``. If ``sel`` is asserted, the Mux returns ``val1``, else ``val0... | 15,109 |
async def test_websocket_update_prefs(
opp, opp_ws_client, mock_camera, setup_camera_prefs
):
"""Test updating preference."""
await async_setup_component(opp, "camera", {})
assert setup_camera_prefs[PREF_PRELOAD_STREAM]
client = await opp_ws_client(opp)
await client.send_json(
{
... | 15,110 |
def get_identity_list(user, provider=None):
"""
Given the (request) user
return all identities on all active providers
"""
identity_list = CoreIdentity.shared_with_user(user)
if provider:
identity_list = identity_list.filter(provider=provider)
return identity_list | 15,111 |
def test_elements():
"""Test simple dc."""
elements = [
('contributors', 'contributor'),
('coverage', 'coverage'),
('creators', 'creator'),
('dates', 'date'),
('descriptions', 'description'),
('formats', 'format'),
('identifiers', 'identifier'),
('... | 15,112 |
def read_links(database_path, search_string='', output_max=20, blob='links'):
"""Вывод схожих рассказов таблицей."""
database = sqlite3.connect(database_path)
cursor = database.cursor()
sql_list = get_blob(search_string, blob, cursor)
for n,sql_tuple in enumerate(sql_list,1):
print('# ------... | 15,113 |
def get_user_pool_domain(prefix: str, region: str) -> str:
"""Return a user pool domain name based on the prefix received and region.
Args:
prefix: The domain prefix for the domain.
region: The region in which the pool resides.
"""
return "%s.auth.%s.amazoncognito.com" % (prefix, regio... | 15,114 |
def database_fixture():
"""Delete all entries on users database before & after the test
"""
mongo_users.delete_many({})
yield mongo_users
mongo_users.delete_many({}) | 15,115 |
def test_get_ticket_context_additional_fields():
"""Unit test
Given
- additional keys of a ticket alongside regular keys.
When
- getting a ticket context
Then
- validate that all the details of the ticket were updated, and all the updated keys are shown in
the context wit... | 15,116 |
def corr_activity(ppath, recordings, states, nskip=10, pzscore=True, bands=[]):
"""
correlate DF/F during states with delta power, theta power, sigma power and EMG amplitude
:param ppath: base filder
:param recordings: list of recordings
:param states: list of len 1 to 3, states to correlate EEG pow... | 15,117 |
def add_dep_info(tgt_tokens, lang, spacy_nlp, include_detail_tag=True):
"""
:param tgt_tokens: a list of CoNLLUP_Token_Template() Objects from CoNLL_Annotations.py file
:param spacy_nlp: Spacy language model of the target sentence to get the proper Dependency Tree
:return:
"""
doc = spacy_nlp.to... | 15,118 |
async def apod(request: Request) -> dict:
"""Get the astronomy picture of the day."""
http_client = request.app.state.http_client
async with http_client.session.get(
f"https://api.nasa.gov/planetary/apod?api_key={NASA_API}"
) as resp:
data = await resp.json()
return {
"titl... | 15,119 |
def main_view(request, url, preview=False):
"""
@param request: HTTP request
@param url: string
@param preview: boolean
"""
url_result = parse_url(url)
current_site = get_site()
# sets tuple (template_name, posts_on_page)
current_template = get_template()
language = get_language... | 15,120 |
def parse_configs(code_config, field_config, time_config):
"""
Wrapper to validate and parse each of the config files. Returns a
a dictionary with config types as keys and parsed config files as values.
"""
# performing basic validation of config paths, obtaining dictionary of
# config types a... | 15,121 |
def butter_highpass_filter_eda(data):
""" High pass filter for 1d EDA data.
"""
b, a = eda_hpf()
y = lfilter(b, a, data)
return y | 15,122 |
def normalize_null_vals(reported_val):
"""
Takes a reported value and returns a normalized NaN is null, nan, empty, etc.
Else returns reported value.
"""
if is_empty_value(reported_val):
return np.NaN
else:
return reported_val | 15,123 |
def in_notebook() -> bool:
"""Evaluate whether the module is currently running in a jupyter notebook."""
return "ipykernel" in sys.modules | 15,124 |
def status(
cycle_id: str=A_(..., help='data load cycle id'),
bad_records_file: pathlib.Path = O_(
None,
'--bad_records_file',
help='file to use for storing rows that failed to load',
metavar='FILE.csv',
dir_okay=False,
resolve_path=True
),
**frontend_kw
)... | 15,125 |
def test_credential_property(mocker):
"""
GIVEN an attribute to make as a property
WHEN credential_property is called
THEN assert a property is returned
"""
val_mock = mocker.patch.object(messages._utils, 'validate_input')
param = credential_property('param')
assert isinstance(param, pro... | 15,126 |
def _clean_dls(limit, path=None):
"""Check that number of images saved so far is no more than `limit`.
Args:
limit: maximum number of downloads allowed in download directory.
path: path to saved images. Default to current working directory.
Raises:
ValueError: if `limit` is not an ... | 15,127 |
def test_insert(type):
"""
>>> test_insert(int_)
[0, 1, 2, 3, 4, 5]
"""
tlist = nb.typedlist(type, [1,3])
tlist.insert(0,0)
tlist.insert(2,2)
tlist.insert(4,4)
tlist.insert(8,5)
return tlist | 15,128 |
def get_next_month_range(unbounded=False):
"""获取 下个月的开始和结束时间.
:param unbounded: 开区间
"""
return get_month_range(months=1, unbounded=unbounded) | 15,129 |
def bedAnnotate_ceas(workflow, conf):
"""
Calls bedAnnotate to get the genome distribution of the summits
"""
import os
summits = conf.prefix + "_sort_summits.bed" if conf.get("macs2", "type") in ["both", "narrow"] else conf.prefix + "_b_sort_peaks.broadPeak"
ceas = attach_back(workflow, ShellCo... | 15,130 |
def probit_regression(
dataset_fn,
name='probit_regression',
):
"""Bayesian probit regression with a Gaussian prior.
Args:
dataset_fn: A function to create a classification data set. The dataset must
have binary labels.
name: Name to prepend to ops created in this function, as well as to the
... | 15,131 |
def test_unet_summary_generation() -> None:
"""Checks unet summary generation works either in CPU or GPU"""
model = UNet3D(input_image_channels=1,
initial_feature_channels=2,
num_classes=2,
kernel_size=1,
num_downsampling_paths=2)
i... | 15,132 |
def block_inception_c(inputs, scope=None, reuse=None):
"""Builds Inception-C block for Inception v4 network."""
# By default use stride=1 and SAME padding
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d],
stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockI... | 15,133 |
def from_json(js):
"""
Helper to parse json values from server into python types
"""
if js is None or js is True or js is False or isinstance(js, six.text_type):
# JsNull, JsBoolean, JsString
return js
if not isinstance(js, dict) or 'type' not in js or 'data' not in js:
rais... | 15,134 |
def exposexml(func):
"""
Convenience decorator function to expose XML
"""
def wrapper(self, data, expires, contentType="application/xml"):
data = func(self, data)
_setCherryPyHeaders(data, contentType, expires)
return self.templatepage('XML', data=data,
... | 15,135 |
def rect(left: float, top: float, right: float, bottom: float, image: Image = None):
"""
Draws a rectangle outline with upper left corner at (left, top) and lower right corner at (right,bottom).
The rectangle is not filled.
:param left: x coordinate value of the upper left corner
:param top: y coo... | 15,136 |
def err(*args):
""" Outputs its parameters to users stderr. """
for value in args:
sys.stderr.write(value)
sys.stderr.write(os.linesep) | 15,137 |
def _SetSource(build_config,
messages,
is_specified_source,
no_source,
source,
gcs_source_staging_dir,
ignore_file,
hide_logs=False):
"""Set the source for the build config."""
default_gcs_source = False
defau... | 15,138 |
def transform_categorical_by_percentage(TRAIN, TEST=None,
handle_unknown="error", verbose=0):
"""
Transform categorical features to numerical. The categories are encoded
by their relative frequency (in the TRAIN dataset).
To be consistent with scikit-learn tr... | 15,139 |
def buildDescription(flinfoDescription='', flickrreview=False, reviewer='',
override='', addCategory='', removeCategories=False):
"""Build the final description for the image.
The description is based on the info from flickrinfo and improved.
"""
description = '== {{int:filedesc}}... | 15,140 |
def allowed_file(filename, extensions):
"""
Check file is image
:param filename: string
:param extensions: list
:return bool:
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in extensions | 15,141 |
def read(infile):
"""Read result from disk."""
_, ext = os.path.splitext(infile)
ext = ext.strip('.')
return read_funcs[ext](infile) | 15,142 |
def _url_in_cache(url):
"""
Determine if a URL's response exists in the cache.
Parameters
----------
url : string
the url to look for in the cache
Returns
-------
filepath : string
path to cached response for url if it exists in the cache,
otherwise None
"""... | 15,143 |
def get_number_of_recovery_codes(userid):
"""
Get and return the number of remaining recovery codes for `userid`.
Parameters:
userid: The userid for which to check the count of recovery codes.
Returns:
An integer representing the number of remaining recovery codes.
"""
return d... | 15,144 |
def creation_time(path_to_file):
"""The file creation time.
Try to get the date that a file was created, falling back to when
it was last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
"""
if platform.system() == 'Windows':
return os.pa... | 15,145 |
async def mailbox_search(search_term: str, Authorize: AuthJWT = Depends(),Token = Depends(auth_schema)):
"""Search email with a search term"""
Authorize.jwt_required()
try:
return JSONResponse(dumps({"success": True, "email": database.search(search_term)}))
except Exception as err:
retur... | 15,146 |
def otel_service(docker_ip, docker_services):
"""Ensure that port is listening."""
# `port_for` takes a container port and returns the corresponding host port
port = docker_services.port_for("otel-collector", 4317)
docker_services.wait_until_responsive(
timeout=30.0, pause=5, check=lambda: is_p... | 15,147 |
def broadcast(vec: T.Tensor, matrix: T.Tensor) -> T.Tensor:
"""
Broadcasts vec into the shape of matrix following numpy rules:
vec ~ (N, 1) broadcasts to matrix ~ (N, M)
vec ~ (1, N) and (N,) broadcast to matrix ~ (M, N)
Args:
vec: A vector (either flat, row, or column).
matrix: A ... | 15,148 |
def neighbour_list_n_out(nlist_i: NeighbourList,
nlist_j: NeighbourList) -> np.ndarray:
"""
Compute n^out between two NeighbourList object.
Args:
nlist_i (NeighbourList): A NeighbourList object for neighbour lists at time 0.
nlist_j (NeighbourList): A NeighbourL... | 15,149 |
def split_if_then(source_file: str) -> dict:
"""Split a script file into component pieces"""
logging.debug("Splitting '{}' into IF/THEN blocks".format(source_file))
with open(source_file) as f:
source_text = f.read()
logging.debug("Read {} bytes".format(len(source_text)))
r = re.compile(_if... | 15,150 |
def add(ctx, project):
"""
This commands adds a project to primer
"""
confdir = ctx.obj['confdir']
project_path = pathlib.Path(project)
project_path = project_path.expanduser()
base = project_path.parent
name = project_path.name
salt_project = Project(confdir, base, name)
try:
... | 15,151 |
def save_as_geotiff(grid_x: np.ndarray, grid_y: np.ndarray, dx: float,
dy: float, rgb: np.ndarray, epsg: int, outfile: str):
"""
Save output image as geotiff using GDAL.
Parameters
----------
grid_x : np.ndarray
Grid x-coordinates.
grid_y : np.ndarray
Grid y-... | 15,152 |
def get_sql_injection_match_set(SqlInjectionMatchSetId=None):
"""
Returns the SqlInjectionMatchSet that is specified by SqlInjectionMatchSetId .
See also: AWS API Documentation
Examples
The following example returns the details of a SQL injection match set with the ID example1ds3t-46da-4fdb-b8... | 15,153 |
def id_label_to_project(id_label):
"""
Given a project's id_label, return the project.
"""
match = re.match(r"direct-sharing-(?P<id>\d+)", id_label)
if match:
project = DataRequestProject.objects.get(id=int(match.group("id")))
return project | 15,154 |
def test_querystring_args_clash():
"""
Cannot use any reserved or already used names for querystring args.
"""
# body_arg clash
with pytest.raises(ArgNameConflict):
APIEndpoint(
'GET',
'/users/{user_id}/feedback/',
querystring_args=[Arg('body')],
)... | 15,155 |
def payoff_blotto_sign(x, y):
"""
Returns:
(0, 0, 1) -- x wins, y loss;
(0, 1, 0) -- draw;
(1, 0, 0)-- x loss, y wins.
"""
wins, losses = 0, 0
for x_i, y_i in zip(x, y):
if x_i > y_i:
wins += 1
elif x_i < y_i:
losses += 1
if wins > losses:
... | 15,156 |
def import_trips(url_path, dl_dir, db_path, taxi_type, nrows=None, usecols=None,
overwrite=False, verbose=0):
"""Downloads, cleans, and imports nyc tlc taxi record files for the
specified taxi type into a sqlite database.
Parameters
----------
url_path : str or None
Path to... | 15,157 |
def _delete_br_cfg_file(bridge):
""" Deletes the config file for the specified bridge.
Args:
bridge (str) bridge name
"""
opsys = platform.dist()[0]
LOG.debug('OS: ' + opsys)
if opsys not in ('Ubuntu', 'redhat'):
LOG.error('Unsupported Operating System')
sys.exit('Unsuppo... | 15,158 |
def main():
""" Load point clouds and visualize """
pcds_down = load_point_clouds(pcd_folder, pointcloud_ext, voxel_size)
if showPlots:
o3d.visualization.draw_geometries(pcds_down,
zoom=0.7,
front=[0.4257, -0.2125, -0.8795],
... | 15,159 |
def householder(h_v: Vector) -> Matrix:
"""Get Householder transformation Matrix"""
return Matrix.identity(h_v.size()).subtract(2 * h_v * h_v.transpose() / (h_v * h_v)) | 15,160 |
def save_crater_records(xcoord_data, ycoord_data, radius, \
xcoord_canvas, ycoord_canvas, scaler):
"""Opens a file, or creates if it doesn't already exist, and
appends the x and y coords, and radius found from selection.
Parameters
----------
xcoord_data : string/float
... | 15,161 |
def _suppression_loop_body(boxes, iou_threshold, output_size, idx):
"""Process boxes in the range [idx*_NMS_TILE_SIZE, (idx+1)*_NMS_TILE_SIZE).
Args:
boxes: a tensor with a shape of [batch_size, anchors, 4].
iou_threshold: a float representing the threshold for deciding whether boxes
overlap too much... | 15,162 |
def calculate_invalidation_digest(requirements: Iterable[str]) -> str:
"""Returns an invalidation digest for the given requirements."""
m = hashlib.sha256()
inputs = {
# `FrozenOrderedSet` deduplicates while keeping ordering, which speeds up the sorting if
# the input was already sorted.
... | 15,163 |
def to_base_str(n, base):
"""Converts a number n into base `base`."""
convert_string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < base:
return convert_string[n]
else:
return to_base_str(n // base, base) + convert_string[n % base] | 15,164 |
def number_of_photons(i,n=6):
"""Check if number of photons in a sample is higher than n (default value is 6)"""
bitstring = tuple(i)
if sum(bitstring) > n:
return True
else:
return False | 15,165 |
def close_browser(driver):
"""
Close Selenium WebDriver
Args:
driver (Selenium WebDriver)
"""
logger.info("Close browser")
take_screenshot(driver)
driver.close() | 15,166 |
def _build_conflicts_from_states(
trackers: List[TrackerWithCachedStates],
domain: Domain,
max_history: Optional[int],
conflicting_state_action_mapping: Dict[int, Optional[List[Text]]],
tokenizer: Optional[Tokenizer] = None,
) -> List["StoryConflict"]:
"""Builds a list of `StoryConflict` objects... | 15,167 |
def recombine_dna_ocx1(dna1: DNA, dna2: DNA, i1: int, i2: int) -> None:
"""Ordered crossover."""
copy1 = dna1.copy()
replace_dna_ocx1(dna1, dna2, i1, i2)
replace_dna_ocx1(dna2, copy1, i1, i2) | 15,168 |
def inception_d(input_layer, nfilt):
# Corresponds to a modified version of figure 10 in the paper
"""
Parameters
----------
input_layer :
nfilt :
Returns
-------
"""
l1 = bn_conv(input_layer, num_filters=nfilt[0][0], filter_size=1)
l1 = bn_conv(l1, num_filters=nfilt[0][1]... | 15,169 |
def generate_response(response, output):
"""
:param response:
:return dictionary
"""
status, command = None, None
if isinstance(response, dict):
status = response.get('ok', None)
response.get('command', None)
elif isinstance(response, object):
status = getattr(respo... | 15,170 |
def check_add_predecessor(data_predecessor_str_set, xml_data_list, xml_chain_list, output_xml):
"""
Check if each string in data_predecessor_str_set is corresponding to an actual Data object,
create new [Data, predecessor] objects lists for object's type : Data.
Send lists to add_predecessor() to write ... | 15,171 |
def try_wrapper(func, *args, ret_=None, msg_="", verbose_=True, **kwargs):
"""Wrap ``func(*args, **kwargs)`` with ``try-`` and ``except`` blocks.
Args:
func (functions) : functions.
args (tuple) : ``*args`` for ``func``.
kwargs (kwargs) : ``*kwargs`` for ``func``.
ret_ (any... | 15,172 |
def main():
"""Execute Nornir Script."""
print_result(west_region.run(task=example_global_lock))
print_result(west_region.run(task=example_edit_config))
print_result(west_region.run(task=example_unlock)) | 15,173 |
def hnet_bsd(args, x, train_phase):
"""High frequency convolutions are unstable, so get rid of them"""
# Sure layers weight & bias
order = 1
nf = int(args.n_filters)
nf2 = int((args.filter_gain)*nf)
nf3 = int((args.filter_gain**2)*nf)
nf4 = int((args.filter_gain**3)*nf)
bs = args.batch_s... | 15,174 |
def hdrValFilesToTrainingData(input_filebase: str, target_varname: str):
"""Extracts useful info from input_filebase.hdr and input_filebase.val
Args:
input_filebase -- points to two files
target_varname -- this will be the y, and the rest will be the X
Returns:
Xy: 2d array [#vars][#samp... | 15,175 |
def save_screenshot_on_exception(driver: WebDriver):
"""
Context manager. Upon a ``WebDriverException`` exception,
it saves a screenshot and re-raise the exception.
:param driver: ``WebDriver`` instance
"""
try:
yield
except WebDriverException as exc:
save_screenshot(driver,... | 15,176 |
def create_column(number_rows: int, column_type: ColumnType) -> pd.Series:
"""Creates a column with either duplicated values or not, and either of string or int type.
:param number_rows: the number of rows in the data-frame.
:param column_type: the type of the column.
:returns: the data-frame.
"""
... | 15,177 |
def abspath(url):
"""
Get a full path to a file or file URL
See os.abspath
"""
if url.startswith('file://'):
url = url[len('file://'):]
return os.path.abspath(url) | 15,178 |
def test_password_modify(client):
"""
Test modifying password with simple modify operation and
password policy.
"""
cli = LDAPClient(client.url)
user_dn = "cn=jeff,ou=nerdherd,dc=bonsai,dc=test"
cli.set_password_policy(True)
cli.set_credentials("SIMPLE", user_dn, "p@ssword")
conn, _ ... | 15,179 |
def PumpEvents(timeout=-1, hevt=None, cb=None):
"""This following code waits for 'timeout' seconds in the way
required for COM, internally doing the correct things depending
on the COM appartment of the current thread. It is possible to
terminate the message loop by pressing CTRL+C, which will raise
... | 15,180 |
def check_mix_up(method):
"""Wrapper method to check the parameters of mix up."""
@wraps(method)
def new_method(self, *args, **kwargs):
[batch_size, alpha, is_single], _ = parse_user_args(method, *args, **kwargs)
check_value(batch_size, (1, FLOAT_MAX_INTEGER))
check_positive(alpha,... | 15,181 |
def generate_motif_distances(cluster_regions, region_sizes, motifs, motif_location, species):
"""
Generates all motif distances for a lsit of motifs
returns list[motif_distances]
motif_location - str location that motifs are stored
species - str species (for finding stored motifs)
... | 15,182 |
def test_list_users_rabbitmq3():
"""
Test if it return a list of users based off of rabbitmqctl user_list.
"""
mock_run = MagicMock(
return_value={
"retcode": 0,
"stdout": "guest\t[administrator user]\r\nother\t[a b]\r\n",
"stderr": "",
}
)
wit... | 15,183 |
def sig_to_vrs(sig):
""" Split a signature into r, s, v components """
r = sig[:32]
s = sig[32:64]
v = int(encode_hex(sig[64:66]), 16)
# Ethereum magic number
if v in (0, 1):
v += 27
return [r, s, v] | 15,184 |
def index_to_string_table_from_tensor(mapping, default_value="UNK", name=None):
"""Returns a lookup table that maps a `Tensor` of indices into strings.
This operation constructs a lookup table to map int64 indices into string
values. The mapping is initialized from a string `mapping` 1-D `Tensor` where
each el... | 15,185 |
def test_profile_reader_no_aws_config(monkeypatch, tmp_path, capsys):
"""Test profile reader without aws config file."""
fake_get_path_called = 0
def fake_get_path():
nonlocal fake_get_path_called
fake_get_path_called += 1
return tmp_path
monkeypatch.setattr(awsswitch, "get_pat... | 15,186 |
def get_exclusion_type(exclusion):
"""
Utility function to get an exclusion's type object by finding the exclusion type that has the given
exclusion's code.
:param exclusion: The exclusion to find the type for.
:return: The exclusion type if found, None otherwise.
"""
for exclusion_type in E... | 15,187 |
def generatePlans(update):
"""
For an update object provided this function references the updateModuleList which lets all exc
modules determine if they need to add functions to change the state of the system when new
chutes are added to the OS.
Returns: True in error, as in we should stop with thi... | 15,188 |
def get_str_by_path(payload: Dict, path: str) -> str:
"""Return the string value from the dict for the path using dpath library."""
if payload is None:
return None
try:
raw = dpath_util.get(payload, path)
return str(raw) if raw is not None else raw
except (IndexError, KeyError, ... | 15,189 |
def get_token_from_code(request):
"""
Get authorization code the provider sent back to you
Find out what URL to hit to get tokens that allow you to ask for
things on behalf of a user.
Prepare and send a request to get tokens.
Parse the tokens using the OAuth 2 client
"""
code = reque... | 15,190 |
def DeWeStartCAN(nBoardNo, nChannelNo):
"""Dewe start CAN"""
if f_dewe_start_can is not None:
return f_dewe_start_can(c_int(nBoardNo), c_int(nChannelNo))
else:
return -1 | 15,191 |
def register_onnx_magics(ip=None): # pragma: no cover
"""
Register magics function, can be called from a notebook.
@param ip from ``get_ipython()``
"""
if ip is None:
from IPython import get_ipython
ip = get_ipython()
ip.register_magics(OnnxNotebook) | 15,192 |
def mw_wo_sw(mol, ndigits=2):
"""Molecular weight without salt and water
:param ndigits: number of digits
"""
cp = clone(mol) # Avoid modification of original object
remover.remove_water(cp)
remover.remove_salt(cp)
return round(sum(a.mw() for _, a in cp.atoms_iter()), ndigits) | 15,193 |
def get_contact_list_info(contact_list):
"""
Get contact list info out of contact list
In rgsummary, this looks like:
<ContactLists>
<ContactList>
<ContactType>Administrative Contact</ContactType>
<Contacts>
<Contact>
... | 15,194 |
def enableLegacyLDAP(host, args, session):
"""
Called by the ldap function. Configures LDAP on Lagecy systems.
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the ldap subcommand
@param session: the active session to ... | 15,195 |
def retrieve_panelist_appearance_counts(panelist_id: int,
database_connection: mysql.connector.connect
) -> List[Dict]:
"""Retrieve yearly apperance count for the requested panelist ID"""
cursor = database_connection.cursor()
qu... | 15,196 |
def set_blueprint(blueprint: Blueprint):
"""
Plugins factory method to set a blueprint.
:param blueprint:
"""
global bp
bp = blueprint
from . import routes | 15,197 |
def chart(
symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"),
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2009, 12, 31), # data stops at 2013/1/1
normalize=True,
):
"""Display a graph of the price history for the list of ticker symbols provided
Arguments:
symbols... | 15,198 |
def create_table(peak_id, chrom, pstart, pend, p_center, min_dist_hit, attrib_keys, min_pos, genom_loc, ovl_pf, ovl_fp, i):
"""Saves info of the hit in a tabular form to be written in the output table. """
if attrib_keys != ["None"]:
# extract min_dist_content
[dist, [feat, fstart, fend, str... | 15,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.