content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_selected_arg(view, com_reg, pos):
"""
Retrieves the selected argument in a comma separated list,
returns None if there are several entries and no entry is selected
directly
"""
args = com_reg.group("args")
if "," not in args:
# only one arg => return it
return args
... | 5,289,700 |
def example_consumer(url, do_method):
"""
Consumer is typically a runnable main that is deployed to execute a tasks.
This method demonstrates how the integration with the message publisher might be tested
:param url: the sqs url
:param do_method: hook to provide a method that allows message content ... | 5,289,701 |
def test_map_effects():
"""Test ANOVA effects parsing."""
selection, names = _map_effects(n_factors=2, effects='A')
assert names == ['A']
selection, names = _map_effects(n_factors=2, effects=['A', 'A:B'])
assert names == ['A', 'A:B']
selection, names = _map_effects(n_factors=3, effects='A*B')
... | 5,289,702 |
def template_hook(name, silent=True, is_markup=True, **kwargs):
"""Calls the given template hook.
:param name: The name of the hook.
:param silent: If set to ``False``, it will raise an exception if a hook
doesn't exist. Defauls to ``True``.
:param is_markup: Determines if the hook s... | 5,289,703 |
def populate(filename, baseurl=None):
"""Populate the database with sample data"""
from quokka.utils.populate import Populate
Populate(db, filepath=filename, baseurl=baseurl, app=app)() | 5,289,704 |
def sync_case_body_cache_for_vol(self, volume_id, rerender=True):
"""
call sync_case_body_cache on cases in given volume
"""
with record_task_status_for_volume(self, volume_id):
volume = VolumeMetadata.objects.get(pk=volume_id)
to_update = []
to_create = []
all_analys... | 5,289,705 |
def create_google_sheet_export(username, id_string, export_id, **options):
"""
Google Sheets export task.
"""
# we re-query the db instead of passing model objects according to
# http://docs.celeryproject.org/en/latest/userguide/tasks.html#state
try:
export = _get_export_object(export_id... | 5,289,706 |
def showPlot3():
"""
Produces a plot comparing the two robot strategies.
"""
num_robots = range(1, 11)
step_standard = []
step_random = []
for n in num_robots:
step_standard.append(runSimulation(n, 1.0, 20, 20, 0.8, 10, StandardRobot))
step_random.append(runSimulation(n, 1.0,... | 5,289,707 |
def eigenvalue_nonunitary_diamondnorm(a, b, mx_basis):
"""
Eigenvalue nonunitary diamond distance between a and b
Parameters
----------
a : numpy.ndarray
The first process (transfer) matrix.
b : numpy.ndarray
The second process (transfer) matrix.
mx_basis : Basis or {'pp',... | 5,289,708 |
def init_layer(layer):
"""Initialize a Linear or Convolutional layer.
Ref: He, Kaiming, et al. "Delving deep into rectifiers: Surpassing
human-level performance on imagenet classification." Proceedings of the
IEEE international conference on computer vision. 2015.
"""
if layer.weight.ndi... | 5,289,709 |
def test_hist_flush(hist, xession):
"""Verify explicit flushing of the history works."""
hf = hist.flush()
assert hf is None
xession.env["HISTCONTROL"] = set()
hist.append({"inp": "still alive?", "rtn": 0, "out": "yes"})
hf = hist.flush()
assert hf is not None
while hf.is_alive():
... | 5,289,710 |
def compute_airfoil_aerodynamics(beta,c,r,R,B,Wa,Wt,a,nu,a_loc,a_geo,cl_sur,cd_sur,ctrl_pts,Nr,Na,tc,use_2d_analysis):
"""
Cl, Cdval = compute_airfoil_aerodynamics( beta,c,r,R,B,
Wa,Wt,a,nu,
a_loc,a_geo,cl_sur,cd_sur,
... | 5,289,711 |
def rescale_image(image, scale=0.5):
"""
Resize the frame is good to have an improvement
of the capability to read the image
"""
image_height = image.shape[0]
image_width = image.shape[1]
dimensions = int(image_width*scale), int(image_height*scale)
return cv2.resize(image, dimen... | 5,289,712 |
def make_fwd_slice(shape, slices, reverse=None, cull_second=True):
"""Make sure slices go forward
This function returns two slices equivalent to `slices` such
that the first slice always goes forward. This is necessary because
h5py can't deal with reverse slices such as [::-1].
The optional `rever... | 5,289,713 |
def _str2float(s: str) -> Union[float, str]:
"""
Convert string to a numeric type, if possible.
"""
try:
# if numpy is installed, use np.float64 instead of Python built-in
if USE_NUMPY:
return np.float64(s)
else:
return float(s)
except ValueError:
... | 5,289,714 |
def test_StrictURLField_values_error_length():
"""
ValidationError:
Enter a valid email address
Ensure this value has at most 200 characters (it has 256)
"""
newval = 'http://{field}.tt'.format(field='t' * 50)
assert URLFieldModel(field=newval).field == newval
with pytest.raises(Validati... | 5,289,715 |
def print_no_data(clusters):
"""Prints a message indicating that no data was found in the given clusters"""
print(no_data_message(clusters)) | 5,289,716 |
def get_prev_weekday(x: Optional[Date] = None) -> Date:
"""
Returns the previous week day as of given (optional) date.
:param x: Optional date in time.
:return: Previous business day.
>>> get_prev_weekday(Date(2020, 1, 1))
datetime.date(2019, 12, 31)
>>> get_prev_weekday(Date(2020, 1, 2))
... | 5,289,717 |
def get_student_teams(
platform_url: str, org_name: str = const.TARGET_ORG_NAME
) -> List[plug.StudentTeam]:
"""Like :py:func:`get_platform_teams`, but converts each team to a
:py:class:`~repobee_plug.StudentTeam`. for easier comparison.
Args:
platform_url: URL to the directory used by the
... | 5,289,718 |
def update_history(player, move):
"""Updates histories and cooperation / defections counts following play."""
# Update histories
player.history.append(move)
# Update player counts of cooperation and defection
if move == C:
player.cooperations += 1
elif move == D:
player.defection... | 5,289,719 |
def openProcFile(proc_filename, read_proc0, bounds):
"""Open single proc*.hdf file and return its handler
Parameters
proc_filename - name of the input proc*hdf file
read_proc0 == list_read_proc[0], the bottom processor layer index. See below.
bounds - oordinates of the edg... | 5,289,720 |
def _SetEnvForNativeSdk(env, sdk_path):
"""Initialize environment according to target architecture."""
bin_path = os.path.join(sdk_path, 'bin')
# NOTE: attempts to eliminate this PATH setting and use
# absolute path have been futile
env.PrependENVPath('PATH', bin_path)
tool_prefix = None
tool_map ... | 5,289,721 |
def get_mern2_props(
m1: float,
m2: float,
m3: float,
n: int) -> Tuple[float, float, float]:
"""
Helper function to estimate Erlang distributions rates and
probabilities from the given moments and Erlang shape (n).
See theorem 3 in [1] for details about A, B, C, p1, x, y... | 5,289,722 |
def clear_tensorboard_files(directory, warning):
"""Cleans tensorboard files in a directory."""
if not tf.gfile.IsDirectory(directory):
return
for fil in tf.gfile.Glob(os.path.join(directory, "events.*")):
if warning:
v = input("Are you sure to remove existing event {} (y/n)".format(fil))
if ... | 5,289,723 |
def get_recursive_files(folder_path):
"""
Returns:
[], sub-files
"""
result = []
for root, dirs, files in os.walk(folder_path):
for f in files:
file_path = os.path.join(root, f)
result.append(file_path)
return result | 5,289,724 |
def get_record(oid):
"""
Handle get and push requests coming to metadata server
POST is an update of an existing record.
Access control is done here. An admin can modify anyone's records
but they must be an admin in the authenication database.
returns:
Response with newly created or e... | 5,289,725 |
def delete_sessions(request):
"""
delete_sessions:
This view deletes the session based on the request_id in Session_info
if it runs without exception then it deletes and return the result : success
if not then it just returns the result : error
@param:
request - trivial
@variables:
sel... | 5,289,726 |
def set_metadata(df, date, device):
"""Set the device and date attribute for the dataframe"""
df["date"] = date
df["device"] = device | 5,289,727 |
def max_quantile_CI(X, q, m, alpha=0.05):
"""Calculate CI on `q` quantile of distribution on max of `m` iid samples using a data set `X`.
This uses nonparametric estimation from order statistics and will have alpha level of at most `alpha` due to the
discrete nature of order statistics.
Parameters
... | 5,289,728 |
def remove_skipped_commands(command_sets: Dict[str, Set[str]]):
"""Remove skipped commands from command_sets."""
skipped_commands = {
"testDeprecation",
"testVersions1And2",
"testRemoval",
"testDeprecationInVersion2",
# Idl specifies the command_name as hello.
"is... | 5,289,729 |
def df_to_graph(struct_df, label):
"""
struct_df: Dataframe
"""
lig_df = struct_df[struct_df.chain == 'L']
lig_graph = gr.prot_df_to_graph(lig_df)
prot_df = struct_df[struct_df.chain != 'L']
prot_graph = gr.prot_df_to_graph(prot_df)
node_feats, edge_index, edge_feats, pos = gr.combine_gr... | 5,289,730 |
async def instance_waiter(callback):
"""
Механим отслеживания новых инстансов
:param callback: Будет вызван как только инстанс будет создан
:return:
"""
log.debug("Begin new instance waiter")
entities = {
"entities": [
{
"entity": "instance",
... | 5,289,731 |
def ctoa(character: str) -> int:
"""Find the ASCII value of character.
Uses the ord builtin function.
"""
code = ord(character)
return code | 5,289,732 |
def starter() -> NoReturn:
"""Initiates crucial functions which needs to be called during start up.
Methods:
- volume_controller: To default the master volume 50%.
- voice_default: To change the voice to default value.
- clear_logs: To purge log files older than 48 hours.
"""
li... | 5,289,733 |
def load_data(data_path,
sep=",",
header=None,
index_col=None) -> object:
"""Helper function to load train and test files
as well as optional param loading
Args:
data_path (str or list of str): path to csv file
sep (str):
index_col (str):
... | 5,289,734 |
def relief(df, measures=ABE.measures.default):
"""
reference: sect 2.2 of hall et al. "Benchmarking Attribute Selection Techniques for Discrete Class Data Mining"
reference2: Kononenko et al. "Estimating Attributes: Analysis and Extensions of Relief"
requires: discretization. distance measure provided
... | 5,289,735 |
def resolve_translation(instance, _info, language_code):
"""Get translation object from instance based on language code."""
return instance.translations.filter(language_code=language_code).first() | 5,289,736 |
def get_conf_dict():
"""
获取标准、标签、业务、项目字典表
:return:
"""
# standard_version_id对应的字典
standard_dict = {}
standard_content_dict = {}
# online标准列表
standard_list = DataManageApi.standard_search({"is_online": 1})
# 标签字典
tag_dict = DataManageApi.tag_dict()
# 业务字典
all_biz_dict ... | 5,289,737 |
def normalize_crunchtime(row):
"""Normalizes a single row of Crunchtime Baseball data
Args:
row: `dict`-ified row from Crunchtime Baseball spreadsheet
Returns:
Formatted model (`Model`)
"""
log = logging.getLogger(__name__)
model = Row()
model.src = 'ct'
model.name_fu... | 5,289,738 |
def screen_oligos(fasta_file, kmer_sizes, hairpin_tm_max = 35, homo_tm_max = 35,
tm_max = 65, tm_min = 50, min_occurrence = 5, no_3_T = True,
no_poly_3_GC = True, max_degen = 60, no_poly_run = True,
step = 3, primer_conc = 200, max_gap_prop = .1,
... | 5,289,739 |
def save_checkpoint(*args, **kwargs):
"""Only save a checkpoint if this is jax process 0. Otherwise pass."""
if jax.process_index() != 0:
return
checkpoints.save_checkpoint(*args, **kwargs) | 5,289,740 |
def vector3(draw, x=float64(), y=float64(), z=float64()):
"""
Generate value for ROS geometry message type "vector3".
Parameters
----------
x : hypothesis.strategies.floats()
Strategy to generate x value. (Default: Default hypothesis strategy.)
y : hypothesis.strategies.floats()
... | 5,289,741 |
def build_worker(cfg: DictConfig) -> WorkerPool:
"""
Builds the worker.
:param cfg: DictConfig. Configuration that is used to run the experiment.
:return: Instance of WorkerPool.
"""
logger.info('Building WorkerPool...')
worker: WorkerPool = (
instantiate(cfg.worker, output_dir=cfg.o... | 5,289,742 |
def rds_get_sensor_type(rd):
"""
For reference designator, determine sensor type to process.
"""
sensor_type = None
try:
for type in valid_sensor_types:
if '-' not in type:
check_type = '-' + type
else:
check_type = type
if ... | 5,289,743 |
def log_error(row, error_message):
"""
Log a row to the failure CSV log file.
Args:
row - A dictionary with original row info
error_message - Error message describing why the row was not imported
"""
global fail_count
try:
update_fail_logger.info("{},{},{},{... | 5,289,744 |
def group_by_ctime(events, mode):
"""
Group events by creation time.
:param events: events to group
:type: list
:param mode: grouping mode (daily or monthly)
:type: str
"""
counter = Counter()
total = 0
for event in events:
if mode == 'daily':
day = event.cti... | 5,289,745 |
def create_repo_list_object(localized_resource_obj,
repo_list_p=None):
"""
Create a repo list object.
:param localized_resource_obj:
The localization object responsible for managing localized strings.
:param repo_list_p:
If provided, this path will be... | 5,289,746 |
def dccsi_test_script(test_str):
"""Simple test command for WingIDE
to run in wing: Edit > Command by Name
^ opens a commanline at bottom of IDE
type: test-script (then return)
^ commandline now takes entering a Test Str
Test Str: Booyah
^ a Pop-up dialog will display in wing
... | 5,289,747 |
def _reshape_into_tiled_square(data: np.array, n: int):
"""Manipulate the shape of the numpy arrays so it corresponds to one large square 3-channel image."""
data = data.reshape((n, n) + data.shape[1:])
data = data.transpose((0, 2, 1, 3, 4))
return data.reshape((n * data.shape[1], n * data.shape[3]) ... | 5,289,748 |
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
async_add_entities, discovery_info=None):
"""Set up MQTT climate device through configuration.yaml."""
await _async_setup_entity(hass, config, async_add_entities) | 5,289,749 |
def auto_regressive(start_date: Union[str, datetime.date],
end_date: Union[str, datetime.date],
frequency: str,
start_values: list,
cst: float,
order: int,
coeffs: list,
sigma: flo... | 5,289,750 |
def load_estimators():
"""
Reads the ML fractional cover estimators
"""
with open('svmPipelines', 'rb') as input:
return dill.load(input) | 5,289,751 |
def handle_sns_event(sns_data):
"""
Purpose: Handler for SNS event
Parameters: SNS data from Lambda handler
Returns:
Raises:
"""
utl.put_line_in_log('SNS Handler', 'thin')
logger.debug("SNS Message: " + json.dumps(sns_data, separators=(',', ':')))
# SNS class initialization
s... | 5,289,752 |
def getsource(obj):
"""Get the source code of an object."""
if inspect.isclass(obj):
# From Python 3.9 inspect library
obj = inspect.unwrap(obj)
file = inspect.getsourcefile(obj)
if file:
# Invalidate cache if needed.
linecache.checkcache(file)
els... | 5,289,753 |
def read_stations(state):
"""Read the station table"""
rows = []
for line in open('ghcnd-stations.txt'):
if not line.startswith('USC') or line[38:40] != state:
continue
rows.append([line[:11], line[13:20], line[21:30], line[31:37],
line[38:40], line[41:76].st... | 5,289,754 |
def test_kolibri_listen_port_env(monkeypatch):
"""
Starts and stops the server, mocking the actual server.start()
Checks that the correct fallback port is used from the environment.
"""
from kolibri.utils import server
def start_mock(port, *args, **kwargs):
assert port == test_port
... | 5,289,755 |
def _shared_ptr(name, nbytes):
""" Generate a shared pointer. """
return [
("std::shared_ptr<unsigned char> {name}("
"new unsigned char[{nbytes}], "
"[](unsigned char *d) {{ delete[] d; }});"
.format(name=name, nbytes=nbytes))
] | 5,289,756 |
def do_static_absolute(parser, token):
"""
'{% load url_toolkit %}'
"{% static_absolute 'test/fb.png' %}"
"""
return StaticFilesAbsoluteNode.handle_token(parser, token) | 5,289,757 |
def combine_dicts(dicts, keys):
"""
Turns list of dicts into dict of np arrays
"""
return {
key: np.array([d[key] for d in dicts])
for key in keys
} | 5,289,758 |
def build_row_idx_filter_expr(row_idx, row_col):
"""Build calcite expression to filter rows by rowid.
Parameters
----------
row_idx
The row numeric indices to select
row_col
InputRefExpr referencing proper rowid column to filter by
Returns
-------
CalciteBaseExpr
... | 5,289,759 |
def html_escape(s):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
"""
s = s.replace("&", "&")
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace(" ", "&n... | 5,289,760 |
def k_smallest_elems(mags, k, noise):
"""Partial sort of tensor `mags` returning a list of the k smallest elements in order.
:param mags: tensor of magnitudes to partially sort
:param k: partition point
:param noise: probability
:return:
"""
mags *= e_greedy_normal_noise(mags, noise)
k_... | 5,289,761 |
def render_docstring(def_elem, name, names):
"""
Render single docstring definition source.
"""
unregistered_tags = set()
# Handle brief and/or detailed description elements
value = "\n".join(filter(None, [
ElementRenderer.render(
def_elem.find("briefdescription"),
... | 5,289,762 |
def upload_to_es(nmap_result: dict, es_instance: Elasticsearch) -> bool:
"""
Uploads the nmap result to elasticsearch.
Input:
- nmap_result: a dictionary result of the nmap scan.
- es_instance: an Elasticsearch object used to index the nmap result.
"""
_doc = nmap_result
if not n... | 5,289,763 |
def decode_base64_str(
string: str,
urlsafe: bool = True,
encoding: str = DEFAULT_ENCODING,
errors: str = DEFAULT_ERRORS,
) -> str:
"""Decode Base64, correctly padding the string.
This is similar to :func:`~gd.crypto.decode_base64`,
except it operates on strings with their encoding.
Pa... | 5,289,764 |
def generate_resources():
"""Responsible for generating the resources pages"""
# Create content pages directory if does not already exist
util.buildhelpers.create_content_pages_dir()
# Verify if resources directory exists
if not os.path.isdir(site_config.resources_markdown_path):
os.mkdir(... | 5,289,765 |
def _df_to_ner_items(
df: pd.DataFrame,
content_column: str = "Content",
annotations_column: str = "Annotations",
) -> List[LabeledTextItem]:
"""Converts pandas dataframe into a list of LabeledTextItem.
Parameters
----------
df: pd.DataFrame
The Pandas dataframe to convert.
cont... | 5,289,766 |
def add_quads(grid, nids, eids_quads, nid_offset):
"""adds quad elements to the vtkUnstructuredGrid"""
nelements = 0
if eids_quads is not None:
nelements = eids_quads.shape[0]
eids = eids_quads[:, 0]
elem_nids = eids_quads[:, 1:]
#inids = np.searchsorted(nids, elem_nids)
... | 5,289,767 |
def approx_vertex_cover(g : Graph):
"""
顶点覆盖问题的近似算法
"""
C = []
edges = deepcopy(g.edges)
while len(edges) != 0:
u, v = g.getvertexfromedge(edges[0])
C += [u.key, v.key]
i = 0
while i < len(edges):
edge = edges[i]
if edge.vertex1.key == u.ke... | 5,289,768 |
def _IsZonalGroup(ref):
"""Checks if reference to instance group is zonal."""
return ref.Collection() == 'compute.instanceGroupManagers' | 5,289,769 |
def assign_learning_rate(session, lr_update, lr_placeholder, new_lr):
"""Run assign operation where the we load the current_rate of percent
real into a Tensorflow variable.
Args:
session: Current tf.Session.
lr_update: tf.assign operation.
lr_placeholder: tf.placeholder for the new learning rate.
... | 5,289,770 |
def plant(f, *, tag, **harvest_kwargs):
"""Injects tagged values into a function.
Transforms a function to one where tagged values can injected. In
implementation, returns a function that takes plants as an additional
initial argument.
Args:
f: a function to be transformed
tag: `str`, the harvest ta... | 5,289,771 |
def lex_ident(node_syn, pred_syn, gold_syn):
"""
1. check if the predicted synset's lexname equals to the gold synset's name
2. check if the predicted synset's lexname is in the set of its wordnet hypernyms' lexnames (including hypernyms/instance_hypernyms)
"""
pred_lex = pred_syn.lexname()
gold... | 5,289,772 |
def main():
"""
Main program. Gets command-line arguments and calls function
download_the_data to initiate a data-downloading process.
Calling sequence:
-----------------
./download_data.py log MIRROR-NAME
./download_data.py log -skip-download # Print unique log & exit
"""
... | 5,289,773 |
def get_word_count(blob, n=1):
"""
This method will build a word count DataFrame given a text blob.
Args:
blob (textblob.TextBlob): blob of all words from tweets
n (int): number of ngrams
Returns:
word count pandas.DataFrame
"""
# Get the count o... | 5,289,774 |
def edges(cv_frame):
"""
Applies a Canny (edge-detection) filter
:param cv_frame: An OpenCV frame with RGB pattern
"""
# r, g, b = cv2.split(img) then cv2.merge([b,g,r])
gray = cv2.cvtColor(cv_frame, cv2.COLOR_RGB2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
return edges | 5,289,775 |
def remove_project_users(post_data=None, slug=None):
"""remove-project-users (Site admins/Site managers/Project managers only)
Usage: remove-project-users [-h] <slug> <users> ...
Arguments:
<slug> The slug of the project
<username> The username of the user to remove
Examples:
climesync remove-p... | 5,289,776 |
def avg_np_arr(data, area_cells=None, block_size=1, func=np.ma.mean):
"""
COARSENS: Takes data, and averages all positive (only numerical) numbers in blocks
E.g. with a block_size of 2, convert (720 x 1440) array into (360 x 720)
Args:
data: numpy array (2D)
area_cells:
block_siz... | 5,289,777 |
def autoswitch(*args, **kwargs):
"""A decorator that exposes a function as a switch, "inferring" the name of the switch
from the function's name (converting to lower-case, and replacing underscores with hyphens).
The arguments are the same as for :func:`switch <plumbum.cli.switch>`."""
def deco(func):
... | 5,289,778 |
def normal_dist(x,mean,sigma):
"""
Function that computes a simple normal distribution (not the same as
the gaussian() function for emission line fitting).
"""
return 1.0/np.sqrt(2*np.pi*sigma**2)*np.exp(-(x-mean)**2/(2.0*sigma**2)) | 5,289,779 |
def get_plugin_manager(namespace):
"""Fetch pluggy's plugin manager for our library."""
pm = pluggy.PluginManager(namespace)
log.info("Loading Hook Specifications..")
pm.add_hookspecs(specs)
log.info("Loading Hook Implemenations from entry points..")
pm.load_setuptools_entrypoints(namespace)
... | 5,289,780 |
def _load(module):
"""Load a module from its name."""
return import_module("{}.{}".format(__name__, module)) | 5,289,781 |
def test_event_pattern(EventPattern=None, Event=None):
"""
Tests whether the specified event pattern matches the provided event.
Most services in AWS treat : or / as the same character in Amazon Resource Names (ARNs). However, CloudWatch Events uses an exact match in event patterns and rules. Be sure to use... | 5,289,782 |
def get_ops_from_graph(graph):
"""Get ops from graph and convert Node."""
ops = graph.get_operations()
merged_ops = OrderedDict()
for op in ops:
support_ops_name = None
scope_name = None
for _support_ops_name in Node.__support_ops__:
if re.findall(_support_ops_name, o... | 5,289,783 |
def train(cfg, train_dataset, features, model, tokenizer, continue_from_global_step=0):
""" Train the model """
if cfg.local_rank in [-1, 0]:
_dir_splits = cfg.output_dir.split('/')
_log_dir = '/'.join([_dir_splits[0], 'runs'] + _dir_splits[1:])
tb_writer = SummaryWriter(log_dir=_log_dir... | 5,289,784 |
def path_to_settings(ini_file):
"""
Find directory of ini-file relative to this directory (currently two directories up).
:param ini_file: name of ini-file, e.g. development.ini
:type: str
:return: path to directory containing ini-file
:rtype: str
"""
dir_name = os.path.abspath(os.path.... | 5,289,785 |
def _create_models(
model: _input_model_type, obs: Sequence[str], lineages: Sequence[Optional[str]]
) -> _return_model_type:
"""
Create models for each gene and lineage.
Parameters
----------
obs
Sequence of observations, such as genes.
lineages
Sequence of genes.
Retur... | 5,289,786 |
def _setup_put(chid, value, chtype=None, count=None):
"""
Setup the C value for ca put. This is used by both :func:`put` and :func:`sg_put`.
Return (chtype, count, c_value) tuple.
"""
if chtype is None:
chtype = field_type(chid)
native_count = element_count(chid)
if count is None or... | 5,289,787 |
def perm_get_ssh_challenge_token(issuer, kwargs):
"""
Checks if an account can request a challenge token.
:param issuer: Account identifier which issues the command.
:returns: True if account is allowed to call the API call, otherwise False
"""
return True | 5,289,788 |
def distrust(mac: str, *args, **kwargs) -> None:
"""Distrust a bluetooth device.
:param mac: MAC address of bluetooth device.
"""
with UsedEngine(*args, **kwargs) as engine:
return engine.distrust(mac) | 5,289,789 |
def masked_word_model_loss():
"""Computes the masked word language modeling loss"""
loss_fct = CrossEntropyLoss()
loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
return loss | 5,289,790 |
def log_to_file(file_out, protocol="json"):
"""Log the tuning records into file.
The rows of the log are stored in the format of autotvm.record.encode.
for lhs == rhs, we add an extra rhs = [] record
Parameters
----------
file_out : str
The file to log to.
protocol: str, optional
... | 5,289,791 |
def periodify(f, T=2*np.pi, tinit=0.0):
""" Forces a piecewise periodic function
"""
def f_p(t):
return f(tinit + np.mod(t, T))
return f_p | 5,289,792 |
def circumference2(d):
"""Calculates the circumference of a cirle using the formula:
\u03C0 * diameter
Parameters
----------
d: int or float
The diameter in the equation.
Returns
-------
Float
\u03C0 * d
Raises
------
ValueError
If d::
... | 5,289,793 |
def namedict(name, requires=(), fields=None):
"""
Return a subclass of dict with named fields
:param fields: option fields
:param requires: requires fields
"""
return type(name, (NamedDict,), {
"__Fields__": fields or {},
"__Requires__": requires,
}) | 5,289,794 |
def dir_empty_ne(path: str) -> Result[bool, Error]:
"""Check if directory is empty, do not raise exceptions.
Args:
path (str): path to a directory.
Returns:
Result[bool, Error]:
Ok (True): directory is empty.
Ok (False): directory is not empty.
Err (kind... | 5,289,795 |
def sumy_clean_lines(lines):
"""
Compared to regular clean lines, this one preserves heading and paragraph information.
"""
new_lines = []
for line in lines:
if line.startswith("="):
new_lines.append(line.strip("=").upper())
else:
new_lines.append(line)
... | 5,289,796 |
def write_traceback(stream, err, test):
"""Converts a sys.exc_info()-style tuple of values into a string.
Copied from Python 2.7's unittest.TestResult._exc_info_to_string.
"""
def _is_relevant_tb_level(tb):
return '__unittest' in tb.tb_frame.f_globals
def _count_relevant_tb_levels(tb):
... | 5,289,797 |
def fill_table(qt_table, tuple_list):
"""Fills the rows and columns of a qt_table given a list of tuples that are
passed in. Each element in the tuple list corresponds to a row in
the final table. Any data previously in the table will be cleared.
qt_table - a QTable
tuple_list - a... | 5,289,798 |
def split_SAM(samFile, n):
""" Given a sam file, separate the header line from the remaining entries,
record which chromosomes are present in the reads, and split the reads
into n chunks.
"""
header = []
chroms = set()
transcript_lines = []
with open(samFile, 'r') as f:
... | 5,289,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.