content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _design_knockoff_equi(exog):
"""
Construct an equivariant design matrix for knockoff analysis.
Follows the 'equi-correlated knockoff approach of equation 2.4 in
Barber and Candes.
Constructs a pair of design matrices exogs, exogn such that exogs
is a scaled/centered version of the input ma... | 149252ad76664ded9f3ed344d54b8026ac3e4da0 | 3,598,400 |
def parse_int(value) -> int:
"""
this function is used to parse data from the DB into an integer.
because a lot of the cells can be empty, we get None as the return type. This function makes sure we
get 0 if the value is None or empty
!!! IMPORTANT !!!
This is to be added to values where we wou... | 066e0a93436697bb31b91743faf851a752dd0e87 | 3,598,401 |
import os
import json
def get_config(key=None, default=None, raise_error=False, home_dir=None):
"""Read mne(-python) preference from env, then mne-python config
Parameters
----------
key : None | str
The preference key to look for. The os evironment is searched first,
then the mne-pyt... | 42e2376f4744bf72b6f63cf915e0aaeaadac49ba | 3,598,402 |
def converted_size(path, estimate=False):
"""Get size of converted raw image.
The size of image converted to raw format can be growing up to the virtual
size of the image.
:param path: path to the image file.
:param estimate: Whether to estimate the size by scaling the
original size
:r... | 0357c63dc64d25dff71f970227946b480f52df6a | 3,598,403 |
import os
import requests
def download_save_html_data(url, filename,
save_html_content=True):
"""Downlaod html data from url and save it at filename
Args:
url (str): url of data to fetch
filename (str): file path where to save downloaded data
save_html_cont... | a7adaca61abf6c9866c5347ad9592d8ec4027288 | 3,598,404 |
def asap(handlers, *, body, **kwargs):
""" Execute one handler at a time, skip on failure, try the next one, retry after the full cycle. """
retryfn = lambda handler: get_retry_count(body=body, handler=handler)
return sorted(handlers, key=retryfn)[:1] | 82d956b0527ee5796669c9ec7a04cfc7a3feaba7 | 3,598,405 |
def distance_by_lowtemp():
"""
"""
q = text(
"""
select date(start_date) as start_date,
avg(W.day_temp_min) as low_temp,
sum(R.distance) as distance
from rides R join ride_weather W on W.ride_id = R.id
group by date(start_date)
... | 483bf254a4948709a834a2351d048d43a4ad0aaf | 3,598,406 |
def bitpos_from_mask(mask, lsb_pos=0, increment=1):
"""
Turn a decimal value (bitmask) into a list of indices where each
index value corresponds to the bit position of a bit that was set (1)
in the mask. What numbers are assigned to the bit positions is controlled
by lsb_pos and increment, as explai... | d7938258c0f2dc523720bc82a48ecba1c2342223 | 3,598,407 |
def cli_arguments():
"""Retrieve all CLI arguments provided by user."""
# First of all, we need to specify all command line flags that are
# recognized by this tool.
parser = ArgumentParser()
parser.add_argument(
"-c",
"--count",
dest="count",
default... | c2b5a1da7b1a23ef9edd47cbb904909b39ef6c63 | 3,598,408 |
def moving_average(list):
"""
list의 평균을 return한다.
input:
list
return:
average(float)
"""
mysum = 0
for i in range(0, len(list)):
mysum = mysum + list[i]
return mysum / len(list) | d5602113e74a7ef0f0027ec5f6964b72680c3499 | 3,598,409 |
import sys
import itertools
def find_first_view_quadruplet(full_paths):
"""
Given a quadruplet of view point path names, find the ordering according to translation
Parameter:
----------
full_paths: a list of length four with filenames
Returns:
----------
order: a list that is... | 88940082b4c705373e538792da9408d7acb2219e | 3,598,410 |
def pixelwise_predictor(feat,
nc=3,
n_layers=1,
n_layerwise_steps=0,
skip_feat=None,
reuse=False,
is_training=True):
"""Predicts texture images and probilistic masks.
Args... | a700668bb7f513fc0ee59c5da2e656346ef8fb98 | 3,598,411 |
def _data_aug_fn(image, ground_truth, hin, win, hout, wout, hnei, wnei, parts, limbs, data_format="channels_first"):
"""Data augmentation function."""
#restore data
ground_truth = cPickle.loads(ground_truth.numpy())
image=image.numpy()
annos = ground_truth["kpt"]
mask = ground_truth["mask"]
... | 98f587ce6282ebcaf999a0945286ffc71b187c20 | 3,598,412 |
import numpy
def _rolling_ball(tile, ball_radius: int, light_background: bool):
""" Applies the rolling-ball algorithm to a single tile.
Args:
tile: A tile, usually from an ome.tif file.
ball_radius: The radius of the ball to use for calculating the background.
light_background: Wheth... | e629d51b6607c0113cc27427775a72449cad0f39 | 3,598,413 |
def quality_threshold(sample, cutoff=5, PBC=False, net_height=0, net_width=0):
""" Run the complete clustering algorithm in one go and returns the clustered indices as a list.
Args:
sample (array): The input dataset
cutoff (float, optional): The clustering cutoff distance.
... | bc9fd5def494431e6e58ecf2cfb9ea5691bffa14 | 3,598,414 |
def setup_metadata_controller():
""" Load metadata controller based on spell_type
"""
if app.metadata.spell_type == consts.spell_types.SNAP:
return _setup_snap_metadata_controller()
# This is the typical default for now
return _setup_juju_metadata_controller() | 59757cade58bd4134106a908272cbf1822d76933 | 3,598,415 |
from datetime import datetime
def create_question(question_text, days):
"""
Creates a question with the given 'question_text' and published the
given number of 'days' offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + d... | c541eb40f68eb9dd3b54eb1d8f96bc84f8a79269 | 3,598,416 |
def url_compose(camera):
""" Compose URL string for the camera """
# rtsp://88.204.57.242:5533/user=admin&password=******&channel=1&stream=1.sdp?
url: str = f'rtsp://{camera.ip_addr}:{camera.port}/user={camera.login}&password={camera.password}&channel=1&stream=0.sdp?'
return url | 62bf81b993e95a4c5ed7ca8362220cf16102c877 | 3,598,417 |
def pt2gen(t_arr, K, T, y0 = 0):
""" generate y(t) of PT2 for t in t_arr
Args:
t_arr (list(float)): time array
K (float): gain
T (float): time-constant
Returns:
list(float): y(t) for t in t_arr
"""
return [pt2(t, K, T) + y0 for t in t_arr] | ae29779f491669f5f56dbafb209da6b1664014bc | 3,598,418 |
def _select_deep(v, field, depth, record):
"""
field = {"name":name, "value":["attribute", "path"]}
r[field.name]=v[field.value], BUT WE MUST DEAL WITH POSSIBLE LIST IN field.value PATH
"""
if hasattr(field.value, "__call__"):
try:
record[field.name] = field.value(wrap(v))
... | 27580452cd7d5e17172d817a8f1a407518c00fda | 3,598,419 |
def filter_constant(vars):
"""Create T/F index for data with variance vars, F if variance constant.
"""
return vars != 0 | 57da83f60c42445903e8fd1442c60f7fd4e16bc6 | 3,598,420 |
import logging
def _project_duals_op_for_layer(layer, dual_var_list):
"""Returns op that updates duals for a single layer."""
# Dual variable may not be required.
if layer.dual_shape() is None:
project_op = tf.no_op()
else:
try:
project_op = layer.project_duals_op(dual_var_list[-1])
except (... | bfb3e11dd5caf6128f4f24d8e93678b4bed3f71c | 3,598,421 |
def dropout_backward(dout, cache):
"""
Perform the backward pass for (inverted) dropout.
Inputs:
- dout: Upstream derivatives, of any shape
- cache: (dropout_param, mask) from dropout_forward.
"""
dropout_param, mask = cache
mode = dropout_param['mode']
dx = None
if mode == 'train':
########... | 5d9274bb84e3a72e7b5e7e08efa142b6f02bb448 | 3,598,422 |
def recent_blog_posts(author=None, limit=10, offset=0, asc=False, before=None):
"""
Get user's recent posts/recommendations
"""
if author and isinstance(author, (int, long)):
author = User(author)
if author and author.id != env.user.id:
if author.get_profile('private') and not autho... | 4a70c3be2ddd03c3550645b1ed00ddaa6550ead3 | 3,598,423 |
def create_simple_line(obj, state):
"""Creates an SVG <line> element from a Faint Line object."""
element = ET.Element('line')
points = obj.get_points()
assert len(points) == 4
element.set('x1', str(points[0]))
element.set('y1', str(points[1]))
arrow = obj.arrow
if arrow != 'none': # F... | e129e7a47703e7a3f440cd7dad3869c02a384119 | 3,598,424 |
def optimal_amiRNA(dna_sequence):
"""
Id any seqs of 21 nt with T at nucleotide 1 and A or T at nucleotide 10
Input is the target (not the complement)
optimal_RNAs --> [(amiRNA,*amiRNA)]
"""
dna_sequence.upper()
dna_sequence = complement(dna_sequence)
pos = 0
optimal_amiRNAs=[]
... | f900b92f96108e37e82f09e220631feeba480ace | 3,598,425 |
import functools
def input_function(is_train, embeddings):
"""An input function satisfying the tf.estimator API."""
# A dataset with keys `question`, `context`, `answer_start`, and `answer_end`.
dataset = nq_long_dataset.get_dataset(is_train)
dataset = dataset.map(
functools.partial(
preproce... | 6ebb0fdfd3e54c6a142aff2373785e43b3315dfd | 3,598,426 |
def calculate_proportion_dict(data, relevant_keys, percent=False, floor=0., underscore=True):
"""
General method to calculate proportions from absolute values provided as dictionaries.
Args:
data: Dictionary containing the absolute values
relevant_keys: The keys of data from which proportio... | 0c11cdb2d5efa73ee9bb8fa4e05cd55e0e3197cd | 3,598,427 |
from plyfile import PlyData, PlyElement
def loadCloudPLY(path):
"""
Loads a PLY file from the specified path.
"""
try:
except:
assert False, "Please install plyfile (pip install plyfile) to load PLY."
# look for/load header file if one exists
header, data = matchHeader(path)
... | c0460843d8efdfc8eeb00526e900a150a2e23985 | 3,598,428 |
def GetClientIdFlag():
"""Anthos auth token client-id flag, specifies the ClientID is the id for OIDC client application."""
return base.Argument(
'--client-id',
required=False,
help='ClientID is the id for OIDC client application.') | 019f23808cdc20a25775ca5d4516ec6a9b4ecf3d | 3,598,429 |
def get_first_package_name(name):
"""
Returns first package name.
From `a.b.c` it returns `a`.
:param str name: Full module name
:return: First package name.
:rtype: str
"""
return name.split(".")[0] | 814b175356ef715af46f788dc9eac7e776884b30 | 3,598,430 |
def get_schlagworte_sorted(schlagworte):
""" uebersetzt die gestemmten Schlagwoerter in die ursruenglichen Schlagwoerter """
items = []
for schlagwort in schlagworte.all():
items.append(get_schlagwort_by_stem(schlagwort))
items.sort()
return items | a8df8e52821689aec70da56b258dcc299dc8a7f0 | 3,598,431 |
def _parse_url_work_relation(response):
""" response is
{'resource': 'https://imslp.org/wiki/7_Bagatelles,_Op.33_(Beethoven,_Ludwig_van)',
'relations': [{'source-credit': '',
'target-credit': '',
'type-id': '0cc8527e-ea40-40dd-b144-3b7588e759bf',
'type': 'download for free',
'end': None,
'direct... | 4e36330be029846bc44c235dafb20e6dc9c5f58f | 3,598,432 |
def run():
"""Entrypoint function."""
logger.info("Scheduled scan for newer versions started")
print("Scheduled scan for newer versions started")
read_packages()
get_repos()
get_version_data(REPO_DATA, PACKAGE_DATA, NEW_VERSION_DATA, VERSION_DATA)
get_version_data(REPO_DATA, TRANSITIVE_PACKA... | b24a69ef0609ba08ed5b52d204eaafdf73b62034 | 3,598,433 |
def get_edge_mask(poly, mask):
"""
Generate edge mask
"""
cv2.polylines(mask, [poly], True, [1])
return mask | 481b91c8ea289df2cd388a93299e6cc94d6ef384 | 3,598,434 |
def merge_dicts(dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result | bdd006b0a9ba641d1608bbf793953610de06f04c | 3,598,435 |
def _checkXmlStructure(data):
"""
@summary: checks the structure of the xml to check if it is valid xml
@param data: can be an xml string
"""
try:
d = minidom.parseString(data)
d = str(d.toxml())
return None
except Exception as e:
return str(e) | 0462e375a3e45cc4da3ba9cc6e41597e7477587c | 3,598,436 |
import urllib
def embed_mp3(music_file, meta_tags):
"""Embed metadata to MP3 files."""
# EasyID3 is fun to use ;)
audiofile = EasyID3(music_file)
audiofile['artist'] = meta_tags['artists'][0]['name']
audiofile['albumartist'] = meta_tags['artists'][0]['name']
audiofile['album'] = meta_tags['alb... | 76e8f9643ebdc9f7a90d0d78fc4a9987b82d5f19 | 3,598,437 |
def isint(value):
""" To check if any variable can be converted to integer """
try:
int(value)
return True
except ValueError:
return False | 9c8b3e4abe11e8c23fb6d28b92637ec885093f28 | 3,598,438 |
def is_url() -> "UrlWith":
"""TODO"""
return UrlWith() | 8d273cd549bb46b550d98e264f68a08ababbd51a | 3,598,439 |
def test_np_print_2():
"""
Feature: JIT Fallback
Description: Support print.
Expectation: No exception.
"""
class PrintNet(nn.Cell):
def construct(self):
x = np.array([1, 2, 3, 4, 5])
print("x: ", x)
return Tensor(x)
net = PrintNet()
res = net... | 075d70848ece95d314167014d0730b12f9967996 | 3,598,440 |
def hkcancor_to_ud(tag: str = None):
"""Map a part-of-speech tag from HKCanCor to Universal Dependencies.
HKCanCor uses a part-of-speech tagset of over 100 tags (46 of which
are described at http://compling.hss.ntu.edu.sg/hkcancor/).
For applications that would benefit from a less granular part-of-spee... | 56624cb18f6684f317f7caaa04f884bdf149282b | 3,598,441 |
def to_array(x):
"""Convert the input to a numpy array"""
if isinstance(x, pd.Series):
return x.values
return np.asarray(x) | 77196a44a6580ebbfc1667c46c4edc8e9525c365 | 3,598,442 |
def example_two_by_two_data():
"""load santa clara data to test two by two ei and plots"""
sc_data = data.Datasets.Santa_Clara.to_dataframe()
group_fractions = np.array(sc_data["pct_e_asian_vote"])
votes_fractions = np.array(sc_data["pct_for_hardy2"])
precinct_pops = np.array(sc_data["total2"])
... | 33d99d6b3804b77eab1486347d9f84943899f462 | 3,598,443 |
import sys
import os
def modify_subnet():
"""
A HTTP POST function to delete a Subnet
Parameters ---
subnet_ids : list : Subnet IDs
"""
LOGGER.info("Request url -> /dhcp4/subnets/modify")
LOGGER.info("Request method -> POST")
json_req_data = request.get_json()
if no... | 4c2f2ee6f651d44dc91c81793798909a8667294d | 3,598,444 |
def is_russian(token):
"""
Returns true if the token contains only russian characters or punctuation, otherwise false.
"""
return any([c in RUS_ALPHABET_SET for c in token]) | db880efa5de5a028c220ea075c925c02244099e9 | 3,598,445 |
def check(client: Client, args: Namespace) -> bool:
"""Checks whether the specified conditions are met."""
stats = client.stats(full=True)
if args.max_players is not None and stats.num_players > args.may_players:
return False
if args.min_players is not None and stats.num_players < args.min_pl... | c129a5023359e5461cd214b0c713603bc8c066c6 | 3,598,446 |
def get_languages(*args, **kwargs):
"""
Wraps tesserocr.get_languages() with a fixed path parameter.
"""
return get_languages_(*args, path=get_tessdata_path(), **kwargs) | 077903b485d112b0de09fe959398fa57f87975c4 | 3,598,447 |
def adjust_contrast_log(arr, gain):
"""
Adjust image contrast by scaling pixels to ``255*gain*log_2(1+v/255)``.
Supported dtypes
----------------
* ``uint8``: yes; fully tested (1) (2) (3)
* ``uint16``: yes; tested (2) (3)
* ``uint32``: no; tested (2) (3) (8)
* ``uint64... | 5fd52969c2c2222f9d9ae20f2a2c42fcefe6582e | 3,598,448 |
def largest_odd_factor(var_arr):
"""
Function that computes the larges odd factors of an array of integers
Parameters
-----------------
var_arr: numpy.array
Array of integers whose largest odd factors needs to be computed
Returns
------------
odd_d: numpy.array
Array of... | 408e94c6223dec5e529d69181a8f187b017fe5b6 | 3,598,449 |
def update_step(loss, config, clip_gradient=1., scope='optimizer'):
"""Computation of gradients and application of weight updates
Optimizer can be supplied via config file, e.g. as
"optimizer_params": {"learning_rate": 1e-3},
"optimizer": "'AdamOptimizer'"
Parameters
-------
loss : tensor
... | 797d90163efc1ea21f8f7526a7ff022d4bcabff6 | 3,598,450 |
import os
import urllib
def project(url, wip=False):
"""Generate a badge for the given project url
Args:
url (str): Project url on github
Returns:
str: The badge
"""
repo_name = url.split('/')[-1]
if eval(os.getenv('INPUT_BADGES').title()):
return f'[:
"""Applies a list of passed resource tags to the AWS ECR repository.
Args:
ecr_repository_arn: ECR repository identifier/ARN
resource_tags: a list of key:string,value:string resource tag dictionaries
Returns:
Returns T... | 3c49d7d1871ff46f84b64488329270da0f9d1445 | 3,598,452 |
import base64
import gzip
def decode_base64_gzip_to_bytes(base64_gzip_data: str) -> bytes:
"""Decode Base64 GZIP into bytes."""
with BytesIO() as compressed_file:
compressed_file.write(base64.b64decode(base64_gzip_data))
compressed_file.seek(0)
with gzip.GzipFile(fileobj=compressed_fi... | a06b315281c1aae8e87e2d6bc5c403929012b534 | 3,598,453 |
import logging
def download_script(script):
"""Download a script"""
logging.info('[ROUTER]: Download script '+script)
try:
script = ScriptService.get_script(script, current_identity)
return send_from_directory(directory=SETTINGS.get('SCRIPTS_FS'), filename=script.slug + '.tar.gz')
exce... | 345097cda32d80863771485c5045f3f7b9544ad3 | 3,598,454 |
import os
def filter_list(logging):
"""Remove some files that don't need to be loaded into the slackbot."""
_mypath = os.path.abspath(__file__)
MYWORKDIR = os.path.dirname(_mypath)
logging.debug(MYWORKDIR)
file_list = os.listdir(MYWORKDIR)
_removal_list = ['__init__.py', '__pycache__', 'templa... | 492c0dc19a41a42331f2b4c9c42c26afa68978fd | 3,598,455 |
import toml
import yaml
import json
def mock_settings_file(request, monkeypatch, tmpdir, file_extension):
"""Temporarily write a settings file and return the filepath and the expected settings outcome."""
ext = file_extension
p = tmpdir.mkdir("sub").join("settings" + ext)
expected_result = {"testgrou... | 4899ebbc9efbe31a931387d4a09dcb8c727eaf8d | 3,598,456 |
import os
def find_all(filename, path):
"""Returns all files called <filename> in <path>."""
result = []
for root, dirs, files in os.walk(path):
if filename in files:
result.append(os.path.join(root, filename))
return result | f8ebdb55b3c538bdc64d35526421e41f76d913dc | 3,598,457 |
def MathSolution(N):
"""Use sum of squares formula and sum of integers formula for O(1) solution"""
sumOfSquares = N * (N+1) * (2*N + 1) // 6
squareOfSum = pow((N + 1) * N // 2, 2)
diff = squareOfSum - sumOfSquares
print("Math solution: ", diff)
return diff | d30046150d95c3217bc446fc3c8e5f3a985f6c51 | 3,598,458 |
from typing import List
def extract_urls_with_indices(text: str, extract_urls_without_protocol: bool = True) -> List[dict]:
"""
Extract valid URLs present in ``text`` along with their Unicode code point indices.
>>> extract_urls_with_indices('http://twitter.com/これは日本語です。example.com中国語')
[
{
... | 1cc646a678a82512fed3cf984c698dffae8e1752 | 3,598,459 |
def error_handler(func):
"""Contain handler for json and error exception. Accept only one value (not tuple) and should be a dict/list
Arguments:
func {[type]} -- [description]
Returns:
[type] -- [description]
"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
... | 4d3dae44f42d31abc722104e8130132330ce00f1 | 3,598,460 |
import re
def searchWalmart(query):
"""
The searchWalmart function scrapes walmart.com
Parameters: query- search query for the product,
currency- currency type entered by the user
Returns a list of items available on walmart.com that match the product entered by the user
"""
qu... | 01180517570d5ef7abc1b937cc3b1077bf22fed1 | 3,598,461 |
def get_months_range(start_date, end_date, keep_day=False):
"""
Returns a list of all months that are within start_date and end_date.
Useful when we need to fill up missing months in a QuerySet where there
were no results in that month and fill up those months with the value `0`.
"""
start_date ... | ac755beb085b8d696471bf316b1fe8d4479946e8 | 3,598,462 |
def integrator_interval(x, k):
"""
Compute the interval of an integrator system: dx = -k*x
:param x: state interval
:param k: gain interval, must be positive
:return: interval for dx
"""
if x[0] >= 0:
interval_gain = np.flip(-k, 0)
elif x[1] <= 0:
interval_gain = -k
... | 0f6c3667ffff4e78d777a0b6e2220713ad0623e6 | 3,598,463 |
import requests
def get_page(link):
"""
this thing takes a link and shoves back some html shit
"""
r = requests.get(link)
r.raise_for_status()
return r.content | 913b96c8670e7d91da92aa00d53582d7eae33dbe | 3,598,464 |
from typing import Iterable
def _build_correction_str(iterator: Iterable) -> str:
""" Creates madx commands (assignments) to run for correction"""
last_type = ''
text = ''
for corr in iterator:
if not _types_almost_equal(corr.type, last_type):
text += f"\n!! {_nice_type(corr.type)}... | d460d1e265619235a71b815b98d8ac4d1200bbbd | 3,598,465 |
import os
def get_dstarrepeater_config():
"""
retrieve some settings from dstarrepeater config while avoiding passwords
"""
distilled_config = {}
#############################
configfile = '/etc/dstarrepeater'
logger.info("Reading dstarrepeater...")
if os.path.isfile(configfile):
... | 18350657ce0fd662bd9ac950dcee82f57eafe92d | 3,598,466 |
def _start_daemon_and_get_client(wallet_name):
"""
Starts a daemon and create a client
"""
electrum_dir = _create_electrum_dir()
# check if running already
process_name = j.sal.process.getProcessByPort(RPC_PORT)
if process_name and 'electrum' in process_name:
print("Electrum daemon i... | 1e3005adb5f554363dba97101a649d9005548d2c | 3,598,467 |
from typing import Union
from typing import Tuple
def nonzero(x: Union[ivy.Array, ivy.NativeArray]) -> Tuple[ivy.Array]:
"""Returns the indices of the array elements which are non-zero.
Parameters
----------
x
input array. Must have a positive rank. If `x` is zero-dimensional, the function
... | 627780d21c18c9a3c862341428202dd1587b60af | 3,598,468 |
from datetime import datetime
def create_airflow_string(tasks):
"""
Given a task graph (as a list of tasks), generates an Airflow DAG file.
Parameters
----------
tasks: list of {Transform, Depositor} objects, required
The tasks constituting the task graph to be written as a DAG.
Retu... | f1bdc7d84615d772348a400e072ab22368ea4009 | 3,598,469 |
import signal
import asyncio
def cli_coro(
signals=(signal.SIGHUP, signal.SIGTERM, signal.SIGINT),
shutdown_func=None,
):
"""Decorator function that allows defining coroutines with click."""
def decorator_cli_coro(f):
@wraps(f)
def wrapper(*args, **kwargs):
loop = asyncio.... | b79b07071bd4c751805ced879fe354c5a45c78eb | 3,598,470 |
def replicate_idx(head):
"""Return a list of indices representing replicate groups"""
h = head
g = h.groupby(['Sample Name', 'Measurement day'])
idx = [i[1].index for i in g]
return(idx) | ac5b80de8d15ef283185b0e93d495516695aa936 | 3,598,471 |
def get_plugin_instance(api_client, id, *args, **kwargs): # noqa: E501
"""get_plugin_instance # noqa: E501
Get running plugin instance # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> response = await api.... | ca74093c8fc963a7555a570b18b15f1bf7190ac0 | 3,598,472 |
def str2ascii(string: str) -> list:
"""Convert a string to a list of ascii-codes"""
return [ord(i) for i in string] | a938b0c585e78a455721e9d17e8915b0769a025f | 3,598,473 |
def rgbToHexColor(r, g, b):
"""Convert r, g, b to #RRGGBB."""
return f'#{int(r):02X}{int(g):02X}{int(b):02X}' | 5cff9abc67c235a4f0fdf258ea555f018d80d1ad | 3,598,474 |
import pathlib
def within_dev_env():
""" detect whether we are within an ASMR dev environment. """
return pathlib.Path('/.ASMR_DEV_ENV').exists() | 86430b29846435b03460b2676d41cea0ba4063e4 | 3,598,475 |
def numeric_to_traj(vals, trajname, coordnames, indepvar=None, indepvarname='t',
indepdomain=None, all_types_float=True, discrete=True,
event_times=None, event_vals=None):
"""Utility function to convert one or more numeric type to a Trajectory.
Option to make the trajecto... | 7241d75179a923873fe9439fd08bc068a4dee262 | 3,598,476 |
def find_nearest(array, value):
"""Gets the nearest element of array to a value."""
array = np.asarray(array)
idx = np.nanargmin((np.abs(array - value)))
return array[idx] | 6b216d10c85a4f9b378f807d42cc3507814fac6e | 3,598,477 |
def red(url):
"""Redirects user from short_url to long_url
:Parameters:
- 'url': Short URL used to query for and redirect to long URL
On GET: Grabs URL Mapping from database and routes accordinly
"""
if request.method == 'GET':
url_map = URLMap.query.filter_by(short_url=url).first()
... | 75da6d78bfd754b1a3c8779e40b960fb903252c3 | 3,598,478 |
from datetime import datetime
def read_gml_ozone(filename=None, **kwargs):
"""
Function to read carbon dioxide data from NOAA GML.
Parameters
----------
filename : str or pathlib.Path
Data file full path name.
**kwargs : keywords
Keywords to pass through to ACT read_csv() rout... | 457cfbf38a9e074d4c84d98af8993cdb5058c13f | 3,598,479 |
def test_fallback_round_with_x_tuple_n_default():
"""
Feature: JIT Fallback
Description: Test sum() in graph mode with input x tuple and input n default.
Expectation: No exception.
"""
@ms_function
def foo():
x = sum((1, 2, 3))
return x
out = foo()
assert out == 6 | 7e94a68322aa8fbfd4efaefa4f282a66d0e1972c | 3,598,480 |
def degree_matrix(adjacency, rtype='array'):
"""Creates a matrix representing vertex degrees.
Parameters
----------
adjacency : list
List of lists, vertex adjacency data.
rtype : {'array', 'csc', 'csr', 'coo', 'list'}
Format of the result.
Returns
-------
array-like
... | 622bd1cda4f77a0a6006189826d3d871365338a7 | 3,598,481 |
import json
import math
def extend_django_sqlite():
"""给 django sqlite 补上一些基础函数"""
def float_max(value_x, value_y):
return float(max(float(value_x), float(value_y)))
def json_contains(column_value, value):
return json.loads(value) in json.loads(column_value)
def json_extract(value, ... | 3ffc1c098b62c4acbe3534db70cabc66959cd421 | 3,598,482 |
from typing import Dict
def get_node_type_counts(plc: plc_client.PlacementCost) -> Dict[Text, int]:
"""Returns number of each type of nodes in the netlist.
Args:
plc: the placement cost object.
Returns:
Number of each type of node in a dict.
"""
counts = {
'MACRO': 0,
'STDCELL': 0,
... | b3fd76f9e3ef3b48ad3c30e766bc9319c77427b0 | 3,598,483 |
def init_csv(file_name: str, header: list, close=True):
"""
create a csv and write header, option to close
"""
csv_file = open(file_name, "a")
write_list(csv_file, header)
if close:
csv_file.close()
else:
return csv_file | bc2883ea84eeeb2cb615e2816e11f3a6acddcfae | 3,598,484 |
def DoCheck(sdk_root):
"""Run layering check at the given root folder."""
return LayeringChecker(sdk_root).Check() | ff19107d77e5dc36b0fc9e91fd6c07f782481aa0 | 3,598,485 |
def spanishwfn(data):
"""Return statistics for Spanish Word-Formation Network."""
return polishwfn(data) | 1df8a0fc1a1f3285e3700aed4eb66f6a931e4c68 | 3,598,486 |
def get_user(username):
"""
Get username line from switch
.. code-block:: bash
salt '*' nxos.cmd get_user username=admin
"""
return sendline('show run | include "^username {0} password 5 "'.format(username)) | feebc6140c030d51bf93a2ebb1fe7070de5f90c5 | 3,598,487 |
import functools
from typing import Any
def _complement(pred: PredicateFn) -> PredicateFn:
"""Return the complement to the predicate function ``pred``."""
@functools.wraps(pred)
def complement(v: Any) -> bool:
return not pred(v)
return complement | 4ff3437403fa80dd053c264e40532196632e4cd0 | 3,598,488 |
from typing import Tuple
from typing import Union
def checkout(args: Tuple[str]) -> Union[res.ResponseFailure, res.ResponseSuccess]:
"""Batch `git checkout` command."""
return guc.GitUseCase().execute(
CONFIG_MANAGER.config.github_selected_repos, "checkout", args
) | 8e2bc5bc512d6e08fd325f5f9e79480edaff2d0d | 3,598,489 |
def preprocess_plazas(osm_holder: OSMHolder, process_strategy: GraphProcessor, shortest_path_strategy, config: dict):
""" preprocess all plazas from osm_importer """
logger.info(f"Start processing {len(osm_holder.plazas)} plazas")
plaza_processor = PlazaPreprocessor(
osm_holder, process_strategy, sh... | 798f8862b10f90b69fa5f2f0bfd7e91a16a65aeb | 3,598,490 |
from typing import Optional
import re
def anonymize_run_string(t: Optional[str]) -> Optional[str]:
"""
Generalizes hex addresses, some sanitizer error numbers, values in "()" brackets.
Use with output, location or issue title
"""
if not t:
return t
re_hex_addr = re.compile(r"0[xX][0-... | ff475c9fa6e4d56a8a00477c34e2e9451ac8713d | 3,598,491 |
def filter_refgene_ensgene_exon(var_df_per_chrom, exon_class,
refgene, ensgene):
"""Filter for a refgene function, ensembl function or both.
Args:
var_df_per_chrom (:obj:`DataFrame`): all variants in a chromosome
variant_class (:obj:`str`): annovar variant class ... | 905db5cab873eabce8ee24872231f2dacabcec29 | 3,598,492 |
import types
from typing import Optional
from typing import List
def references(
ls: LanguageServer, params: types.ReferenceParams = None
) -> Optional[List[types.Location]]:
"""Find references to current symbol, if a bibliography key is present"""
if params is None:
return None
markdown_file ... | 97ae980dc545e664d4f92fb1375cdf123aee98f3 | 3,598,493 |
def get_op_for_request(request, route_info, spec):
"""
Find out which operation in the Swagger schema corresponds to the given
pyramid request.
:type request: :class:`pyramid.request.Request`
:type route_info: dict (usually has 'match' and 'route' keys)
:type spec: :class:`bravado_core.spec.Spe... | b558f7512fead97a5b2777357e9e14cf3093b500 | 3,598,494 |
def get_domains(sents, lang, engine='corenlp', options=None):
"""
>>> from sagas.nlu.legacy.aiobj_kit import get_domains
>>> get_domains('你有几台笔记本电脑?', 'zh', 'ltp')
>>> get_domains('列出上周编辑的文件。', 'zh', 'ltp', DomainGetOptions(enable_predicts=True))
:param sents:
:param lang:
:param engine:
... | 46440c41da735a927325a62280836b57f6eecafe | 3,598,495 |
def _lin_f(p, x):
"""Basic linear regression 'model' for use with ODR.
This is a function of 2 variables, slope and intercept.
"""
return (p[0] * x) + p[1] | 52bc228dd48ee7939fa60cd052989de70a44b197 | 3,598,496 |
from pathlib import Path
def find_cfg_file(directory: Path, name: str) -> str:
"""Find the configuration file by matching the value of BASIC section name paramter to the name variable."""
ini_files = []
for filename in directory.glob("*.ini"):
try:
config = ConfigParser()
i... | 301ac645fbd4a8dc2a6444f2ce70a65a83220000 | 3,598,497 |
def get_keyword_from_synonyms(string: str, default_keyword: str, synonyms: dict):
"""
checks if a word matches to a synonym from a given dictionary
:param string token to be allocated to a synonym class
:param default_keyword the keyword used in case if no keyword was found
:param synonyms dictio... | 5e9648ab839b03ab93d0c38244b65ef700cb084b | 3,598,498 |
def mock_user(request):
"""Define a mock user to be used when testing REST API services"""
user = dict(
id="test_id",
name="User Name",
description="I'm a test user",
url="someurl",
)
return user | ff6eee62cd27328130bcd37c6164d3b4b17e2558 | 3,598,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.