content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
from typing import Dict
def from_file(archive: PathOrTarFile) -> Optional[Dict]:
"""Load and parse CRAN package archive
Args:
archive (PathOrTarFile): path to archive or `tarfile.TarFile` instance
Returns:
(dict): Dictionary of R package metadata
"""
re... | b4e0c24bfc0c7489be27da23fcc5c3431273d932 | 34,453 |
from google.cloud import bigquery
def to_google_cloud_bigquery(pandas_gbq_schema):
"""Given a schema in pandas-gbq API format,
return a sequence of :class:`google.cloud.bigquery.schema.SchemaField`.
"""
# Need to convert from JSON representation to format used by client library.
schema = add_defa... | 519c6314889c1ca0bca747e2f5784ac00bf94aed | 34,454 |
def update_exception_behavior(behavior_input, id):
"""
Executes a "update exception behavior" mutation with graphql-client
:param behavior_input: the behavior input
:param id: The id of the behavior to update
:return: Server response
"""
behavior_variables = {
"behaviorInput": behavi... | b8046c2a2a64e66e73159f2f19137bd7b8ab9097 | 34,455 |
def ps_dim(tasks):
"""
Dimension a Polling Server such that it fits into the provided task set.
Parameters
----------
tasks : list of pSyCH.tasks.Periodic
Task set whose schedulability is to be checked.
Returns
-------
sched : bool
True if the task set is schedulable, F... | 458b77bd5bb32ddd5c7002f872d0ed4e22642c4c | 34,456 |
def signature(obj, *, follow_wrapped=True):
"""Get a signature object for the passed callable."""
return Signature.from_callable(obj, follow_wrapped=follow_wrapped) | cec0e2d7bcf6cd3347bcd06ef58f33a0c65bdb94 | 34,457 |
def create_sys(Model, size, epsi, dens, init, bd_cond='periodic'):
"""Creates a instance of the LdftModel `Model` under the parameters `size`,
`epsi`, `dens`. The `init`-parameter determines the initial density profile
of the created system.
Parameters
----------
Model : `class`
The... | d30ae63022934e668c0ef90a72c91713caa6a228 | 34,459 |
def limit(resource, value):
"""
Check if this is a valid limit for the number of matching resources to be specified.
:param resource:
:type resource:
:param value: specified limit
:type value: int
:return: True if valid limit, False otherwise
:rtype: bool
"""
return value > 0 | 3ee75e7e41752e2bddebb94915bbf9161e02caec | 34,460 |
import gc
def sequence(values, rasts):
"""
Iterates through a sequence of linearly interpolated rasters.
Args:
values:
The unknown values for which new rasters will be interpolated and returned.
rasts:
A dictionary of the known values and rasters between which the ... | 6ff4d0f192f1bc92030693aba4e903378d06b636 | 34,461 |
def is_native_xmon_op(op: cirq.Operation) -> bool:
"""Check if the gate corresponding to an operation is a native xmon gate.
Args:
op: Input operation.
Returns:
True if the operation is native to the xmon, false otherwise.
"""
return isinstance(op, cirq.GateOperation) and is_native... | 41189dc252c766669127129e4a801f13b93a33fb | 34,462 |
def mono_extractor(b_format, azis=None, eles=None, mode='beam'):
"""
:param b_format: (frames, channels) IN SN3D
:param mode: 'beamforming' or 'omni'
:return:
"""
frames, channels = b_format.shape
x = np.zeros(frames)
if mode == 'beam':
# MaxRE decoding
b_format_n... | edaf426546a41dd3bb4afcb95e28dcfe93e20044 | 34,463 |
def get_ranking_order_switches(list):
"""list has to be list of quadruples (obs_id, sent_id, score, rank) output from get_ranks function
as in Ranking-Based Evaluation of Regression Models, Rosset et al."""
ranking_order_switches=0
#itearte over list, get observation i
n = len(list)
for i in ran... | f87e8e07bdde631747454ddd27a79e81ed3b5c6f | 34,464 |
def b58_to_bytes(val: str) -> bytes:
"""
Convert a base 58 string to bytes
"""
return base58.b58decode(val) | 49f4634a4c44f162aca242e5ccf41239926af504 | 34,465 |
def generate_sphere(phi, theta, r):
"""
Generate points for structured grid for a spherical shell volume.
This method is useful for generating a structured cylindrical mesh for VTK.
:param phi: azimuthal angle array
:param theta: polar angle array
:param r: radius of sphere
:return: grid poi... | 3de54ecdc22c056d5ec3a3d979573b4e4cf0e893 | 34,466 |
def get_target_langs(request):
"""
Get Target Languages for a CI Pipeline
:param request: Request object
:return: HttpResponse object
"""
if not request.is_ajax():
return HttpResponse("Not an Ajax Call", status=400)
post_params = request.POST.dict()
ci_pipeline = post_params.get... | f7b663b26012505568b5d49b81903951ad4842ac | 34,467 |
def page_list_return(total, current=1):
"""
page
分页,返回本次分页的最小页数到最大页数列表
"""
min_page = current - 4 if current - 6 > 0 else 1
max_page = min_page + 6 if min_page + 6 < total else total
return range(min_page, max_page + 1) | 99b099a7e90e1e150881d93129b1558eb8bc9a20 | 34,469 |
import time
def get_deployment_dates(site, node, sensor, deploy):
"""
Based on the site, node and sensor names and the deployment number, determine the start and end times for a
deployment.
:param site: Site name to query
:param node: Node name to query
:param sensor: Sensor name to query
... | cbc91ea8518184a40c1e8d35bacc1deebab3e768 | 34,472 |
def delete_documents_by_filter(filters: FilterRequest):
"""
Can be used to delete documents from a document store.
:param filters: Filters to narrow down the documents to delete.
Example: '{"filters": {{"name": ["some", "more"], "category": ["only_one"]}}'
To delete ... | d69f6d390544d61666a576c1a84d4721bad6ad5a | 34,473 |
def ensure_credential_server_running( foreground=False, run_once=False ):
"""
Instantiate our credential server and keep it running.
"""
# is the watchdog running?
pids = syndicate_watchdog.find_by_attrs( "syndicate-credential-server-watchdog", {} )
if len(pids) > 0:
# it's running
ret... | 2a55534f29509ad275d350db534c7ab158388278 | 34,475 |
import glob
def load_dbc(folder, verbose=True):
"""
Load all dbc files from specified folder add to dbc database.
Parameters
----------
folder : str
Absolute or relative path to folder, which contains dbc files.
verbose : bool, optional
Set to False to have no readout. The def... | 62b062d1f48021317f99cd46dad6ad697d0ec4a9 | 34,476 |
def unique_timestamps(data):
"""
Identify unique timestamps in a dataframe
:param data: dataframe. The 'Time' column is used by default
:returns: returns a sorted numpy array
"""
unique_timestamps = sorted(data['Time'].unique())
return unique_timestamps | 4e8b86643e4c976d51e39663ffefc95ec2be0e55 | 34,477 |
def printf_format_for_type(t, types):
""" Returns a format string for printing the given type
(either atomic or struct). """
description = type_description(t, types)
if "struct" in description:
specifer = printf_format_for_struct(t, types)
else:
specifer = description["printf_specifi... | 6647cfa80934e345f269b4d4afa69e95f0d8928d | 34,478 |
def get_operator_artifact_type(operatorArtifactString):
"""get_operator_artifact_type takes a yaml string and determines if it is
one of the expected bundle types.
:param operatorArtifactString: Yaml string to type check
"""
# Default to unknown file unless identified
artifact_type = UNKNOWN_F... | 50e14ff39e8c4e7258c0f305cf8a05973c836d3a | 34,479 |
def is_occ_conflict_exception(e):
"""
Is the exception an OccConflictException?
:type e: :py:class:`botocore.exceptions.ClientError`
:param e: The ClientError caught.
:rtype: bool
:return: True if the exception is an OccConflictException. False otherwise.
"""
is_occ = e.response['Error... | 3df46480341b617570e1e980ade194c9bd3fb26e | 34,480 |
def replace_list_element(l, before, after):
"""Helper function for get_cluster_idx
"""
for i, e in enumerate(l):
if e == before:
l[i] = after
return l | b15f43332efdcec878fbd16df64d46b1e23d2630 | 34,481 |
def hit_counter_from_list(filenames, barcode):
"""
:param filenames: all files from a single barcode - just the same hit_counter but for a list of filenames
:param barcode: the barcode associated to our experiment
:return: a dict {genome:hits}
"""
genomes = dict()
for name in filenames:
... | ed85426ed654399a10434a4d1c4d97cd603368c1 | 34,482 |
def average(v):
"""
:param v: a list of numerical values
:return: average for a list of values expressed as a float
"""
return sum(v) * 1.0 / len(v) | cbc9e450ee854289c62b613c257655fcd0c3e62c | 34,483 |
def get_all_projects_of_type(project_type: int):
"""Get the project ids for active and inactive projects in Firebase DB."""
project_id_list = []
fb_db = firebaseDB()
# we neglect private projects here
# since there are no projects set up in production yet
status_list = ["active", "inactive"]
... | ed5211bcab68139de79c262d2f61c5e62e714610 | 34,484 |
import typing
def set_engine(filename, *,
resolve: bool = False,
require: bool = False,
title: typing.Optional[str] = None,
title_memory_tag: str = _globals.MEMORY_TAG):
"""Return new sqlite3 engine and set it as default engine for treedb."""
log.inf... | eebd51176d8b4533af810d2f27cd4e48ea6bf316 | 34,485 |
def camel_split(string):
# test: (str) -> str
"""
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees')))
('the', 'Birds', 'And', 'The', 'Bees')
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees123')))
('the', 'Birds', 'And', 'The', 'Be... | d001f42b103ad911c92256bd326a3d478fc8f424 | 34,486 |
def iSP(a: Point, b: Point, c: Point) -> Turn:
"""iSP
Determine the positional relationship of the three Points.
Returns
-------
Turn direction
"""
flg = sign((b - a).det(c - a))
if flg == 1:
return Turn.CCW
elif flg == -1:
return Turn.CW
else:
if si... | 80143dcb4d3b6985cae49208193ee9662b4e5edb | 34,487 |
def generatePathsACS(ants: list, graph: np.ndarray, H: np.ndarray, P: np.ndarray, alpha: float,
beta: float, decay: float, pher_init: float, Q: float,
exp_heuristic: bool = True) -> list:
"""
Function that performs the exploration of the graph using the Ant Colony Syste... | 36cdd05ab9b403203603851403b85e502c614905 | 34,488 |
def get_comments(user):
"""Returns all of the user's comments"""
comments = ''
for comment in user.get_comments(limit=None):
comments = comments + ' ' + comment.body
return comments | cb095b78a2ac304c849e75a7b988c581a826aef1 | 34,491 |
def is_supported():
"""Get whether Dialite is supported for the current platform."""
return not isinstance(_the_app, StubApp) | 67846bf87c1b7c3ceda7bf6eb1090f55f9bd6453 | 34,492 |
def _check_axes_range(axes, ndim):
"""
Check axes are within the number of dimensions of tensor x and normalize the negative axes.
Args:
axes (Union[int, tuple(int), list(int)]): Axes of the tensor.
ndim (int): The number of dimensions of the tensor.
Return:
Axes (Union[int, tupl... | 135b7b729b5e207c5b97de14a32035d291765c2e | 34,493 |
def cm_LU_USGS24():
"""Land use colormap.
https://github.com/blaylockbk/pyBKB_v2/blob/master/BB_cmap/landuse_colormap.py
# MUST SET VMAX AND VMIN LIKE THIS TO SCALE COLOR RANGE CORRECTLY
cm, labels = LU_MODIS21()
plt.pcolormesh(LU_INDEX, cmap=cm, vmin=1, vmax=len(labels) + 1)
"""
C =... | 4f5eb1cce0f4fddc88712d8e2863a8b8593e3cba | 34,495 |
import functools
def lazy_value(fce):
""" The decorator for only once computed value. Same a functools.cache,
but there is no need to take care of arguments.
"""
x = []
""" Hack for staticmethod decorator, which is in fact binded by the descriptor protocol """
if isinstance(fce, staticmet... | dd983e23b036f5d2c7fbe98e048973c894378d97 | 34,496 |
def identity_by_descent(dataset, maf=None, bounded=True, min=None, max=None) -> Table:
"""Compute matrix of identity-by-descent estimates.
.. include:: ../_templates/req_tvariant.rst
.. include:: ../_templates/req_biallelic.rst
Examples
--------
To calculate a full IBD matrix, using minor al... | 7d8a0a2015955d19046835dcbf0f2ae60e937aa4 | 34,497 |
def sanitize_cloud(cloud: str) -> str:
"""Fix rare cloud layer issues"""
if len(cloud) < 4:
return cloud
if not cloud[3].isdigit() and cloud[3] not in ("/", "-"):
# Bad "O": FEWO03 -> FEW003
if cloud[3] == "O":
cloud = cloud[:3] + "0" + cloud[4:]
# Move modifiers ... | 7ec10be12ac2bc1a305688b31125af11a734c327 | 34,498 |
def list_permission(request):
"""显示权限名称的列表"""
tpl_name = 'user/list_permission.html'
perms = Permission.objects.all()
info = {'perms':perms}
return render(request,tpl_name,info) | 1fc388516789ab594d12080b7d8beeb5afa50220 | 34,499 |
def compute_sphercial_clustering_loss(centroids, features, batch_memberships):
"""Compute repulsive chain loss
Args:
features: [B, C] l2 normalized data, cf) B: batch size, C: feature dimension
memberships (int): [B, ] current membership
centroids: [K, C] cluster centers
... | 23fd09308af857f463c304b62dc0bb86dd89adb2 | 34,500 |
from typing import Union
import typing
def av_client_start(
tutk_platform_lib: CDLL,
session_id: Union[int, c_int],
username: bytes,
password: bytes,
timeout_secs: int,
channel_id: int,
) -> typing.Tuple[c_int, c_uint]:
"""Start an AV client.
Start an AV client by providing view accou... | 95058f251163e987ce6eecf3646413352f6b4a8c | 34,501 |
def balance_data(data):
""" DEPRECATED """
survived, died = count_survivors(data['Survived'])
remove_n = abs(survived - died)
dropId = []
if survived > died:
dropid = np.random.choice(data[data['Survived'] == 1].index, remove_n, replace=false)
elif survived < died:
dropId = np.ra... | 34b502f52dfa70d2f48d0ad6735766fc969a41f9 | 34,503 |
def log_concave_rejection_sampler(
mode,
prob_fn,
dtype,
sample_shape=(),
distribution_minimum=None,
distribution_maximum=None,
seed=None):
"""Utility for rejection sampling from log-concave discrete distributions.
This utility constructs an easy-to-sample-from upper bound for a discret... | 6c109478f39ce3ec4e5d630bb5d7b6e8a81df76c | 34,504 |
import time
def login(user_name, password):
""" This function takes user name and password to login into Github account.
Args:
:param user_name: Github username
:param password: Github password
Returns:
error_dict (dict): If it's logged in successfully or not wi... | fc119d4584ae721b72e916505445e1d760d04629 | 34,505 |
def make_tukey(n, a=0.5):
"""Make a tukey window
Args:
n (int): Number of points
a (float, optional): Width of window. Defaults to 0.5.
Returns:
np.array: Weights
"""
x = np.arange(n)
weights = np.ones_like(x, dtype=float)
weights[0:int(a*n/2)] = 1/2*(1-np.cos(2*np.... | cb14f4cfa9495567954b6ea83eef0f2c568190e3 | 34,506 |
def linear_gradient(start_hex: str, finish_hex: str = "#FFFFFF", n: int = 11) -> color_dict:
""" returns a gradient list of (n) colors between
two hex colors. start_hex and finish_hex
should be the full six-digit color string,
including the number sign ("#FFFFFF") """
# Starting and ending colors in... | 4df9e2d3f2b921e0826ffd51dde208a30bd78e96 | 34,507 |
def bast_label_to_number(annotation, label):
"""Given an annotation file and a label convert it to its corresponding
number for the BAST dataset."""
return bast_label_to_number_dict(annotation).get(label, None) | d62451272d84d1749d13070cda3b27825bb7c0d8 | 34,508 |
def function_with_exception(val):
"""Return a `val` if it is non-negative"""
if val < 0:
raise ValueError("val cannot be negative.")
return val | f9a4a50879477a5e45fcb9a9d54a10695fc526df | 34,510 |
def _c(obj: model.Component):
"""Convert :class:`.Component`."""
# Raises AttributeError if the concept_identity is missing
return str(obj.concept_identity.id) | 369d1f7b797e0a7162337f36d621593c7cf1f42e | 34,511 |
import copy
def get_power_instance(wildcards):
"""
Returns a formatted template
Arguments:
rest_base - Base URL of the RESTful interface
ident - Identifier of the chassis
"""
c = copy.deepcopy(_TEMPLATE)
c['@odata.context'] = c['@odata.context'].format(**wildcards)
c[... | f7fe438dcba027b68cf65919458568c742bf9735 | 34,512 |
import pyspark.sql.functions as fn
from pyspark.sql import Window
def get_user_history(history_type):
"""
:param history_type: 'click' or 'top' or 'play'
:return:
"""
spark.sql('use {}'.format(user_pre_db))
if history_type == 'play':
tmp_df = spark.sql('select user_id, movie_id, cate_i... | 346c2615961db564bda0336c679e08079b8a1ec8 | 34,513 |
def display_on_frame(self, image, left_curverad, right_curverad, car_off):
"""
Display texts on image using passed values
"""
font = cv2.FONT_HERSHEY_COMPLEX
curve_disp_txt = 'Curvature: Right = ' + str(np.round(right_curverad,2)) + 'm, Left = ' + str(np.round(left_curverad,2)) +... | c8e86350b7018d1b2eba94db8929a870cf6f8bc5 | 34,514 |
from pathlib import Path
def path_is_relative_to(path: Path, other: PathOrStr) -> bool:
"""
This is copied from :meth:`pathlib.PurePath.is_relative_to` to support older Python
versions (before 3.9, when this method was introduced).
"""
try:
path.relative_to(other)
return True
e... | 577c591d519e4b0364f202306151411694d81138 | 34,515 |
def generate_tokens( parser, lines, flags, keywords):
"""
This is a rewrite of pypy.module.parser.pytokenize.generate_tokens since
the original function is not RPYTHON (uses yield)
It was also slightly modified to generate Token instances instead
of the original 5-tuples -- it's now a 4-tuple of
... | c09fea9f20879017d87e695c63d6a6cca637a0ae | 34,516 |
def get_days_word_ending(days: int) -> str:
"""Определяет окончание слова "дня", "дней" и т.д. в зависимости от входящего числа"""
last_numeral = days % 10
prelast_numeral = days % 100
prelast_numeral = prelast_numeral // 10
if prelast_numeral == 1:
return 'дней'
if last_numeral == 0 or ... | 4f2887b438ab8909b29a0fa572c5735477da2262 | 34,517 |
def _init_hoomd_rb_torsions(structure, ref_energy=1.0):
"""RB dihedrals (implemented as OPLS dihedrals in HOOMD)."""
# Identify the unique dihedral types before setting
dihedral_type_params = {}
for dihedral in structure.rb_torsions:
t1, t2 = dihedral.atom1.type, dihedral.atom2.type
t3, ... | f71d955f1f2294ed1c6a5b041ed75dea1028bc34 | 34,518 |
def moments(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = data.sum()
X, Y = np.indices(data.shape)
x = (X * data).sum() / total
y = (Y * data).sum() / total
col = data[:, int(y)]
width_x = np.sqr... | 371cb1c1b8419eb9a604300c87a7a9084a13e46f | 34,519 |
def compute_throughputs(batch_size, gpu_times):
"""
Given a batch size and an array of time running on GPU,
returns an array of throughputs
"""
return [batch_size / gpu_times[i] * 1000 for i in range(len(gpu_times))] | 14b20806ad8e21126c460613a99f9b68bce31ef0 | 34,520 |
import torch
def load_trained_model(args, config_class, model_class, label_count_info, n_gpu, device):
"""Load trained model for evaluation"""
model = _build_pretrained_model(args, config_class, model_class, label_count_info)
model.to(device)
model_path = args.output_dir + "/epoch_%d" % args.load_n_e... | d64ff9fdd7e37dfd577983618f57f2bf7f1107cb | 34,521 |
import re
def parse_filter_field(string_filters) -> dict:
"""
Parses string with sets of name, value and comparison into a dict
Args:
string_filters: A string of the form 'name=<name1>,value=<value1>,comparison=<comparison1>;name=<name2>...'
Returns:
A dict of the form {<name1>:[{'Val... | adec2fa457a9f9d38770dce1ba9f50143480c884 | 34,522 |
def convert_to_one_hot(integer_vector, dtype=None, max_labels=None,
mode='stack', sparse=False):
"""
Formats a given array of target labels into a one-hot
vector.
Parameters
----------
max_labels : int, optional
The number of possible classes/labels. This means th... | 0341090659f502f81adb368880af4659b1886236 | 34,524 |
from typing import Sequence
def get_constraints(
guesses: list[str], calls: list[Sequence[Call]]
) -> tuple[dict[int, str], set[str], set[str]]:
"""Get constraints."""
positions = {}
appears = set()
no_appears = set()
for call, guess in zip(calls, guesses):
for i, c, x in zip(itt.count... | 0163f17fb93d9b2244f6762dbafdddfa7eefb0da | 34,525 |
def apply_trained_model(
trained_model_object, input_table, feature_names, replace_missing,
standardize, transform_via_svd, replacement_dict_for_training_data=None,
standardization_dict_for_training_data=None,
svd_dict_for_training_data=None):
"""Uses a trained model to make predicti... | 0760fe4bf49ba7f5b7b00de46a7e5dc5cb01f5d7 | 34,526 |
def extract_host(host, level='backend', default_pool_name=False):
"""Extract Host, Backend or Pool information from host string.
:param host: String for host, which could include host@backend#pool info
:param level: Indicate which level of information should be extracted
from host string.... | 01ee481a143ab32069e91bcb082e1e1eb229da71 | 34,527 |
from medtagger.api.rest import app
from typing import Any
def get_api_client() -> Any:
"""Return API client for testing purpose."""
app.testing = True
return app.test_client() | 48d6897a4ed07f9fb87aee37e8e2ff69383f71f8 | 34,528 |
def verify_ospf3_metric(device,
interface,
metric,
max_time=60,
check_interval=10):
"""Verify the OSPF3 metric
Args:
device (obj): Device object
interface (str): Interface name
metric (str): ... | 6c7f12304a4987293b9336bcbf6300951de75f09 | 34,529 |
import weakref
def copy_cache(
cache: t.Optional[t.MutableMapping],
) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
"""Create an empty copy of the given cache."""
if cache is None:
return None
if type(cache) is dict:
return {}
return LRUCache(cache.capac... | 4c0945da8471112a28bd34ad27286df55a23e968 | 34,532 |
def get_plugins(metadata):
"""Return the registered plugins.
Load and return all registered plugins.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError("No plugins found")
results = []
for p in sorted(plugins.get_all(), key=attrgetter("name")):
if metadata:
... | b88ddbc9e85bdc04d0f2a71458ab2545f925c88b | 34,533 |
def _ConvertUnmatchedResultsToStringDict(unmatched_results):
"""Converts |unmatched_results| to a dict of strings for reporting.
Args:
unmatched_results: A dict mapping builder names (string) to lists of
data_types.Result who did not have a matching expectation.
Returns:
A string dictionary repr... | 9c09a205bbcea48865e490f67342e0768f58555e | 34,534 |
def get_color(r, g, b, a):
""" converts rgba values of 0 - 255 to the equivalent in 0 - 1 """
return (r / 255.0, g / 255.0, b / 255.0, a / 255.0) | 78b4d71e04c7f3271462461641ec71e9fb849347 | 34,536 |
import re
def escape_version(version):
"""
Escaped version in wheel filename. Doesn't exactly follow
the escaping specification in :pep:`427#escaping-and-unicode`
because this conflicts with :pep:`440#local-version-identifiers`.
"""
return re.sub(r"[^\w\d.+]+", "_", version, flags=re.UNICODE) | ad382dc611a87b66db49f0332698618bda4cf86b | 34,539 |
def union_degree(node_df, edge_df, degree_df, OD_full_path):
"""
Inputs:
node_df, edge_df - the node and edge specific df from get_specific_df
OD_full_path - output of shortest_path
degree_df - output of get degree df
Outputs:
edge_degree_df, node_degr... | 89e5a9298fbb9214049c19c0cbc725b3ed7f66a5 | 34,540 |
def paths(resources, resource_strip_prefix):
"""Return a list of path tuples (target, source) where:
target - is a path in the archive (with given prefix stripped off)
source - is an absolute path of the resource file
Tuple ordering is aligned with zipper format ie zip_path=file
Args:
... | 2e0ebcee01cc7b61143ba6fc63bf44820e393fcb | 34,541 |
from typing import Optional
import json
import yaml
from typing import cast
def get_content(extra_file: ExtraFileTypeDef) -> Optional[str]:
"""Get serialized content based on content_type.
Args:
extra_file: The extra file configuration.
Returns:
Serialized content based on the content_ty... | 0c8d9fee5c244f2e6a42f5dd53eb7c4c508b824c | 34,542 |
def to_bs():
"""Example Registry Pipeline that loads existing pipelines"""
return [("pbsmrtpipe.pipelines.dev_04:pbsmrtpipe.tasks.dev_hello_world:0", "pbsmrtpipe.tasks.dev_txt_to_fasta:0")] | 36c08e38ccdefda793708b88a41f61d5f05e4197 | 34,543 |
def get_total_reflectance(mco_filename):
"""
extract reflectance from mco file.
Attention: mco_filename specifies full path.
Returns: the reflectance
"""
return get_diffuse_reflectance(mco_filename) + \
get_specular_reflectance(mco_filename) | f3ea4830fc2c8ee45fd33c229bec3430f85c199a | 34,544 |
import random
def mutate(c, gp, pmut):
"""Mutation of chromosome
Based on the probability to mutate, it selects a random gene to change. It selects
a random other creature to take a new gene from a gene pool.
Args:
c: creature's chromosme to be changed.
gp: gene pool to select from.
... | d65435e5ffbdcbdd44199493c2b0599fc8b96417 | 34,545 |
import numpy
def _(shape: numpy.ndarray):
"""
If a shape is an array of points, compute the minima/maxima
or let it pass through if it's 1 dimensional & length 4
"""
if (shape.ndim == 1) & (len(shape) == 4):
return shape
return numpy.array([*shape.min(axis=0), *shape.max(axis=0)]) | 1ab490ece446a6afec11f90038a285adf9afa141 | 34,546 |
def selectHierarchy(node):
""" get the hierarchy of the current given object
:param node: the object to search through
:type node: string
:return: list of the objects children and current object included
:rtype: list
"""
ad = cmds.listRelatives(node, ad=1, f=1) or []
ad.append(node[0])
... | c83c28b391e39f30dade59e73f89335a09fe807e | 34,548 |
import logging
import http
def logErrorAndReturnOK(error_msg='Error found in Task'):
"""Logs the given error message and returns a HTTP OK response.
Args:
error_msg: Error message to log
"""
logging.error(error_msg)
return http.HttpResponse() | 788f2b6b30e55e8375aab5fdb364f991aed7f71f | 34,549 |
def make_std_gaussian(var_names):
"""
Make a d dimensional standard Gaussian.
:param var_names: The variable name of the factor.
:type var_names: str list
:return: The standard Gaussian
:rtype: Gaussian
"""
assert var_names, "Error: var_names list cannot be empty."
dim = len(var_nam... | 3c2c9f5a35786391d6ca1131e7a54767bc18a54d | 34,550 |
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
# In order to accelerate program
for i in lis:
if i.startswith(sub_s) is True:
return True
return False | e53f941ce35bfe1e4f9c9a20d8cf90541186397d | 34,551 |
def sum_numbers_loop(n: int) -> int:
"""
BIG-O Notation = O(n)
"""
result = 0
for i in range(n + 1):
result += i
return result | d3265f5d7ceb277d105ab08f81ac4ce91fcc4153 | 34,552 |
import itk
def range(imageOrFilter) :
"""Return the range of values in a image of in the output image of a filter
The minimum and maximum values are returned in a tuple: (min, max)
range() take care of updating the pipeline
"""
img = image(imageOrFilter)
img.UpdateOutputInformation()
img.Update()
c... | 9bbe0fc68be26df35f062da3d4589c906050a10f | 34,554 |
import uuid
def get_unique_id():
"""Generate and set unique identifier of length 10 integers"""
identifier = uuid.uuid4()
return str(identifier.int)[:10] | 52ac119a062f454faad77df2fecb1f902bdd8530 | 34,555 |
import scipy
def erb_fir_filters(signal, edges, fs):
"""
Generates a bank of FIR filters for a given set of erb edges following the approach of
Hopkins et al. (2010), such that each filter has a response of -6 dB (relative to the
peak response) at the frequencies at which its response intersects wit... | 5ff1d3680e0f92e955d3a8314488b0c5900ba585 | 34,556 |
def restart(*args, **kwargs):
"""Return an instance of this to restart a workflow with the new input."""
return restart_type(args, kwargs) | 1203873275248791046f2ef87f75276141b59a46 | 34,557 |
def FourierMaskRandom(width, height,proportion, R):
"""
Create a random sampling pattern where each point is sampled from :
1 if r < R
1/(1-r)**2 if r > R
with 0<R<1
Args:
width (int): Size of output mask in x... | d4bee00f7eb2899bceba025f90f5c5389765a30a | 34,558 |
def get_shapes_from_group(group):
""" Gets all object shapes existing inside the given group
:param group: maya transform node
:type group: str
:return: list of shapes objects
:rtype: list str
.. important:: only mesh shapes are returned for now
"""
# checks if exists inside maya sce... | 053faff6240f75ab859e1c2bbd33604bdbde0c84 | 34,560 |
def bond_quatinty(price, investment, minimum_fraction=0.1):
"""
Computes the quantity of bonds purchased given the investment,
bond price per unit, and the minimum fraction of a bond that
can be purchased
:param investment: Amount of money that will be invested
:param minimum_fraction:... | 7b42ae44d2e2db2229251088cf3645e965887e0d | 34,561 |
def find_template(templates_list, template_name):
"""
Function returns copy of a template with a name template_name from templates_list.
"""
result_list = [template for template in templates_list if template_name == template['name']]
return deepcopy(result_list[0]) if result_list else {"template":{}... | a766a5dcf6d451ff26bee94d0eb8a28ff5e98c60 | 34,563 |
def dct_compress(X, n_components, window_size=128):
"""
Compress using the DCT
Parameters
----------
X : ndarray, shape=(n_samples,)
The input signal to compress. Should be 1-dimensional
n_components : int
The number of DCT components to keep. Setting n_components to about
... | 57cc70951c5e1e15964715383f876975d2e80844 | 34,564 |
def nan_divide(a: NDArrayOrFloat, b: NDArrayOrFloat) -> NDArrayOrFloat:
"""Helper function to avoid divide by zero in arrays and floats.
Args:
a: Numerator
b: Denominator
Returns:
a/b replace div0 by np.nan
"""
bc_shp = check_broadcastable(a=a, b=b)
return np.divide(a, b,... | ee3858c2ad3e2fdb87704eabb2acf523337f68d2 | 34,565 |
def get_folder_sessions(id):
"""
Get a list of sessions in the given folder
To fetch all elements, this endpoint can be called multiple times,
starting at pageNumber = 0 and incrementing the page number until
no results are returned.
"""
url = "{}/{}/sessions".format(panopto_url("folders"),... | 94dc5dd76bccc5b072aa37aa85f941cbebe7a4e9 | 34,566 |
def neighbours(image, i, j):
"""Define neighbours of the current pixel
Arguments:
image {numpy.ndarray} -- image
i {int} -- row coordinate of the pixel
j {int} -- column coordinate of the pixel
Returns:
list -- list of pixels that are neighbours of current pixel
... | eb9b7f0358fee26865ae75b544b532cb5dc5cd51 | 34,567 |
def mutation_delete_musicplaylist(identifier: str):
"""Returns a mutation for deleting a musicplaylist object based on the identifier.
Arguments:
identifier: The unique identifier of the musicplaylist object.
Returns:
The string for the mutation for deleting the musicplaylist object based ... | bb552783f4b9b8d232dd2fae79823eb06fcf5c00 | 34,568 |
import re
def check_for_repeating_characters(tokens, character):
"""
References:
:func:`re.findall`
Args:
tokens ():
character ():
Returns:
"""
replacements = []
pattern = "([" + character + "{2,}]{2,4})"
for token in tokens:
if len(token) > 12:
... | 9a421e634ad1cd330c2933fda84eb2430e7ef2ed | 34,569 |
import hashlib
def md5sum(filename):
""" Compute the MD5 hash for a given filename """
blocksize = 65536
hasher = hashlib.md5()
with open(filename, "rb") as fid:
buf = fid.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = fid.read(blocksize)
retur... | 4de15169bb672067fc4fcebeae930e56768b0881 | 34,570 |
from datetime import datetime
def time_stamp():
"""Current time stamp"""
ts = datetime.now()
return ts.strftime('%d-%b-%Y %H:%M:%S') | b17e6841b4c79cc1098123e154c9dd6e59098953 | 34,572 |
def fromDict(moduleDict):
"""Factory function recreating any moduleItem or moduleItem subtype from a dictionary-serialized representation.
If implemented correctly, this should act as the opposite to the original object's toDict method.
If the requested module is builtIn, return the builtIn module object of... | f0c2fdecc8bd73a40bea92e810724e14fffad341 | 34,573 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.