content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def autoaugment_preproccess(
input_size,
scale_size,
normalize=None,
pre_transform=True,
**kwargs):
"""
Args:
input_size:
scale_size:
normalize:
pre_transform:
**kwargs:
Returns:
"""
if normalize is None:
nor... | 5,348,400 |
def pubchem_image(cid_or_container, size=500):
"""
Generate HTML code for a PubChem molecular structure graphic and link.
Parameters:
cid_or_container: The CID (int, str) or a subscriptable object that
contains a key ``cid``.
Returns:
HTML code for an image from PubChem.
... | 5,348,401 |
def break_discussion():
"""Emulate buggy 'ticket move' behavior"""
project = M.Project.query.get(shortname='test')
tracker = M.AppConfig.query.find({'options.mount_point': 'bugs'}).first()
discussion = M.Discussion(name='fake discussion')
app_config = M.AppConfig()
app_config.tool_name = 'Ticket... | 5,348,402 |
def to_lines(text: str, k: int) -> Optional[List[str]]:
"""
Given a block of text and a maximum line length k, split the text into lines of length at most k.
If this cannot be done, i.e. a word is longer than k, return None.
:param text: the block of text to process
:param k: the maximum length of e... | 5,348,403 |
def _image_pos(name):
"""
查找指定图片在背景图中的位置
"""
imsrc = ac.imread('images/bg/{}.png'.format(name[1:]))
imobj = ac.imread('images/{}.PNG'.format(name))
# find the match position
pos = ac.find_template(imsrc, imobj)
circle_center_pos = pos['result']
return circle_center_pos | 5,348,404 |
def handle_greenness_indices(parameters: tuple, input_folder: str, working_folder: str, msg_func: Callable, err_func: Callable) -> \
Optional[dict]:
"""Handle running the greenness algorithm
Arguments:
parameters: the specified parameters for the algorithm
input_f... | 5,348,405 |
def weights_init_normal(m, std=0.02):
""" This init is common in GAN """
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, std)
elif classname.find('BatchNorm2d') != -1:
m.weight.data.normal_(1.0, std)
m.bias.data.fill_(0.0) | 5,348,406 |
def overwrite_table_data(
cube_path: os.PathLike, data: bytes, label=None, table_name=None
):
"""The file at *cube_path* will be modified by overwriting the
data in the specfied table name with the contents of *data*.
Either *label* or *table_name* is needed. If neither a *label*
dict (which must ... | 5,348,407 |
def notify_osd_fallback(title, message, sound, fallback):
"""Ubuntu Notify OSD notifications fallback (just sound)."""
# Fallback to wxPython notification
fallback(title, message, sound) | 5,348,408 |
def product_except_self(nums: list[int]) -> list[int]:
"""Computes the product of all the elements of given array at each index excluding the value at that index.
Note: could also take math.prod(nums) and divide out the num at each index,
but corner cases of num_zeros > 1 and num_zeros == 1 make code inele... | 5,348,409 |
def _season_retrieve_rows(
db: sql.Connection,
columns: str,
classification: str | int,
start_date: date | None,
stop_date: date | None,
exclusion_certifications: Collection[str] = (),
) -> Iterator[tuple]:
"""Gathers projects belonging in a single season in release order
The `columns` ... | 5,348,410 |
def fetch_pkey():
"""Download private key file from secure S3 bucket"""
s3_client = boto3.client('s3')
s3_client.download_file(S3_BUCKET, BUCKET_KEY, PKEY_FILE)
pkey_filename = PKEY_FILE.replace("/tmp/", "")
if os.path.isfile(PKEY_FILE):
return print(f"{pkey_filename} successfully downloaded... | 5,348,411 |
def so_mörk():
"""Sagnorð."""
return itertools.chain(
# Nafnháttur - nútíð er sleppt og ekki til í þáttíð miðmynd
{"sng---", "sng--þ", "snm---"},
# Boðháttur - alltaf 2.p og nútíð
string_product({"sb"}, MYND, {"2"}, TALA, {"n"}),
# Lýsingarháttur nútíðar
string_pr... | 5,348,412 |
def _histogram(values, value_range, nbins=100, dtype=tf.int32, name=None):
"""Return histogram of values.
Given the tensor `values`, this operation returns a rank 1 histogram counting
the number of entries in `values` that fell into every bin. The bins are
equal width and determined by the arguments `... | 5,348,413 |
def find_missing_letter(chars):
"""
chars: string of characters
return: missing letter between chars or after
"""
letters = [char for char in chars][0]
chars = [char.lower() for char in chars]
alphabet = [char for char in "abcdefghijklmnopqrstuvwxyz"]
starting_index = alphabet.index(chars[0])
for lett... | 5,348,414 |
def series_to_pyseries(
name: str,
values: "pl.Series",
) -> "PySeries":
"""
Construct a PySeries from a Polars Series.
"""
values.rename(name, in_place=True)
return values.inner() | 5,348,415 |
def _stagefile(coption, source, destination, filesize, is_stagein, setup=None, **kwargs):
"""
Stage the file (stagein or stageout)
:return: destination file details (checksum, checksum_type) in case of success, throw exception in case of failure
:raise: PilotException in case of controlled e... | 5,348,416 |
def tally_cache_file(results_dir):
"""Return a fake tally cache file for testing."""
file = results_dir / 'tally.npz'
file.touch()
return file | 5,348,417 |
def get_soft_label(cls_label, num_classes):
"""
compute soft label replace one-hot label
:param cls_label:ground truth class label
:param num_classes:mount of classes
:return:
"""
# def metrix_fun(a, b):
# torch.IntTensor(a)
# torch.IntTensor(b)
# metrix_dis = (a - b... | 5,348,418 |
def get_option(args, config, key, default=None):
"""Gets key option from args if it is provided, otherwise tries to get it from config"""
if hasattr(args, key) and getattr(args, key) is not None:
return getattr(args, key)
return config.get(key, default) | 5,348,419 |
def z_decode(p):
"""
decode php param from string to python
p: bytes
"""
if p[0]==0x4e: #NULL 0x4e-'N'
return None,p[2:]
elif p[0]==0x62: #bool 0x62-'b'
if p[2] == 0x30: # 0x30-'0'
return False,p[4:]
else:... | 5,348,420 |
def parse_extension(uri):
""" Parse the extension of URI. """
patt = re.compile(r'(\.\w+)')
return re.findall(patt, uri)[-1] | 5,348,421 |
def rotz(ang):
"""
Calculate the transform for rotation around the Z-axis.
Arguments:
angle: Rotation angle in degrees.
Returns:
A 4x4 numpy array of float32 representing a homogeneous coordinates
matrix for rotation around the Z axis.
"""
rad = math.radians(ang)
c ... | 5,348,422 |
def getBits(data, offset, bits=1):
"""
Get specified bits from integer
>>> bin(getBits(0b0011100,2))
'0b1'
>>> bin(getBits(0b0011100,0,4))
'0b1100'
"""
mask = ((1 << bits) - 1) << offset
return (data & mask) >> offset | 5,348,423 |
def rescale(img, input_height, input_width):
"""Code from Loading_Pretrained_Models.ipynb - a Caffe2 tutorial"""
aspect = img.shape[1]/float(img.shape[0])
if(aspect>1):
# landscape orientation - wide image
res = int(aspect * input_height)
imgScaled = skimage.transform.resize(img, (in... | 5,348,424 |
def compute_halfmax_crossings(sig):
"""
Compute threshold_crossing, linearly interpolated.
Note this code assumes there is just one peak in the signal.
"""
half_max = np.max(sig)/2.0
fwhm_set = np.where(sig > half_max)
l_ndx = np.min(fwhm_set) #assumes a clean peak.
if l_ndx > 0:
... | 5,348,425 |
def test_export_edited_suffix():
"""test export with --edited-suffix"""
import glob
import os
import os.path
import osxphotos
from osxphotos.cli import export
runner = CliRunner()
cwd = os.getcwd()
# pylint: disable=not-context-manager
with runner.isolated_filesystem():
... | 5,348,426 |
def quote_identities(expression):
"""
Rewrite sqlglot AST to ensure all identities are quoted.
Example:
>>> import sqlglot
>>> expression = sqlglot.parse_one("SELECT x.a AS a FROM db.x")
>>> quote_identities(expression).sql()
'SELECT "x"."a" AS "a" FROM "db"."x"'
Args:
... | 5,348,427 |
def write_png(data, origin='upper', colormap=None):
"""
Transform an array of data into a PNG string.
This can be written to disk using binary I/O, or encoded using base64
for an inline PNG like this:
>>> png_str = write_png(array)
>>> 'data:image/png;base64,'+png_str.encode('base64')
... | 5,348,428 |
def prepare_url(url, source_url=None):
"""
Operations that purify a url, removes arguments,
redirects, and merges relatives with absolutes.
"""
try:
if source_url is not None:
source_domain = urlparse(source_url).netloc
proper_url = urljoin(source_url, url)
... | 5,348,429 |
def str_contains_num_version_range_with_x(str):
"""
Check if a string contains a range of number version with x.
:param str: the string to check.
:return: true if the string contains a a range of number version with x, false else.
"""
return bool(re.search(r'\d+((\.\d+)+)?(\.x)? < \d+((\.\d+)+)?... | 5,348,430 |
def get_args():
"""
gets cli args via the argparse module
"""
msg = "This script records cpu statistics"
# create an instance of parser from the argparse module
parser = argparse.ArgumentParser(description=msg)
# add expected arguments
parser.add_argument('-s', dest='silent', required=Fa... | 5,348,431 |
def mpc_coro_ignore(
func: Callable[..., Coroutine[SecureElement, None, SecureElement]]
) -> Callable[..., SecureElement]:
"""
A wrapper for an MPC coroutine that ensures that the behaviour of the code is unaffected by
the type annotations.
:param func: The async function to be wrapped
:return:... | 5,348,432 |
def test_managed():
"""
Test to manage a memcached key.
"""
name = "foo"
ret = {"name": name, "result": False, "comment": "", "changes": {}}
mock_t = MagicMock(side_effect=[CommandExecutionError, "salt", True, True, True])
with patch.dict(
memcached.__salt__, {"memcached.get": mock... | 5,348,433 |
def is_all_in_one(config):
"""
Returns True if packstack is running allinone setup, otherwise
returns False.
"""
# Even if some host have been excluded from installation, we must count
# with them when checking all-in-one. MariaDB host should however be
# omitted if we are not installing Mar... | 5,348,434 |
def subset_prots_longest_cds(genes,proteins_path, path_out):
"""
the gene-protein ID matching table, generated with gffread is used for this table
(it contains the length of the CDS ) to infer the transcript with the longest cds for each gene
this transcript is then written to a tmp fasta file
Args... | 5,348,435 |
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
response.title = 'Award management'
data = {"message":... | 5,348,436 |
def session_generate(instanceAddress, appSecret): # pragma: no cover
"""
**Deprecated**
Issue a token to authenticate the user.
:param instanceAddress: Specify the misskey instance address.
:param appSecret: Specifies the secret key.
:type instanceAddress: str
:type appSecret: str
:rtyp... | 5,348,437 |
def _dream_proposals( currentVectors, history, dimensions, nChains, DEpairs, gamma, jitter, eps ):
"""
generates and returns proposal vectors given the current states
"""
sampleRange = history.ncombined_history
currentIndex = np.arange(sampleRange - nChains,sampleRange)[:, np.newaxis]
combi... | 5,348,438 |
def handle_compressed_file(
file_prefix: FilePrefix,
datatypes_registry,
ext: str = "auto",
tmp_prefix: Optional[str] = "sniff_uncompress_",
tmp_dir: Optional[str] = None,
in_place: bool = False,
check_content: bool = True,
) -> HandleCompressedFileResponse:
"""
Check uploaded files ... | 5,348,439 |
def compress_r_params(r_params_dict):
"""
Convert a dictionary of r_paramsters to a compressed string format
Parameters
----------
r_params_dict: Dictionary
dictionary with parameters for weighting matrix. Proper fields
and formats depend on the mode of data_weighting.
... | 5,348,440 |
def replace_ext(filename, oldext, newext):
"""Safely replaces a file extension new a new one"""
if filename.endswith(oldext):
return filename[:-len(oldext)] + newext
else:
raise Exception("file '%s' does not have extension '%s'" %
(filename, oldext)) | 5,348,441 |
def pp_table(operations, multiplies, n, num_stages):
"""Pretty prints a table describing the
calculations made during the pipeline."""
stage_titles = ["a"] + [f"Stage {i}" for i in range(num_stages)]
table = PrettyTable(stage_titles)
for row in range(n):
table_row = [f"{row}"]
for st... | 5,348,442 |
def getAllArt():
"""
1/ verify if user is authenticated (login)
2/ if yes he can post a new article
if not he can only read article
"""
if request.method == "GET":
articles = actualArticle.getAll()
return articles
elif request.method == 'PUT':
if 'logged_in... | 5,348,443 |
def test_dev_exception_logging(caplog: LogCaptureFixture) -> None:
"""Test that exceptions are properly logged in the development logger."""
configure_logging(name="myapp", profile="development", log_level="info")
logger = structlog.get_logger("myapp")
try:
raise ValueError("this is some except... | 5,348,444 |
def test_withStatementComplicatedTarget():
""" If the target of a statement uses any or all of the valid forms
for that part of the grammar
(See: http://docs.python.org/reference/compound_stmts.html#the-with-statement),
the names involved are checked both for definedness and any bindings
created ar... | 5,348,445 |
def update_ref(refname, newval, oldval):
"""Change the commit pointed to by a branch."""
if not oldval:
oldval = ''
assert(refname.startswith('refs/heads/'))
p = subprocess.Popen(['git', 'update-ref', refname,
newval.encode('hex'), oldval.encode('hex')],
... | 5,348,446 |
def normalize_citation(line: str) -> Union[Tuple[str, str], Tuple[None, str]]:
"""Normalize a citation string that might be a crazy URL from a publisher."""
warnings.warn("this function has been externalized to :func:`citation_url.parse`")
return citation_url.parse(line) | 5,348,447 |
def cnn_predict_grid(data_in=None,
win_sizes=[((int(8), int(5)), 2, 1),((int(10), int(6)), 3, 2),((int(13), int(8)), 4, 3)],
problim = 0.95,
model_fpath=model_fpath,
scaler_fpath=scaler_fpath,
nc_fpath='D:/Master/data/cmems_data/global_10km/noland/phys_nolan... | 5,348,448 |
def connect_syndicate( username=CONFIG.SYNDICATE_OPENCLOUD_USER, password=CONFIG.SYNDICATE_OPENCLOUD_PASSWORD, user_pkey_pem=CONFIG.SYNDICATE_OPENCLOUD_PKEY ):
"""
Connect to the OpenCloud Syndicate SMI, using the OpenCloud user credentials.
"""
debug = True
if hasattr(CONFIG, "DEBUG"):
debu... | 5,348,449 |
def test_docker_run_implies_container_method():
"""
If a value is given for the ``--docker-run`` argument then the method is
*container*.
"""
args = telepresence.cli.parse_args([
"--docker-run", "foo:latest", "/bin/bash"
])
assert args.method == "container" | 5,348,450 |
def join(var, wrapper, message):
"""Either starts a new game of Werewolf or joins an existing game that has not started yet."""
# keep this and the event in fjoin() in sync
evt = Event("join", {
"join_player": join_player,
"join_deadchat": join_deadchat,
"vote_gamemode": vote_gamemod... | 5,348,451 |
def get_all_comb_pairs(M, b_monitor=False):
"""returns all possible combination pairs from M repeated measurements (M choose 2)
Args:
M (int): number of measurements per
Returns:
indices1, incides2
"""
indices1 = np.zeros(int(M*(M-1)/2))
indices2 = np.zeros(int(M*(M-1)/2... | 5,348,452 |
def gomc_sim_completed_properly(job, control_filename_str):
"""General check to see if the gomc simulation was completed properly."""
with job:
job_run_properly_bool = False
output_log_file = "out_{}.dat".format(control_filename_str)
if job.isfile(output_log_file):
# with ope... | 5,348,453 |
def test_teams_new_get():
"""Can a user get /teams/new"""
app = create_ctfd(user_mode="teams")
with app.app_context():
register_user(app)
with login_as_user(app) as client:
r = client.get("/teams/new")
assert r.status_code == 200
destroy_ctfd(app) | 5,348,454 |
def test_border():
"""Test border."""
app = MakeApp(srcdir='tests/marktest', copy_srcdir_to_tmpdir=True,
confoverrides={'sphinxmark_border': 'left'})
app.builder.build_all()
assert app.config.sphinxmark_border == 'left'
html = Path(path.join(app.outdir, htmlfile)).read_text()
... | 5,348,455 |
def debounce(timeout, **kwargs):
"""Use:
@debounce(text=lambda t: t.id, ...)
def on_message(self, foo=..., bar=..., text=None, ...)"""
keys = sorted(kwargs.items())
def wrapper(f):
@functools.wraps(f)
def handler(self, *args, **kwargs):
# Construct a tuple of keys from t... | 5,348,456 |
def trainval(exp_dict, savedir, args):
"""
exp_dict: dictionary defining the hyperparameters of the experiment
savedir: the directory where the experiment will be saved
args: arguments passed through the command line
"""
# 2. Create data loader and model
train_loader = he.get_loader(
... | 5,348,457 |
def test_disease_gene_example_dwwc(dwwc_method):
"""
Test the PC & DWWC computations in Figure 2D of Himmelstein & Baranzini
(2015) PLOS Comp Bio. https://doi.org/10.1371/journal.pcbi.1004259.g002
"""
graph = get_graph("disease-gene-example")
metagraph = graph.metagraph
# Compute GiGaD path... | 5,348,458 |
def delete_local_group(self):
"""
Delete local group
:param self: MainController object
:return: None
"""
self.log('Delete local group by clicking on "DELETE GROUP" button...')
self.wait_until_visible(type=By.ID, element=popups.LOCAL_GROUP_DELETE_GROUP_BTN_ID).click()
self.log('... and c... | 5,348,459 |
def isolated_add_event(event, quiet=True):
"""
Add an event object, but in its own transaction, not bound to an existing transaction scope
Returns a dict object of the event as was added to the system
:param event: event object
:param quiet: boolean indicating if false then exceptions on event add... | 5,348,460 |
def get_publishers():
""" Fetch and return all registered publishers."""
url = current_app.config['DATABASE']
with psycopg2.connect(url) as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM userrole WHERE is_publisher = %s ORDER BY reg_date DESC;", ('true',))
res = ... | 5,348,461 |
def acs_map():
"""call after curses.initscr"""
# can this mapping be obtained from curses?
return {
ord(b'l'): curses.ACS_ULCORNER,
ord(b'm'): curses.ACS_LLCORNER,
ord(b'k'): curses.ACS_URCORNER,
ord(b'j'): curses.ACS_LRCORNER,
ord(b't'): curses.ACS_LTEE,
ord(... | 5,348,462 |
def get_polymorphic_ancestors_models(ChildModel):
"""
ENG: Inheritance chain that inherited from the PolymorphicModel include self model.
RUS: Наследуется от PolymorphicModel, включая self.
"""
ancestors = []
for Model in ChildModel.mro():
if isinstance(Model, PolymorphicModelBase):
... | 5,348,463 |
def plot_load_vs_fractional_freq_shift(all_data,ax=None):
"""
Plot fractional frequency shift as a function of load temperature for all resonators
"""
if ax is None:
fig,ax = plt.subplots(figsize=(8,8))
for name, group in all_data.groupby('resonator_index'):
ax.plot(group.sweep_prima... | 5,348,464 |
def cli(env):
"""Displays bandwidth pool information
Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr
"""
manager = AccountManager(env.client)
items = manager.get_bandwidth_pools()
table = formatting.Table([
"Id",
"Pool Name",
"Region",
"Servers"... | 5,348,465 |
def encode_dist_anchor_free_np(gt_ctr, gt_offset, anchor_ctr, anchor_offset=None):
"""
3DSSD anchor-free encoder
:param:
gt_ctr: [bs, points_num, 3]
gt_offset: [bs, points_num, 3]
anchor_ctr: [bs, points_num, 3]
anchor_offset: [bs, points_num, 3]
:return:
encoded_... | 5,348,466 |
def BCrand(h, hu, t, side, mean_h, amplitude, period, phase):
""" Conditions aux limites du modele direct, avec plus de paramètres"""
if side == 'L':
h[0] = mean_h + amplitude * np.sin((t * (2 * np.pi) / period) + phase)
hu[0] = 0.0
elif side == 'R':
h[-1] = h[-2]
hu[-1] = hu... | 5,348,467 |
def dumpproc(stdout, stderr=None):
"""
print stdout/stderr of a process
"""
if stdout is not None and len(stdout) > 0:
print(" ", "=" * 20, "BEGIN STDOUT", "=" * 20)
for line in stdout.decode().splitlines():
print(" ", f"{Style.DIM}{line}{Style.RESET_ALL}")
print(" ",... | 5,348,468 |
def pyplot(
figure=None,
scale: float = 0.8,
clear: bool = True,
aspect_ratio: typing.Union[list, tuple] = None
) -> str:
"""
:param figure:
:param scale:
:param clear:
:param aspect_ratio:
:return:
"""
environ.abort_thread()
from bs4 import Beautif... | 5,348,469 |
def simplify(graph):
""" helper that simplifies the xy to mere node ids."""
d = {}
cnt = itertools.count(1)
c2 = []
for s, e, dst in graph.edges():
if s not in d:
d[s] = next(cnt)
if e not in d:
d[e] = next(cnt)
c2.append((d[s], d[e], dst))
g = Gr... | 5,348,470 |
def delete(name: str) -> None:
"""
Delete a character.
:param name: the character's name
"""
con = kingdomsouls.database.connect()
with con:
try:
con.execute(
"""
DELETE FROM characters
WHERE name = ?
""",
... | 5,348,471 |
def _get_class_for(type):
"""Returns a :type:`class` corresponding to :param:`type`.
Used for getting a class from object type in JSON response. Usually, to
instantiate the Python object from response, this function is called in
the form of ``_get_class_for(data['object']).from_data(data)``.
:type... | 5,348,472 |
def _query_jupyterhub_api(method, api_path, post_data=None):
"""Query Jupyterhub api
Detects Jupyterhub environment variables and makes a call to the Hub API
Parameters
----------
method : string
HTTP method, e.g. GET or POST
api_path : string
relative path, for example /users/... | 5,348,473 |
def PoolingOutputShape(input_shape, pool_size=(2, 2),
strides=None, padding='VALID'):
"""Helper: compute the output shape for the pooling layer."""
dims = (1,) + pool_size + (1,) # NHWC
spatial_strides = strides or (1,) * len(pool_size)
strides = (1,) + spatial_strides + (1,)
pads = co... | 5,348,474 |
def libre_office(odt_list, pdf_dir):
"""Convert a list of odt-files to pdf-files.
The input files are provided as a list of absolute paths,
<pdf_dir> is the absolute path to the output folder.
"""
# Use LibreOffice to convert the odt-files to pdf-files.
# If using the appimage, the paths MUST be absolut... | 5,348,475 |
def parse_config_file(config_file_path: Path) -> List[TabEntry]:
""" Parse the json config file, validate and convert to object structure """
app_config = None
Logger().info(f"Loading file '{config_file_path}'...")
if not config_file_path.is_file():
Logger().error(f"Config file '{config_file_pa... | 5,348,476 |
def create_app():
""" 工厂函数 """
app = Flask(__name__)
register_blueprint(app)
# register_plugin(app)
register_filter(app)
register_logger()
return app | 5,348,477 |
async def nasapod(ctx):
"""gives NASA's image of the day"""
await ctx.send(astrof()) | 5,348,478 |
def passwordbox(**kwargs):
"""
This wrapper is for making a dialog for changing your password.
It will return the old password, the new password, and a confirmation.
The remaining keywords are passed on to the autobox class.
"""
additional_fields = kwargs.get("additional_fields") and kwar... | 5,348,479 |
def unravel_hpx_index(idx, npix):
"""Convert flattened global map index to an index tuple.
Parameters
----------
idx : `~numpy.ndarray`
Flat index.
npix : `~numpy.ndarray`
Number of pixels in each band.
Returns
-------
idx : tuple of `~numpy.ndarray`
Index array... | 5,348,480 |
def install_apt_pkg():
"""
Install my own usefull package, won't explain more about why :P
"""
apt_manager = AptManager()
apt_manager.commit()
all_pkg = ['nano', 'htop', 'tmux', 'vim', 'cmake',
'libncurses5-dev', 'libncursesw5-dev', 'git',
'tree', 'zip', 'expect', '... | 5,348,481 |
def map2sqldb(map_path, column_names, sep='\t'):
"""Determine the mean and 2std of the length distribution of a group
"""
table_name = os.path.basename(map_path).rsplit('.', 1)[0]
sqldb_name = table_name + '.sqlite3db'
sqldb_path = os.path.join(os.path.dirname(map_path), sqldb_name)
conn = ... | 5,348,482 |
def parse_revdep(value):
"""Value should be an atom, packages with deps intersecting that match."""
try:
targetatom = atom.atom(value)
except atom.MalformedAtom as e:
raise argparser.error(e)
val_restrict = values.FlatteningRestriction(
atom.atom,
values.AnyMatch(values.F... | 5,348,483 |
def is_context_word(model, word_a, word_b):
"""Calculates probability that both words appear in context with each
other by executing forward pass of model.
Args:
model (Mode): keras model
word_a (int): index of first word
word_b (int): index of second word
"""
# define ... | 5,348,484 |
def map_and_save_gene_ids(hit_genes_location, all_detectable_genes_location=''):
"""
Maps gene names/identifiers into internal database identifiers (neo4j ids) and saves them
:param hit_genes_location: genes in the set we would like to analyse
:param all_detectable_genes_location: genes in the set tha... | 5,348,485 |
def next_method():
"""next, for: Get one item of an iterators."""
class _Iterator:
def __init__(self):
self._stop = False
def __next__(self):
if self._stop:
raise StopIteration()
self._stop = True
return "drums"
return next(_... | 5,348,486 |
def get_ingress_deployment(
serve_dag_root_node: DAGNode, pipeline_input_node: PipelineInputNode
) -> Deployment:
"""Return an Ingress deployment to handle user HTTP inputs.
Args:
serve_dag_root_node (DAGNode): Transformed as serve DAG's root. User
inputs are translated to serve_dag_ro... | 5,348,487 |
def get_project_settings(project):
"""Gets project's settings.
Return value example: [{ "attribute" : "Brightness", "value" : 10, ...},...]
:param project: project name or metadata
:type project: str or dict
:return: project settings
:rtype: list of dicts
"""
if not isinstance(project... | 5,348,488 |
def guard(M, test):
"""Monadic guard.
What it does::
return M.pure(Unit) if test else M.empty()
https://en.wikibooks.org/wiki/Haskell/Alternative_and_MonadPlus#guard
"""
return M.pure(Unit) if test else M.empty() | 5,348,489 |
def get_git_hash() -> str:
"""Get the git hash."""
rv = _run("git", "rev-parse", "HEAD")
if rv is None:
return "UNHASHED"
return rv | 5,348,490 |
def primary_style():
""" a blue green style """
return color_mapping(
'bg:#449adf #ffffff',
'bg:#002685 #ffffff',
'#cd1e10',
'#007e3a',
'#fe79d1',
'#4cde77',
'#763931',
'#64d13e',
'#7e77d2',
'bg:#000000 #ffffff',
) | 5,348,491 |
def test_add_index_with_string_list():
"""test index add with list of string(64)."""
header = ShardHeader()
schema_json = {"id": {"type": "number"}, "name": {"type": "string"},
"label": {"type": "string"}, "key": {"type": "string"}}
schema = header.build_schema(schema_json, ["key"], "... | 5,348,492 |
def decrypt_files(rsa_key):
"""
Decrypt all encrypted files on host machine
`Required`
:param str rsa_key: RSA private key in PEM format
"""
try:
if not isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey):
rsa_key = Crypto.PublicKey.RSA.importKey(rsa_key)
if not rsa... | 5,348,493 |
def _bivariate_uc_uc(
lhs,rhs,
z,
dz_dl, # (dz_re_dl_re, dz_re_dl_im, dz_im_dl_re, dz_im_dl_im)
dz_dr # (dz_re_dr_re, dz_re_dr_im, dz_im_dr_re, dz_im_dr_im)
):
"""
Create an uncertain complex number as a bivariate function
This is a utility method for implementing mathematical
function... | 5,348,494 |
def smoothing_filter(time_in, val_in, time_out=None, relabel=None, params=None):
"""
@brief Smoothing filter with relabeling and resampling features.
@details It supports evenly sampled multidimensional input signal.
Relabeling can be used to infer the value of samples at
... | 5,348,495 |
async def test_rgb_light_custom_effect_via_service(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test an rgb light with a custom effect set via the service."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
... | 5,348,496 |
def get_selector_qty(*args):
"""get_selector_qty() -> int"""
return _idaapi.get_selector_qty(*args) | 5,348,497 |
def get(
host: str,
path: str,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
authenticated: bool = True,
stream: bool = False,
) -> requests.Response:
"""
Send a GET request to the remote API.
"""
return do_request(
"GET",
host... | 5,348,498 |
def test_find_outermost_module_name():
"""
This test intents to ensure that the utility function `find_module_name` will
find the correct outermost module name for a given filepath by default
"""
# given
package_path = build_path("test_find_outermost_module_name", "some_package")
inner_modul... | 5,348,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.