content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import argparse
import getpass
def build_annofabapi_resource(args: argparse.Namespace) -> annofabapi.Resource:
"""
annofabapi.Resourceインスタンスを生成する。
以下の順にAnnoFabの認証情報を読み込む。
1. `.netrc`ファイル
2. 環境変数`ANNOFAB_USER_ID` , `ANNOFAB_PASSWORD`
認証情報を読み込めなかった場合は、標準入力からUser IDとパスワードを入力させる。
Returns:
... | 0a633437b80dd39a81b0c608b1a2ee58d04a7950 | 69,700 |
def c_lpf(img, pixel_size, cutoff_freq):
"""
Implements a coherent low pass filter in the spatial-frequency
domain
Args:
img: input image
pixel_size: pixel size of detector
cutoff_freq: cut off frequency
Returns:
Coherently low pass filtered image
"""
height... | 438d16f36cd62bededd34b4e221ebbe54fad528a | 69,701 |
def _attr_list_to_dict(attr_list):
"""
_attr_list_to_dict -- parse a string like: host:ami, ..., host:ami into a
dictionary of the form:
{
host: ami
host: ami
}
if the string is in the form "ami" then parse to format
{
default: ami
}
raises ValueError if lis... | 378b1a55d908750eea2b457e35abce0a17364a41 | 69,702 |
import typing
from typing import Union
from typing import Dict
from typing import Any
def Hover(
attributes: dict = {},
children: list = [],
class_: str = None,
close_delay: typing.Union[float, str] = None,
disabled: bool = None,
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_... | 7d9910b897996025bb188889215020d524a66982 | 69,703 |
import networkx as nx
import pandas as pd
import seaborn as sns
import itertools
def plot_interaction_heatmap(G, th=0.5, method='ward', metric='euclidean', z_score=None, standard_scale=None, figsize=None, save=None):
"""plots a heatmap of logaritmized interaction scores for each Source-->Target combination.
... | 269d1c7e897ce0908e3e7b8517ef6c100ba4edf2 | 69,704 |
def wrapper_range(args):
"""
Simple wrapper, useful for debugging.
:param args: the arguments to process_piece
:return: the same as process_piece
"""
#print(str(args))
return process_range_bam(*args) | 4e487c5bff002363812be7ea9bf2168b4cd78c02 | 69,705 |
def compute_adv_profile(
ds_profile, da_domain, gradient_method, advection_velocity_sampling_method
):
"""
Compute the horizontal advective tendency profile and reference profile for
a field `da_domain` (named `phi` here) for a point on trajectory (defined
by `lat` and `lon` on `ds_profile`) with ho... | daba46953bc7232062df1a1df4cb774b4db9c61a | 69,706 |
def matmul_scalar(c, b):
"""
Multiplies a given numpy array (b) by a given scalar value (c)
:param c: (ndarray)
:param b: (ndarray)
:return: (ndarray) same shape as b
"""
return np.multiply(c, b) | 17486b55ad3db717b4a0fe2b3a7420ed060f4b69 | 69,707 |
def example_freq():
"""Example staypoints with 4 location for 2 users with [3, 2, 1, 1] staypoint per location."""
list_dict = [
{"user_id": 0, "location_id": 0},
{"user_id": 0, "location_id": 0},
{"user_id": 0, "location_id": 0},
{"user_id": 0, "location_id": 1},
{"user_... | 17a0218b8ac3d01f407325aff1f4f75d1c052609 | 69,708 |
def get_job_locations_from_db(loc_list):
"""Get the number of jobs by country as a dictionary."""
countries = {}
for loc in loc_list:
country = loc.split()[-1].lower()
if country == 'usa' or country == 'states' or country == 'us':
countries.setdefault('usa', 0)
countr... | dd394bc6889be4e87f55bc523e4a9bc5d4ed617a | 69,709 |
def base():
""" Method for running the base script, which creates the images. """
try:
base.create_all_final_demo()
return render_template('base_success.html')
except:
return render_template('base_failure.html') | 6796ec60957231d8f8d0a6c6e239a1c37a27436c | 69,710 |
import os
import psutil
import time
def get_group_log(worker_type, unit, status, task='overall', inc_children=False):
"""
Return a string with log information intended to track how long a group of units takes
Arguments:
worker_type = The type of worker this is (Profile, Merge, etc.)
unit... | 01b3525959211dcb6af42ad2edac858d07cc4bd9 | 69,711 |
def keysym_to_str(keysym):
"""
convert a keysym to its equivalent character or
key description and return it.
Returns an empty for an unknown keysym.
That's just a shortcut for :mod:`ooxcb.keysymdef`.
"""
return keysymdef.names.get(keysym, '') | 226a5a09aa37e025be8580c2d67f8280b40fbd49 | 69,712 |
import os
import numpy
from datetime import datetime
import calendar
def pointchart(var, coords, path, files):
"""
Description: generates a timeseries for a given point and given variable defined by the user.
Arguments: A dictionary object from the AJAX-ed JSON object that contains coordinates and the var... | 0075e534680493d4135c358fc3f67ad638a627e5 | 69,713 |
def find_cho_ccc(atoms):
"""
C
/
R-C----C-H
|| \
O C
or
H C
| /
R-C----C-H
| \
O C
or
H S
| /
R-C----C-H
| \
O S
example:
(5R)-5-C-Cyclohexyl-5-C-phenyl-D-xylos... | 21c509b2b3c6fe1bca44b19ca6f613059c6d7baa | 69,714 |
import json
import difflib
def spec_diff(request, spec1=None, spec2=None):
"""
Allow the user to select two specs to diff.
"""
specs = Spec.objects.all().order_by("name")
if not spec1 or not spec2:
return render(request, "specs/diff.html", {"specs": specs})
spec1 = get_object_or_404(S... | 07e4c347c488db8ea87b443df775734f5b01bcbf | 69,715 |
import argparse
def main():
"""Run main program."""
parser = argparse.ArgumentParser(
description="Parse arguments for models.")
parser.add_argument(
"--indir", help="Dataset directory.",
default="../data/frankfurt/FSE_metadata.csv")
parser.add_argument('--outdir', help='Model... | 440889e838d1bcfc12c71eab8aea7c175bb2612b | 69,716 |
def is_correct_extension(filename):
"""Checks if a file is a required sample.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known sample extension
"""
filename_lower = filename.lower()
return any(filename_lower.endswith(ext) for ext in EX... | 54f48f8fd247f043ce74e2f84190468b67196a7b | 69,717 |
def softmax_loss(theta, x, y, learning_rate=None):
"""
Categorical cross-entropy / softmax loss.
The cost function for multi-class logistic regression.
"""
# theta = np.matrix(theta)
# x = np.matrix(X)
# y = np.matrix(y)
first = np.multiply(-y, np.log(sigmoid_activation(x * theta.T)))
... | 56065c1f2bba4dfe27379079a8e8e549dc9aa6ae | 69,718 |
def get_formatted_el(
element: str,
sym_label: str,
use_oxi_state: bool = True,
use_sym_label: bool = True,
fmt: str = "raw",
):
"""Formats an element string.
Performs a variety of functions, including:
- Changing "Sn+0" to "Sn".
- Inserting the symmetry label between the element a... | 87d379236b0979dc6d6680caa4f5622f3530ed1b | 69,719 |
import os
def rdkit_featuredefinition():
""" Loads rdkit chemical feature factory.
Returns
-------
rdkit.Chem.rdMolChemicalFeatures.MolChemicalFeatureFactory
The feature factory.
"""
fdefName = os.path.join(RDConfig.RDDataDir,'BaseFeatures.fdef')
return Chemic... | 14c775f9081326d709039d745fdea3d24d469ba3 | 69,720 |
def bct_lattice(
q_values,
unitcell_param,
pivot,
euler_angles=(0, 0, 0),
offset_indices=False,
verbose=False,
):
"""
Calculate Bragg peaks positions for a BCT unit cell.
The long axis is by default along qz (vertical up).
:param q_values: tuple of 1D arrays (qx, qz, qy), q_val... | 22976c3c88fcc6b818bb5ac49c0b2d179176037c | 69,721 |
import pathlib
from typing import Any
import os
def generate_parser_c_extension(
grammar: Grammar, path: pathlib.PurePath, debug: bool = False
) -> Any:
"""Generate a parser c extension for the given grammar in the given path
Returns a module object with a parse_string() method.
TODO: express that us... | 8cdce9891ae38470b54ef218cc0cee9be94b3fb5 | 69,722 |
def efun(pretrained=False, **kwargs):
""" eFUN """
# NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2
model = _gen_efun(
'eFUN', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)
return model | 5ba6f1de42cce50b1556df3126b2abfbc42bd589 | 69,723 |
from typing import Tuple
async def parse_avito_products_update(url: str, user_id: str) -> Tuple[list, list]:
"""Parse avito url and find new and updated products."""
avito_page = await get_avito_soup_page(url)
if not avito_page:
raise HTTPError('Failed to download search page', request=url)
pr... | 53e6353ab90260299e7a4b05661a883b112a3b8f | 69,724 |
def calc_nrmse(tar_img, ref_img, norm_type='Euclidean'):
"""Compute the normalized root mean-squared error (NRMSE) between two images.
Parameters
----------
tar_img : sitk
Test image.
ref_img : sitk
Ground-truth image.
norm_type : {'Euclidean', 'min-max', 'mean'}
Controls... | 964c663c70a75216a6a842d329c2bd40512f8e53 | 69,725 |
def humansize(nbytes):
"""
Translates a size in bytes to a human readable size format
:param int nbytes: integer of size of torrent file
:return: size in bytes in a human readable format
:rtype: str
"""
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
i = 0
while nbytes >= 1024 and i < len(su... | 98390c0f5c471b501caf2fa2bba1e593c8a17eb6 | 69,726 |
def _parser(date):
"""
date parser to cast a string in the format "%d/%m/%Y" to a date
"""
return pd.datetime.strptime(date, "%d/%m/%Y") | fbe163910d48374c34d46fda2367eded4fdaad8f | 69,727 |
def pad_sents(sents, padding_token_index):
"""
Pad the sents(in word index form) into same length so they can form a matrix
# 15447
>>> sents = [[1,2,3], [1,2], [1,2,3,4,5]]
>>> pad_sents(sents, padding_token_index = -1)
[[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]]
"""
... | 0063d8716f7081644e4353de662d58f0dc04e8fe | 69,728 |
def gm_constrs(t, x_list, p):
""" Form the internal CXVPY constraints to form the weighted geometric mean t <= x^p.
t <= x[0]^p[0] * x[1]^p[1] * ... * x[n]^p[n]
where x and t can either be scalar or matrix variables.
Parameters
----------
t : cvx.Variable
The epigraph variable
x... | 614e283beb3ad7148df78e227ff360bc6bb2080d | 69,729 |
from typing import List
def multi_gate(size: int, targets: List[int], gate: Gate, phi=0j) -> Matrix:
"""
Constructs a (2**size by 2**size) gate matrix that applies a
specific gate to one or more specified qubits
:param size int: total number of qubits in circuit
:param targets List[int]: list of ... | a447968e1aa4c12dbecf02c26ec14dd2b75f2c97 | 69,730 |
def get_instances_with_configs(configs):
"""Create Monsoon instances from a list of dict configs.
Each config should have the required key-value pair
'serial': <an integer id>.
Args:
configs: A list of dicts each representing the configuration of one
Monsoon.
Returns:
A ... | a08e253daf5bb338f4530d9c71c39917c9f755f4 | 69,731 |
import hashlib
def md5_md5_md5_pass(string, salt=None, **placeholder):
"""
Create an MD5 hash in a specific format md5(md5(md5(pass)))
> :param string: string to be hashed
> :return: a MD5 hash in the above format
Example
>>> md5_md5_md5_pass("test")
25ab3b38f7afc116f18fa... | 9f91ed6abe8656292a1a1607c5c3eda377a5a4c7 | 69,732 |
def twoclass(y_true, y_pred_proba, threshold=0.5, classnames=None, normalize=False, title='', cmap=plt.cm.Blues, showfig=True, verbose=3):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
cm = confusion_matrix(y_true, y_pred_prob... | 016d9cb5e6dfe1d862040adad4401c24f34575d0 | 69,733 |
from typing import ChainMap
def apply_blocks(molecule, blocks):
"""
Generate a new :class:`~vermouth.molecule.Molecule` based on the residue
names and other attributes of `molecule` from `blocks`.
Parameters
----------
molecule: vermouth.molecule.Molecule
The molecule to process.
... | 2f598608d50daa9bc9c2073977d42e1135676dea | 69,734 |
def absolutify(url):
"""Takes a URL and prepends the SITE_URL"""
site_url = getattr(settings, "SITE_URL", False)
# If we don't define it explicitly
if not site_url:
protocol = settings.PROTOCOL
hostname = settings.DOMAIN
port = settings.PORT
if (protocol, port) in (("htt... | 160e3d272c3b38b559f2a54f27778e5f4711de77 | 69,735 |
import os
def file_extension_detect(filename):
"""Determine if file is notebook or RDF,
based on the file extension.
"""
_, extension = os.path.splitext(filename)
rdf_exts = ['.ttl', '.nt', '.jsonld', '.json']
nb_exts = ['.ipynb']
if extension in rdf_exts:
return 'RDF'
elif ext... | 430cf1b12ae4bde6cc336f58f0a1fdc727369209 | 69,736 |
def clamp(minimum, n, maximum):
"""Return the nearest value to n, that's within minimum to maximum (incl)
"""
return max(minimum, min(n, maximum)) | a3db191a733041196b8a3e0cfc83731e839a14aa | 69,737 |
from typing import Optional
from typing import Union
import ray
def resume(workflow_id: str,
storage: Optional[Union[str, Storage]] = None) -> ray.ObjectRef:
"""Resume a workflow asynchronously. See "api.resume()" for details.
"""
if isinstance(storage, str):
store = create_storage(stor... | 1be5cb24b0109858f0d106a14fedfe907d1997c8 | 69,738 |
def metadata():
"""
Returns an XML with the SAML 2.0 metadata for this
SP as configured in the saml2_settings.py file.
"""
metadata = entity_descriptor(current_app.saml2_config)
response = make_response(metadata.to_string(), 200)
response.headers['Content-Type'] = "text/xml; charset=utf8"
... | 683db354980f57aa4f74f3cdb67db1098decde48 | 69,739 |
def boxlist_to_masklist(boxlist):
"""Converts a BoxList containing 'masks' into a BoxMaskList.
Args:
boxlist: An np_box_list.BoxList object.
Returns:
An BoxMaskList object.
Raises:
ValueError: If boxlist does not contain `masks` as a field.
"""
if not boxlist.has... | dd7608874ad4ae476fa9789b5c7d650bb672d4b6 | 69,740 |
from typing import List
from typing import Optional
def setup_optima(x: np.ndarray,
optima: List[float],
optima_label: str,
ax: Optional[Axes] = None) -> Axes:
"""Set up optima.
:param x:
:param optima:
:param optima_label:
:param ax: Plot into t... | 67afd52f8157fed689554de91c4cef19bb413106 | 69,741 |
import sys
def move(start, dir):
"""
"""
if dir == "U":
mv = (-1, 0)
elif dir == "D":
mv = (1, 0)
elif dir == "L":
mv = (0, -1)
elif dir == "R":
mv = (0, 1)
else:
print("Direction needs to be U D L or R. Exiting")
sys.exit(1)
end = (start[0] + mv[0], start[1] + mv[1])
if end[0] < 0 or end[0] > 4... | 7e40bc61eb3d765985207ad62d69683b0546321f | 69,742 |
import operator
def normalize_data(data):
"""Normalizes a sequence of input data according to the heuristic
laid out in the module documentation.
"""
data = data or []
if isinstance(data, dict):
data = [{"key": key, "value": value} for key, value in data.items()]
data.sort(key=oper... | d1cacf020cd8df2762f747a85a41a758e1e12ba8 | 69,743 |
def get_expression(adata, use_raw=True, use_geosketch=False, geosketch_N=10000, geosketch_transform=None):
"""Grab expression and put into pandas dataframe."""
if use_raw:
ad = adata.raw
else:
ad = adata
if isinstance(ad.X, csr_matrix):
df = pd.DataFrame(ad.X.toarray(), index=ad... | 7ba894df1eac5ccd30775162a700a7b0071b0f41 | 69,744 |
import matplotlib.pyplot as plt
def plot_etotal(ecut_list, etotals, aug_ratios, **kwargs):
"""
Uses Matplotlib to plot the energy curve as function of ecut
Args:
ecut_list:
List of cutoff energies
etotals:
Total energies in Hartree, see aug_ratios
aug_ratio... | 9b44fdaa675e23cfe3d52888f0b084b341c725c1 | 69,745 |
import time
def get_frequency(rss: fp.util.FeedParserDict) -> int:
"""
Calculate the average time gap between episodes.
Parameters
----------
rss : fp.util.FeedParserDict
RSS feed of the podcast.
Returns
-------
int
"""
if rss is None or not rss["entries"]:
re... | e3dc4daabc1a981265cf0fa649cfab2b3d4c8ffc | 69,746 |
import typing
def gen_allowed_hosts_setting() -> typing.List[str]:
"""ALLOWED_HOSTS setting."""
allowed_hosts = ENV.get(f"{ENV_VAR_PREFIX}_ALLOWED_HOSTS")
if not allowed_hosts:
return []
return [host for host in allowed_hosts.split(",") if host] | c15aac536d60dea1eb816c865d739f47b5c71ef7 | 69,747 |
def get_vehicle_mass(vehicle_info):
"""
Get the mass of a carla vehicle (defaults to 1500kg)
:param vehicle_info: the vehicle info
:type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo
:return: mass of a carla vehicle [kg]
:rtype: float64
"""
mass = 1500.0
if vehicle_info.mass:
... | 216f109e9f963ba6de92cf168055b1a7e516d777 | 69,748 |
def has_table(table):
"""Return True if the given backend has a table of the given name."""
return ENGINE.has_table(table) | 3ece338172776c0d73c8e82b8a1269c64e79c526 | 69,749 |
def _make_raw_request(host, port, method, path, body=None, request_headers=None, secure=False, timeout=None):
"""
issue a request to a specific host & port, for a specified method, on a
specified path with a specified (optional) body (encrypted per the
connection), and return the response (status, reaso... | b987cd4637581a0dcbc8ba6b3c6f1ba1dfce8f70 | 69,750 |
def read_instruction(fio, start_pos):
"""
Reads a single instruction from `fio` and returns it, or ``None`` if
the stream is empty.
:param fio: Any file-like object providing ``read()``.
:param start_pos: The current position in the stream.
"""
op = fio.read(1)
if not op:
retur... | f7a282019507a7387ea08fc2313355513565eaaa | 69,751 |
def attribute_conversion(word, from_pos):
""" This function converts a word to a noun using the attribute method from WordNet"""
# The attribute method exists for adjectives I think
synsets = wn.synsets(word, from_pos)
# Word not found
if not synsets:
return []
result =[]
attribute_lis... | e49a57cdf878a2aecf2c21345d280c411c0e2414 | 69,752 |
def add_modules_to_metadata(modules, metadata):
"""
modules is a list of lists of otus, metadata is a dictionary of dictionaries where outer dict keys
are features, inner dict keys are metadata names and values are metadata values
"""
for module_, otus in enumerate(modules):
for otu in otus:... | b1dcd3e179a01c11d5a847094ceef4240d2b899e | 69,753 |
def do_maximisation_step(resp_mat, data_set):
"""
Finds the mu, cov and pi (weights) that maximise the data log likelihood
:param resp_mat: (m x K) matrix, responsibility matrix (K = num_classes, m = num of datapoints)
:param data_set: (m x n) matrix, dataset with each row a single example (m = num data... | 5bd5b2a7e4add811c4cfe3d5312ec710b4b3dc27 | 69,754 |
def longest_word(list_name):
"""Stores the number of rows. """
long_word = [0] * len(list_name) #Stores number of items in each sublist
i = 0
for column in list_name: #counts words in each sublist
l_word = 0
for word in column:
l_word += 1
long_word[i] = l_word
... | 932f250b50fc3c8161545e7c4741b255483923e5 | 69,755 |
def _get_passthru_keys(spec, zip_keys=None, extend_keys=None):
"""
Keys in `spec` that are not exploded and are simply carried over from the `spec`
into the variants without modification.
:param spec: Variants specification
:type spec: dict
:param zip_keys: Keys defined as 'zip_keys' (see :func... | 5f57353f0fa6885e36a430c9ef13f104937bad0a | 69,756 |
def _dataset_parser(value):
"""Parse a CIFAR-10 record from value."""
featdef = {
'image': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64),
}
example = tf.parse_single_example(value, featdef)
image = tf.decode_raw(example['image'], tf.uint8)
image.se... | b8a0acb219ee752a34f1fc373f525a601b00060b | 69,757 |
def clone_models(d):
""" Clone bokeh models in a dict.
Parameters
----------
d : dict
The input dict.
Returns
-------
d : dict
A copy of the input dict with all bokeh models replaced by a clone of
themselves.
"""
d = d.copy()
for k, v in d.items():
... | c8c225a9170e20c74912c60766a0dec230c3f0f7 | 69,758 |
from typing import Tuple
def refit_reg(x_train: np.ndarray, y: np.ndarray, l1_grid_size: int, l1_exp_scale: float,
max_penalty: float, interp: bool = True
) -> Tuple[np.ndarray, float, np.ndarray]:
"""
Final model refit with regularization
Args:
x_train:
y:
... | 9ea9fc1c223e739a116dd9c449e0126d39717560 | 69,759 |
from typing import List
def parse_virus_preset_dump(msg: Message) -> List[int]:
"""
strips sysex header and checksum bits to return list of preset patches
"""
data = list(msg.data[len(VIRUS_SYSEX_HEADER): -len(VIRUS_SYSEX_CHECKSUM)])
assert len(data) == 256
return data | a42e0861f80b584910e99f307307196a07cbd9d6 | 69,760 |
def rejudge(request):
"""Ajax method: Rejudge a single submission `id`"""
user = User.getCurrent(request)
id = request.POST["id"]
submission = Submission.get(id)
runCode(submission, user)
return JsonResponse(submission.result, safe=False) | 3bf53bb2fa6b38970659a3b85612df520571704b | 69,761 |
def get_sobel_kernels():
"""
Returns the Sobel operator kernels
https://en.wikipedia.org/wiki/Sobel_operator
"""
K_sobel_x = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
K_sobel_y = np.array([[1, 2, 1],
[0, 0, 0],
... | 27b96f131dbff00819358336551dacd266756811 | 69,762 |
def LabelAnalyzer():
"""
A analysis factory function for MeTaL.
"""
return analysis | 8180352955157c680fbc437c0e22a93e5a721a20 | 69,763 |
def job_to_json(job):
""""Convert a Job object to json via its associated
ModelSchema class
"""
json_dict = JobSchema().dump(job).data
# Sort lists
# json_dict["families"] = sorted(json_dict["families"],
# key=lambda p: p.get("name"))
return json_dict | fe6243ab01774029c81f79ef64866fb4dd2edd13 | 69,764 |
from typing import List
def get_classical_part_of_the_noise(povm: List[np.ndarray]) -> List[np.ndarray]:
"""
Description:
From given povm get stochastic map describing classical part of the noise.
Parameters:
:param povm: POVM from effects of which diagonal parts shall be extracted.
... | ac49ff02b84ad903e4327132738372f2f1a58f0b | 69,765 |
def triplet_semihard_loss_mine(labels, embeddings, margin=1.0, background=0,log_var=None):
"""Computes the triplet loss with semi-hard negative mining.
The loss encourages the positive distances (between a pair of embeddings with
the same labels) to be smaller than the minimum negative distance among
which are... | 15f6a9dcf15e1d855ad64ccc455fbb1436739b23 | 69,766 |
def uvm_object_value_str(v):
"""
Function- uvm_object_value_str
Args:
v (object): Object to convert to string.
Returns:
str: Inst ID for `UVMObject`, otherwise uses str()
"""
if v is None:
return "<null>"
res = ""
if hasattr(v, 'get_inst_id'):
res = "{}".... | e56bd12094923bf052b10dcb47c65a93a03142a2 | 69,767 |
def mt_mi_exam_collate(batch_list):
""" Collate function for a multi-task multi-input dataset
"""
all_inputs = defaultdict(list)
all_targets = defaultdict(list)
all_info = []
for inputs, targets, info in batch_list:
all_info.append(info)
for name, inpt in inputs.items():
... | 3e8b0a670a71a5bf3be282dd36284b677088d923 | 69,768 |
import os
def file_list(dirname, ext='.java'):
"""获取目录下所有特定后缀的文件
@param dirname: str 目录的完整路径
@param ext: str 后缀名, 以点号开头
@return: list(str) 所有子文件名(不包含路径)组成的列表
"""
return list(filter(
lambda filename: os.path.splitext(filename)[1] == ext,
os.listdir(dirname))) | 55769bc06ecea6727152999d9e73b63730e09172 | 69,769 |
import numpy
import scipy
def _compute_cumulative_statistics(
samples,
samples_processed_order,
num_samples_used,
confidence_level):
"""
Computes mean and error as the number of samples progresses. The output
are the means, absolute and relative errors of the samples.
... | fbfc5b9bda54592e7c703392b027cac11dc2cfcf | 69,770 |
import itertools
def checkio(stones):
""" Minimal possible weight difference between stone piles
"""
if len(stones) == 1:
return stones[0]
return min(set(map(best_balance, list(itertools.permutations(stones))))) | 618f4d11a8d795b2b78ca50370c3f8cf112de1ce | 69,771 |
def app(environ, start_response):
"""A barebones WSGI app.
This is a starting point for your own Web framework
"""
status = "200 OK"
response_headers = [("Content-Type", "text/plain")]
start_response(status, response_headers)
return [b"Hello world from a simple WSGI application\n"] | 90f9018ccca5dca0a5437170d8a494463e5e0cc3 | 69,772 |
import tqdm
import json
def download_all_dicts_to_file(filename, search, mode='w'):
""" Download data from elastic search server
:param filename: str, name of file to save data
:param search: elasticsearch search object to query
:param mode, char, file write mode (w, a)
:return filename, str:
... | 4abea20e5cd58fa05bd498e4f7462530a2b677fe | 69,773 |
def _initialize_sites_graphic_structure(graphic_struct: dict, scale_wedges: bool = False) -> dict:
"""Once the data structure has been created, it can now be initialized with plausible values."""
init_site_graphics = graphic_struct
for agent_name in init_site_graphics.keys():
# identify number of we... | 71a6e1750dbf966db21668b01747182ea130ca45 | 69,774 |
def get_taxa(**params) -> JsonResponse:
"""Search taxa
.. rubric:: Notes
* API reference: :v1:`GET /taxa <Taxa/get_taxa>`
Example:
>>> response = get_taxa(q='vespi', rank=['genus', 'family'])
>>> pprint(response)
[52747] Family: Vespidae (Hornets, Paper Wasps, Potter Wasps, an... | f960c4c96d42bbc4cee3a2717ee7d327ca95b056 | 69,775 |
import pathlib
def findjson(basedir):
"""Return a list of absolute paths to json files recursively discovered by walking the directory tree rooted at basedir"""
return [str(path.resolve()) for path in pathlib.Path(basedir).rglob('*.json')] | 5def3388237a1e70d3801952579c7cbc51fb435b | 69,776 |
import torchvision
import torch
def load_cifar10_all(data_dir='./data', val_size=0.1, shuffle=True, seed=1):
"""Load entire CIFAR-10 dataset into tensor"""
transform = transforms.Compose([
transforms.ToTensor(),
])
trainset = torchvision.datasets.CIFAR10(
root=data_dir, train=True, d... | 66908b6fc6d39cd7f4812817cae6f64cce032f02 | 69,777 |
def check_if_in_cache(search_term):
"""
Checks if the specified search term is in the local database cache.
and returns the video id if it exists.
:param search_term: String to be searched for in the cache
:return A tuple with Boolean and video id if it exists
"""
try:
song = Song.ge... | fe79a761e6fc4ddf7cefdc53da2c3e3be468d691 | 69,778 |
import sys
def ntohs(integer):
"""ntohs(integer) -> integer
Convert a 16-bit integer from network to host byte order.
"""
if sys.byteorder == 'big':
return integer
if not isinstance(integer, (int, long)):
raise TypeError('an integer is required')
if integer < 0:
raise OverflowError("can't con... | b7a7a1675e188ff2087d27e74e53a27b21151e60 | 69,779 |
import string
def create_esax(x, b, w):
"""
This method creates eSAX symbols for a univariate time series.
:param x: numeric vector representing the univariate time series
:type: pandas.Series
:param b: breakpoints used for the eSAX representation
:type: numpy.ndarray
:param w: word size ... | 44c4d465ec340c0c35742be87517a9348ee09e6b | 69,780 |
def one_way_anova_test(df, cat_col, val_col, alpha=0.05):
"""
This will detect the difference of the groups of values and the value column.
The return value is whether it is safe to assume there are group differences.
We assume the group variance are all the "same", and that the val_col is normal.
... | 2b98d30b9df19f0352424f4a718ab80afa47c786 | 69,781 |
async def get_health(request):
"""
Args:
request:
Returns:
health of all registered services
:Example:
curl -X GET http://localhost:8081/foglamp/service
"""
response = get_service_records()
return web.json_response(response) | 185d7b37b0df2d3f1c129fb476ffa6baf5cfc13f | 69,782 |
from typing import Sequence
def batch(graphs: Sequence[gn_graph.GraphsTuple]) -> gn_graph.GraphsTuple:
"""Returns a batched graph given a list of graphs.
This method will concatenate the ``nodes``, ``edges`` and ``globals``,
``n_node`` and ``n_edge`` of a sequence of ``GraphsTuple`` along axis 0. For
``sende... | cd227a3232fede85bb766da3bdc3cc6cee8f5104 | 69,783 |
def get_process_ids(connection):
"""Return all process ids"""
sql = "SELECT id FROM systems WHERE is_biz_process=1"
result = connection.execute(text(sql))
return [r.id for r in result] | 8cc07908867a2af479d246c5f51816be9fc8c322 | 69,784 |
import os
def runcmd(cmd):
"""run command"""
pipe = os.popen('"' + '" "'.join(cmd) + '"', 'r')
std_out = pipe.read()
pipe.close()
return std_out.rstrip('\n') | 45fd11b886bcc37fa927527c67eb4eaaeee5c60d | 69,785 |
def share_emotion_photo() -> FlaskResponse:
"""
XHR procedure updating the visitor log according to his emotion.
Raises:
404: if the request is not POST.
"""
if "emotion" not in request.form:
return basic_json(False, "Emotion required!")
emotion = escape(request.form["emotion"])... | 153535ea6d337d71e798cf207543a92e04df35e6 | 69,786 |
def encode_defunct(
primitive: bytes = None,
*,
hexstr: str = None,
text: str = None) -> SignableMessage:
"""
Encoded as defined here: https://github.com/ethereum/eth-account/blob/master/eth_account/messages.py
Except with Helios in the message instead of Ethereum
"""
... | 3a2f62127b7b8cd059f3dfb647f9e9a20b4eacdc | 69,787 |
import requests
import os
import pprint
import jsonschema
import json
import hashlib
def test_serve_snapshot(ray_start_with_dashboard):
"""Test detached and nondetached Serve instances running concurrently."""
detached_serve_driver_script = f"""
import ray
from ray import serve
ray.init(
address="{ray_s... | 344209a3261658757e30fafe68aa1cb0f2987dc0 | 69,788 |
def readfile(huc12, filename):
"""Make me a df please"""
df = read_yld(filename)
if df.empty:
return None
df["huc12"] = huc12
df["fpath"] = filename.split("/")[-1].split("_")[-1].split(".")[0]
return df | 2801cd1823309b67e0cc80e08397dd3e12a7062b | 69,789 |
import subprocess
def execute_local_command(command, assert_error=True):
""" General function for most of local execution needs """
log.info('Executing local command: {}'.format(command))
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p... | 398adcafef85f4e5954e07f2500c5e984ed2bfe8 | 69,790 |
def convert_team_name_id(nickname):
"""
Given the team nickname, return the team id from teams table in db.
:param str nickname: team nickname
:return str team_id: team id
:Example:
>>> convert_team_name_id('Brewers')
1
"""
# Open database connection
db = MySQLdb.connect(hos... | 29fe512821880f8e71223c854890ed8492700095 | 69,791 |
def config_vlan_range(dut, vlan_range, config="add", skip_verify=False, cli_type = ''):
"""
Author: sneha.mathew@broadcom.com
Creates/Deletes range of VLANs given as input.
:param dut:
:param vlan_range: range of VLAN IDs in string format, separator space: "first-VLAN last_VLAN".
... | 10570716ec2b4262c2753cf644736ad22a27ef54 | 69,792 |
def second_task(s : str) -> str:
"""
This function randomly reorders all the letters in a world.
Parameters:
s: the string to shuffle
Returns:
str: shuffled string
Examples:
>>> second_task('What can we do with the drunken sailor?')
' Tahw acn ew od hwit the un... | fc0d2c51ab0ff055d88ac4231ea2b06a1653a8d7 | 69,793 |
from typing import Tuple
from typing import List
def task_id_ancestors(task_id: Tuple[int]) -> List[Tuple[int]]:
"""
Gets the full list of tasks above the given task.
"""
parents = []
parent = task_id_parent(task_id)
while parent is not None:
parents.append(parent)
parent = tas... | d25b7dce8dd878c6650f43f01040b529ac62b32e | 69,794 |
def ReadSsconfFile(filename):
"""Reads an ssconf file and verifies its size.
@type filename: string
@param filename: Path to file
@rtype: string
@return: File contents without newlines at the end
@raise RuntimeError: When the file size exceeds L{_MAX_SIZE}
"""
statcb = utils.FileStatHelper()
data =... | 9883de30e8b625f21092da8ce1076850a9e8e911 | 69,795 |
def auto_unmark(*args):
"""
auto_unmark(start, end, type)
Remove range of addresses from a queue. 'start' may be higher than
'end', the kernel will swap them in this case. 'end' doesn't belong to
the range.
@param start (C++: ea_t)
@param end (C++: ea_t)
@param type (C++: atype_t)
"""
return _i... | c7c209c3f603367c9e4e26b719bcbc9058762d91 | 69,796 |
def _example_word(lang):
"""
Returns an example word for a given language
:param lang: str Language abbreviation
:return: A word. Should be one early in the vocab for that language
"""
return {
"de": "mann",
"es": "hombre"
}.get(lang) | e9d60f31cb0c5f2b1dd397e19b60a52a43fc41d2 | 69,797 |
def lightweight_image_augment(image, strength=0.4, augment_prob=0.5,
allowed_transforms='all'):
"""
augmentations from simclr paper
:param image: [h, w, 3] -- float32 in the range of 0.0 to 1.0
:param strength: magic number from simclr. i made hue weaker
:param augment_... | b676a23dd67ae4e5eec756fed26aa7bf85fac1a6 | 69,798 |
def _canonicalize(parts):
"""
Return a copy of 'parts' with consecutive "**"s coalesced.
Raise a ValueError for unsupported uses of "**".
"""
res = []
prev_was_globstar = False
for p in parts:
if p == _GLOBSTAR:
# Skip consecutive **'s
if not prev_was_globst... | faf7f7da69ed4bc2624ba59820ff44ac4657c597 | 69,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.