content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def bytes_to_bytesio(bytestream):
"""Convert a bytestring to a BytesIO ready to be decoded."""
from io import BytesIO
fp = BytesIO()
fp.write(bytestream)
fp.seek(0)
return fp | 5,341,800 |
def image_scatter_channels(im: Image, subimages=None) -> List[Image]:
"""Scatter an image into a list of subimages using the channels
:param im: Image
:param subimages: Number of channels
:return: list of subimages
"""
image_list = list()
if subimages is None:
subimages = im.sh... | 5,341,801 |
def unauthorized_handler():
"""
If unauthorized requests are arrived then redirect sign-in URL.
:return: Redirect sign-in in page
"""
current_app.logger.info("Unauthorized user need to sign-in")
return redirect(url_for('userView.signin')) | 5,341,802 |
def main(exit_event):
"""
ladder
Lights one channel at a time in order
Then backs down to the first
Then repeat everything 20 times
"""
# this is a list of all the channels you have access to
lights = hc._GPIO_PINS
# start with all the lights off
hc.turn_off_lights()
# paus... | 5,341,803 |
def pre_order_next(path, children):
"""Returns the next dir for pre-order traversal."""
assert path.startswith('/'), path
# First subdir is next
for subdir in children(path):
return posixpath.join(path, subdir)
while path != '/':
# Next sibling is next
name = posixpath.basename(path)
parent ... | 5,341,804 |
def gettiming(process_list, typetiming):
"""
Used to get a sort set for different duration needed to conver to
morse code.
"""
timing = []
for x in process_list:
if(x[0] == typetiming):
timing.append(x[3])
timing = set(timing)
return sorted(timing) | 5,341,805 |
def new_begin(self):
"""Runs when game is began."""
org_begin(self)
night_mode() | 5,341,806 |
def init():
"""Top level command handler."""
@click.command()
@click.option('--approot', type=click.Path(exists=True),
envvar='TREADMILL_APPROOT', required=True)
@click.argument('eventfile', type=click.Path(exists=True))
def configure(approot, eventfile):
"""Configure loca... | 5,341,807 |
def launch_subprocess(command):
"""
Process launch helper
:param command Command to execute
:type command list[str]|str
:return Popen object
"""
is_shell = not isinstance(command, (list, tuple))
return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=is_shell, close_fds=T... | 5,341,808 |
def tobooks(f: '(toks, int) -> DataFrame', bks=bktksall) -> DataFrame:
"""Apply a function `f` to all the tokens in each book,
putting the results into a DataFrame column, and adding
a column to indicate each book.
"""
return pd.concat([f(v, i) for i, v in bks.items()]) | 5,341,809 |
def _identity_error_message(msg_type, message, status_code, request):
"""
Set the response code on the request, and return a JSON blob representing
a Identity error body, in the format Identity returns error messages.
:param str msg_type: What type of error this is - something like
"badRequest"... | 5,341,810 |
def dummySvgCall():
"""Code which is here just so pyinstaller can discover we need SVG support"""
dummy = QtSvg.QGraphicsSvgItem("some_svg.svg") | 5,341,811 |
def _string_to_list(s, dtype='str'):
""" converts string to list
Args:
s: input
dtype: specifies the type of elements in the list
can be one of `str` or `int`
"""
if ' <SENT/> ' in s:
return s.split(' <SENT/> ')
elif dtype == 'int':
return [int(e) for e in s.split(L... | 5,341,812 |
def internal_solve_pounders(
criterion,
x0,
lower_bounds,
upper_bounds,
gtol_abs,
gtol_rel,
gtol_scaled,
maxinterp,
maxiter,
delta,
delta_min,
delta_max,
gamma0,
gamma1,
theta1,
theta2,
eta0,
eta1,
c1,
c2,
solver_sub,
maxiter_sub,
... | 5,341,813 |
def get_overlap_info(bbox):
"""
input:
box_priors: [batch_size, number_obj, 4]
output: [number_object, 6]
number of overlapped obj (self not included)
sum of all intersection area (self not included)
sum of IoU (Intersection over Union)
average of all intersection are... | 5,341,814 |
def comvideo(inputvideo, endvideo):
"""
视频合成
:param inputvideo:合成的第一段视频
:param endvideo:合成的第二段视频
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '视频空间合成{}.mp4'.format(endvideo)
outname = path + a
video1 = VideoFileClip(inputvideo)
video2 = VideoFileClip(endvideo)
... | 5,341,815 |
def get_current_language(request, set_default=True, default_id=1):
"""
Description:
Returns the current active language. Will set a default language if none is found.
Args:
request (HttpRequest): HttpRequest from Django
set_default (Boolean): Indicates if a default language must be a... | 5,341,816 |
def _update_user_proficiency(user_proficiency):
"""Updates the user_proficiency.
Args:
user_proficiency: UserContributionProficiency. The user proficiency to
be updated.
"""
user_proficiency_model = user_models.UserContributionProficiencyModel.get(
user_proficiency.user_id, ... | 5,341,817 |
def get_children():
""" Get children of a given instance. """
yield lambda selector, key: base.find_children(metadata.CRAIGSLIST, selector, key) | 5,341,818 |
def is_leap_year(year):
"""
returns True for leap year and False otherwise
:param int year: calendar year
:return bool:
"""
# return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
return year % 100 != 0 or year % 400 == 0 if year % 4 == 0 else False | 5,341,819 |
def update_search_params(context, **kwargs):
"""Update the set parameters of the current request"""
params = context["request"].GET.copy()
for k, v in kwargs.items():
params[k] = v
return params.urlencode() | 5,341,820 |
def dynamic2message(dynamic_dict: dict) -> Message:
"""
将从api获取到的原始动态转换为消息
"""
author_name = dynamic_dict['desc']['user_profile']['info']['uname']
dynamic_id = dynamic_dict['desc']['dynamic_id']
if dynamic_dict['desc']['type'] == 1: # 转发或投票
text = f"用户[{author_name}]转发了动态:\n" + dynamic_... | 5,341,821 |
def main(include_diagnoses=(1,3)):
"""Training and validation using all modalities
Parameters:
----------
include_diagnoses: tuple or list
Which groups/diagnoses included in training and validation, such as (1,3)
"""
# Instantiate model
model = Model()
# Concatenate all mo... | 5,341,822 |
def dem_to_roughness(src_raster, band=0):
"""Calculate the roughness for the DEM.
Parameters
----------
src_raster : Raster
The dem used to calculate the roughness.
band : int, optional, default: 0
source band number to use.
Returns
-------
dst_raster: Raster
ro... | 5,341,823 |
def conv_filter_image_summary(tag, kernel, padding=1):
"""Creates an image summary of the convolutional filters of the first layer.
Parameters
----------
tag: str or Tensor of type string
A scalar Tensor of type string. Used to build the tag of the summary values.
A placeholder could be ... | 5,341,824 |
def import_file(path, name=None):
"""Import modules from file."""
spec = importlib.util.spec_from_file_location(name or '', path)
module = importlib.util.module_from_spec(spec)
if name:
sys.modules[name] = module
spec.loader.exec_module(module)
return module | 5,341,825 |
def batch_matmul_checker(
attrs: Any, args: List[relay.expr.Expr], op_name: str
) -> bool: # pylint: disable=unused-variable
"""Check if dense is supported by TensorRT."""
if get_tensorrt_use_implicit_batch_mode() and len(args[0].checked_type.shape) != len(
args[1].checked_type.shape
):
... | 5,341,826 |
def func_run_dynamic(input_file, dynamic_dic, exclude, pprint):
"""
Execute one dynamic template
:param input_file: (string) The template file name
:param dynamic_dic: (dict) The dictionary of the dynamic variables
:return:
"""
new_template_filename = create_dynamic_template(input_file, dyn... | 5,341,827 |
def find(store_config, shardid): # FIXME require config instead
"""Find the path of a shard.
Args:
store_config: Dict of storage paths to optional attributes.
limit: The dir size limit in bytes, 0 for no limit.
use_folder_tree: Files organized in a folder tr... | 5,341,828 |
def octoquote():
"""prints a small gift"""
print(np.random.choice(all_quotes))
pass | 5,341,829 |
def CppCallStaticMethod(scope, type_defn, method, param_exprs):
"""Gets the representation of a static function call.
Args:
scope: a Definition for the scope in which the expression will be written.
type_defn: a Definition, representing the type of the object being called.
method: a Function, represent... | 5,341,830 |
def xclGetDeviceInfo2 (handle, info):
"""
xclGetDeviceInfo2() - Obtain various bits of information from the device
:param handle: (xclDeviceHandle) device handle
:param info: (xclDeviceInfo pointer) Information record
:return: 0 on success or appropriate error number
"""
libc.xclGetDeviceI... | 5,341,831 |
def template_failure(request, status=403, **kwargs):
""" Renders a SAML-specific template with general authentication error description. """
return render(request, 'djangosaml2/login_error.html', status=status) | 5,341,832 |
def zflatten2xyz(z, x=None, y=None):
""" flatten an nxm 2D array to [x, y, z] of shape=(n*m, 3)"""
if x is None:
x = np.arrange(0, z.shape[0], step=1)
if y is None:
y = np.arrange(0, z.shape[1], step=1)
xlen = len(x)
ylen = len(y)
assert z.shape[0] == xlen and z.shape[1] == ylen,... | 5,341,833 |
def test_update_site_logo(admin_client, settings):
"""
We can add a site logo, and it renders out
"""
url = reverse("admin:index")
settings.JAZZMIN_SETTINGS["site_logo"] = "books/img/logo.png"
response = admin_client.get(url)
soup = BeautifulSoup(response.content, "html.parser")
assert... | 5,341,834 |
def penalized_log_likelihood(curve,t,pairwise_contact_matrix,a,b,term_weights,square_root_speed=None,pairwise_distance_matrix=None):
"""
penalized log likelihood
"""
if pairwise_distance_matrix is None: #if the do not already have the pairwise distance matrix computed, then compute it
pairwise_d... | 5,341,835 |
def listening_ports():
""" Reads listening ports from /proc/net/tcp """
ports = []
if not os.path.exists(PROC_TCP):
return ports
with open(PROC_TCP) as fh:
for line in fh:
if '00000000:0000' not in line:
continue
parts = line.lstrip(' ').split(' ... | 5,341,836 |
def dict2array(X):
"""
Returns a Numpy array from dictionary
Parameters
----------
X: dict
"""
all_var = []
for k in X.keys():
all_var.append(X[k])
return np.array(all_var) | 5,341,837 |
def preprocess_field_data(subdelimiter, field_value, path_to_script):
"""Executes a field preprocessor script and returns its output and exit status code. The script
is passed the field subdelimiter as defined in the config YAML and the field's value, and
prints a modified vesion of the value (result)... | 5,341,838 |
def dfs_level_details():
"""This function traverses all levels in a DFS style. It gets the child directories and
recursively calls the same function on child directories to extract its level details
Returns:
Dictionary: Key is the level name, value is a list with first element as url
and th... | 5,341,839 |
def set_ansible_envar() -> None:
"""Set an envar if not set, runner will need this"""
ansible_config_path, msgs = get_conf_path("ansible.cfg")
for msg in msgs:
logger.debug(msg)
# set as env var, since we hand env vars over to runner
if ansible_config_path and not os.getenv("ANSIBLE_CONFIG... | 5,341,840 |
def makeNonParameterized(p):
"""Return a new Pointset stripped of its parameterization.
"""
if isinstance(p, Pointset) and p._isparameterized:
return Pointset({'coordarray': copy(p.coordarray),
'coordnames': copy(p.coordnames),
'norm': p._normord,
... | 5,341,841 |
def interface_getattr(*v):
"""Behaves like `getattr` but for zope Interface objects which
hide the attributes.
.. note:: Originally I simply tried to
override :meth:`InterfaceDocumenter.special_attrgetter` to deal with the
special access needs of :class:`Interface` objects, but found that thi... | 5,341,842 |
def round_time(t, to=timedelta(seconds=1)):
""" cftime will introduces noise when decoding values into date objects.
This rounds time in the date object to the nearest second, assuming the init time
is at most 1 sec away from a round minute. This is used when merging datasets so
their time dims match up... | 5,341,843 |
def decide_end(match_list, return_whole_match_object = False):
"""
Among all the match objects, return the march string the closest to the end of the text
Return : a string. If return_whole_match_object is True, return a match object
"""
if len(match_list) == 0:
return pd.NA
ends = ... | 5,341,844 |
def ensure_tag(tag_id):
"""
Check if a tag with id `tag_id` exists. If not, create it.
"""
if not tag_id:
raise ValueError("Tag id must not be empty")
with get_db().transaction() as t:
try:
t.query(_Tag).filter(_Tag.id == tag_id).one()
except NoResultFound:
... | 5,341,845 |
def get_level_refactorings_count(level: int, dataset: str = "") -> str:
"""
Get the count of all refactorings for the given level
Parameter:
level (int): get the refactoring instances for this level
dataset (str) (optional): filter for these specific projects
"""
retu... | 5,341,846 |
def repeat_batch(t, K, dim=0):
"""Repeat a tensor while keeping the concept of a batch.
:param t: `torch.Tensor`: The tensor to repeat.
:param K: `int`: The number of times to repeat the tensor.
:param dim: `int`: The dimension to repeat in. This should be the
batch dimension.
:returns: `t... | 5,341,847 |
def ifte(s, g_cond, g_true, g_false):
"""goal that succeeds if g_cond and g_true succeed or g_cond fails and g_false succeeds"""
def loop(s_inf=g_cond(s)):
try:
first_cond = next(s_inf)
except StopIteration:
yield from g_false(s)
return
except Suspend... | 5,341,848 |
def filter_by_continue_threshold_variance_threshold(peak_info, acc, cont_win_size=3, cont_thres=4, var_thres=0.001):
"""
Calculate the continuity by a given window length, then calculate the variance and filter the data by
a given threshold
:param peak_info: a 5D matrix
:param cont_win_size: continu... | 5,341,849 |
def configure(config: Configuration) -> None:
"""Configure the Origin Request handler."""
global _config
_config = config | 5,341,850 |
def send_update(*args: str) -> bool:
""" Updates the path endpoint to contain the current UTC timestamp """
assert args, "Firebase path cannot be empty"
endpoint = args[-1]
value = {endpoint: datetime.utcnow().isoformat()}
return send_message(value, *args[:-1]) | 5,341,851 |
def test_sophos_firewall_web_filter_update_command(requests_mock):
"""
Scenario: Update an existing web filter.
Given:
- User has provided valid credentials.
When:
- sophos_firewall_web_filter_update is called.
Then:
- Ensure outputs prefix is correct.
- Ensure a sample value fro... | 5,341,852 |
def run_quad_extraction(cart3d_triq_filename):
"""tests getting the normal groups"""
cart3d = Cart3D(log=None, debug=False)
result_names = [] # read the mesh only
cart3d.read_cart3d(cart3d_triq_filename, result_names=result_names)
points = cart3d.points
elements = cart3d.elements
celements... | 5,341,853 |
def execute_custom(datatype, runtype, driver, data_repository, step_list):
"""
Execute a custom testcase
"""
print_info("{0} {1}".format(datatype, runtype))
tc_status = False
if data_repository.has_key("suite_exectype") and \
data_repository["suite_exectype"].upper() == "ITERATIVE":
... | 5,341,854 |
def setup(bot):
"""
Setup the cog
"""
bot.add_cog(Admin(bot)) | 5,341,855 |
def _gather_function(properties, funcs):
"""generate functions of all components as sequence"""
for name, fun in funcs.iteritems():
if len(fun) == 1:
properties[name] = fun[0]
else:
properties[name] = _gen_sequence_function(fun) | 5,341,856 |
def parseSolFile(filename):
"""Parses SOL file and extract soil profiles."""
data = {}
profile = None
lat = None
lon = None
with open(filename) as fin:
for line in fin:
if line.startswith("*"):
if profile is not None:
data[(lat, lon)] = "{0... | 5,341,857 |
def test_validate_params():
"""Testing validation of params attribute."""
# four different ways in which params can fail
invalid_params_0 = (1.0, 1.0, 0.02, 0.02, 0.15, 0.33, 0.03)
invalid_params_1 = {'A0': 1.0, 'g': -0.02, 'L0': 1.0, 'n': -0.02, 's': 0.15,
'alpha': 0.33, 'delta'... | 5,341,858 |
def test_environment():
"""Test loading form environment variables"""
for var, value in env_vars:
os.environ[var] = value
config = yaconfig.Config(metaconfig)
config.load_environment(prefix="YACONFIG_TEST_")
for variable, value in config.items():
assert value == env_expected[varia... | 5,341,859 |
def get_deps_info(projects, configs):
"""Calculates dependency information (forward and backwards) given configs."""
deps = {p: configs[p].get('deps', {}) for p in projects}
# Figure out the backwards version of the deps graph. This allows us to figure
# out which projects we need to test given a project. So, ... | 5,341,860 |
def write_cflags():
"""Adds C-Flags. C++ version is defined at the beginning of this file"""
text = f"""CFLAGS = ${{TF_CFLAGS}} ${{OMP_CFLAGS}} -fPIC -O2 -std={CPPVERSION}
LDFLAGS = -shared ${{TF_LFLAGS}}
"""
text += write_cflags_cuda()
return text | 5,341,861 |
def ins_to_sem_compatibility(sem_labels_for_instances, num_sem_labels, stuff_sem_cls_ids, stuff_penalisation=1.0):
"""
Returns the compatibility matrix for the instance_labels -> semantic_labels bipartite potentials in BCRF.
Args:
sem_labels_for_instances: Semantic labels of the instances. 0th in... | 5,341,862 |
def display_matches(BL_im, FU_im, BL_points, FU_points, inliers=[]):
"""
A function that displays the two given images and plots the matching points in each of the corresponding images.
"""
fig = plt.figure()
fig.add_subplot(1, 2, 1)
plt.imshow(BL_im)
plt.title('BL01')
for point ... | 5,341,863 |
def test_update_package_dry_run(monkeypatch):
"""Test generating an update command for a package."""
monkeypatch.setattr(manage, "call", Mock())
pkg = PkgFile("mypkg", "1.0", replaces=PkgFile("mypkg", "0.9"))
update_package(pkg, ".", dry_run=True)
assert not manage.call.mock_calls | 5,341,864 |
def get_coverage(inputs):
"""Get edge coverage.
Returns:
A dictionary of inputs and corresponding coverage
"""
cov_dict = dict()
for test_input in inputs:
"Get coverage by running the program"
cov = coverage(input)
"Update coverage dictionary of test input"
cov_dict[test_input] = cov
ret... | 5,341,865 |
def test_inchi_key(input, output):
"""Check that inchi key is the same"""
rd_mol = Chem.MolFromSmiles(input)
rd_inchi_key = cmiles.generator.get_inchi_and_key(rd_mol)[1]
assert rd_inchi_key == output | 5,341,866 |
def compress_as(filename, fmt, target=None, keep=True):
"""Compress an existing file.
Supported compression formats are: gzip, bzip2, zip, and lzma (Python
3.3 or newer only).
Args:
filename: The path and name of the uncompressed file.
fmt: Decides to which format the file will be comp... | 5,341,867 |
def average(arr, mode = "mixed"):
"""
average(arr, mode) takes the average of a given array
Once again, the modes of add() can be used here to denote what the type of the array is
The function below, determine_mode(arr) can be used to determine the correct mode for your array
"""
if len(arr) == ... | 5,341,868 |
def createTag(tag):
"""
Method that creates a tag on the ExtraHop system.
Parameters:
tag (str): The name of the tag
"""
url = urlunparse(("https", HOST, "/api/v1/tags", "", "", ""))
headers = {"Authorization": "ExtraHop apikey=%s" % API_KEY}
data = {"name": TAG}
r = req... | 5,341,869 |
def save_result_to_csv(source, results, dst="."):
"""Save ingestion results to CSV file."""
with open(f"{dst}/ingestion-{source}.csv", "w") as f:
writer = csv.writer(f)
for initial_size, result in results.items():
for entites, time in result.items():
writer.writerow(i... | 5,341,870 |
def non_halting(p):
"""Return a non-halting part of parser `p` or `None`."""
return left_recursive(p) or non_halting_many(p) | 5,341,871 |
def set_cfg(config_name:str):
""" Sets the active config. Works even if cfg is already imported! """
global cfg
# Note this is not just an eval because I'm lazy, but also because it can
# be used like ssd300_config.copy({'max_size': 400}) for extreme fine-tuning
cfg.replace(eval(config_name)) | 5,341,872 |
def remove_products_by_search_number(user_id: str, search_number: str):
"""Remove products of search."""
db = get_database_connection()
search_url = db.hget(f'{DB_SEARCH_PREFIX}{user_id}', search_number)
remove_launched_search(user_id, search_url.decode('utf-8'))
products_pattern = f'{DB_PRODUCT_PRE... | 5,341,873 |
def _isValidWord(word):
"""Determine whether a word is valid. A valid word is a valid english
non-stop word."""
if word in _englishStopWords:
return False
elif word in _englishWords:
return True
elif wordnet.synsets(word):
return True
else:
return False | 5,341,874 |
def compare_floats(value1: float, value2: float):
"""Função que compara 2 floats"""
return True if abs(value1 - value2) <= 10**-6 else False | 5,341,875 |
def carrega_dataset(caminho_diretorio: str, divisao: Tuple[int, int], embaralhar=True) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Especifique o caminho do diretório em que os arquivos `noisy.npy`e `original.npy` estão.
Args:
caminho_diretorio (str): caminho do diretório.
divi... | 5,341,876 |
def _build_treelite_classifier(m, data, arg={}):
"""Setup function for treelite classification benchmarking"""
from cuml.utils.import_utils import has_treelite, has_xgboost
if has_treelite():
import treelite
import treelite.runtime
else:
raise ImportError("No treelite package fou... | 5,341,877 |
def insertion_sort(start, end):
"""Sort an array of pairs of addresses.
This is an insertion sort, so it's slowish unless the array is mostly
sorted already (which is what I expect, but XXX check this).
"""
next = start
while next < end:
# assuming the interval from start (included) to ... | 5,341,878 |
def _RenameChartsAndPointsWithSuffix(charts, suffix):
"""Append |suffix| to all chart names (except 'trace') and point names
(except 'summary').
Args:
charts: A dictionary of charts.
suffix: A string suffix, e.g. '_control'.
"""
# First rename all points except 'summary.
for chart_name in charts:
... | 5,341,879 |
def _pkq(pk):
"""
Returns a query based on pk.
Note that these are designed to integrate with cells and how they are saved in the database
:Parameters:
----------------
pk : list
list of primary keys
:Returns:
-------
dict
mongo query filtering fo... | 5,341,880 |
def inspect_decode_labels(pred, num_images=1, num_classes=NUM_CLASSES,
inspect_split=[0.9, 0.8, 0.7, 0.5, 0.0], inspect_ratio=[1.0, 0.8, 0.6, 0.3]):
"""Decode batch of segmentation masks accroding to the prediction probability.
Args:
pred: result of inference.
num_images: number of ima... | 5,341,881 |
def set_default_values(
**attributes: Dict[str, Union[float, int, str]],
) -> Dict[str, Union[float, int, str]]:
"""Set the default value of various parameters.
:param attributes: the attribute dict for the electronic filter being calculated.
:return: attributes; the updated attribute dict.
:rtype:... | 5,341,882 |
def validate_function(fn: FunctionType, config: Configuration, module_type: ModuleType) -> FunctionValidationResult:
"""Validates the docstring of a function against its signature.
Args:
fn (FunctionType): The function to validate.
config (Configuration): The configuration to use while validati... | 5,341,883 |
def find_existing_installation(package_name: str, display_name: str, test=True):
"""
Finds an existing installation of a package in the windows registry given the package name and display name
#### Arguments
package_name (str): Name of the package
display_name (str): Display name of the pack... | 5,341,884 |
def say(l, b, i):
"""
!d Repeat a word or phrase
!a <message...>
!r moderator
"""
try:
print 'Saying the phrase:', ' '.join(i.args)
b.l_say(' '.join(i.args), i, 1)
return True
except TypeError:
return False | 5,341,885 |
def run_benchmark(args):
"""Runs the benchmark."""
try:
dtest = xgb.DMatrix('dtest.dm')
dtrain = xgb.DMatrix('dtrain.dm')
if not (dtest.num_col() == args.columns
and dtrain.num_col() == args.columns):
raise ValueError("Wrong cols")
if not (dtest.num_r... | 5,341,886 |
def rSanderSelect(dbItem,index=0,interactive=False):
"""
rSanderSelect(dbItem,index=0,interactive=False)
select which rSander henry data to use in dbItem
Parameters:
dbItem, db[key] dictionary object with keys = ['hbpSIP','hbpSIPL',
'hbpSI_index']
index, pos... | 5,341,887 |
def dataset_w_pedigree_field():
"""
:return: Return model Dataset example with `pedigree_field` defined.
"""
search_pattern = SearchPattern(left="*/*/*_R1.fastq.gz", right="*/*/*_R2.fastq.gz")
dataset = DataSet(
sheet_file="sheet.tsv",
sheet_type="germline_variants",
search_p... | 5,341,888 |
def build_index(site_data, posts):
"""Build index.
Builds an index page from the given site data and list
of posts.
Parameters
----------
site_data : dict
Site- and blog-level data.
posts : list
A list of dictionaries of page data.
Returns
-------
None
"""
... | 5,341,889 |
def main():
"""Make a jazz noise here"""
args = get_args()
file = '../data/metagenomes-4.1.csv'
njobs = 10
#interpro_dir = os.path.join(os.getcwd(), 'interpro')
interpro_dir = '../data/interpro'
if not os.path.isdir(interpro_dir):
os.makedirs(interpro_dir)
tmpl = 'https://www.e... | 5,341,890 |
def get_new_access_token(client_id, client_secret, refresh_token):
"""Use long-lived refresh token to get short-lived access token."""
response = requests.post(
'https://www.googleapis.com/oauth2/v4/token',
data={
'client_id': client_id,
'client_secret': client_secret,
... | 5,341,891 |
def prettify_seconds(seconds):
"""
Prettifies seconds.
Takes number of seconds (int) as input and returns a prettified string.
Example:
>>> prettify_seconds(342543)
'3 days, 23 hours, 9 minutes and 3 seconds'
"""
if seconds < 0:
raise ValueError("negative input not allowed")
... | 5,341,892 |
def _PrepareServer(vm):
"""Installs Tensorflow Serving on a single server vm.
Args:
vm: server vm to operate on
"""
logging.info('Installing Tensorflow Serving on server %s', vm)
vm.Install('tensorflow_serving')
vm.InstallPreprovisionedBenchmarkData(
BENCHMARK_NAME, [RESNET_NHWC_SAVEDMODEL_TGZ], ... | 5,341,893 |
def get_regions_prodigal(fn):
"""Parse prodigal output"""
regions = {}
with open(fn, 'r') as f:
for line in f:
if line[:12] == '# Model Data':
continue
if line[:15] == '# Sequence Data':
m = re.search('seqhdr="(\S+)"', line)
if ... | 5,341,894 |
def add_processor(name, processor_object):
"""Adds a Processor to the autopkglib namespace"""
globals()[name] = processor_object
if name not in _PROCESSOR_NAMES:
_PROCESSOR_NAMES.append(name) | 5,341,895 |
def get_transform(account_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
transform_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTransformResult:
"""
Use this data source to access information... | 5,341,896 |
def do_ptp_modify(cc, args):
"""Modify PTP attributes."""
ptps = cc.ptp.list()
ptp = ptps[0]
op = "replace"
attributes = []
if args.enabled is not None:
attributes.append('enabled=%s' % args.enabled)
if args.mode is not None:
attributes.append('mode=%s' % args.mode)
if ... | 5,341,897 |
def default_preprocessing(df):
"""Perform the same preprocessing as the original analysis:
https://github.com/propublica/compas-analysis/blob/master/Compas%20Analysis.ipynb
"""
return df[(df.days_b_screening_arrest <= 30)
& (df.days_b_screening_arrest >= -30)
& (df.is_recid != -1... | 5,341,898 |
def get_step_type_udfs(
step_type: str,
workflow: str,
adapter: ArnoldAdapter = Depends(get_arnold_adapter),
):
"""Get available artifact udfs for a step type"""
artifact_udfs = find_step_type_artifact_udfs(
adapter=adapter, step_type=step_type, workflow=workflow
)
process_udfs = fi... | 5,341,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.