content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _make_unique(l):
"""Check that all values in list are unique and return a pruned and sorted list."""
return sorted(set(l)) | 64,800 |
def parse_preproc_line(line, preproc_defs):
"""Parse a preprocessor line into a tree that can be evaluated"""
# Scan line and translate to python syntax
inchar = None # Character context
line_len = len(line)
pline = ""
index = 0
while index < line_len:
if (line[index] == '"') or (lin... | 64,801 |
def group_by_area(units):
"""Create a dictionary containing lists of UnitGroup objects by area."""
areas = [ID_area(i.ID) for i in units]
groups = {i: [] for i in sorted(set(areas))}
for a, u in zip(areas, units): groups[a].append(u)
return groups | 64,802 |
def render_to_mail(template, context, **kwargs):
"""
Renders a mail and returns the resulting ``EmailMultiAlternatives``
instance
* ``template``: The base name of the text and HTML (optional) version of
the mail.
* ``context``: The context used to render the mail. This context instance
... | 64,803 |
def filledprf(x0, y0, sigma, n=0.2, res=100):
"""
Fill the pRF centered in x0, y0 and radius sigma
Arguments
---------
x0 : int
column for center
y0 : int
row for center
sigma : float
standard deviation of the pRF
n : float
power exponent
res : int
... | 64,804 |
def post_info(request, post, put_content=False):
"""Return a hash with post fields (content is omitted for performance)."""
data = {
'title': post.title,
'subject': post.subject,
'publication_date': post.pub_date,
'author': post.author.username,
'path': post.path,
... | 64,805 |
def get_CommodityDef():
""" get commodity definition settings """
file_country = "../Input/2_commodity/01_MainCommodity.csv"
dt_data = genfromtxt(file_country, dtype = str, skip_header=1, delimiter=',')
lsCommodity = list()
for row in dt_data:
lsCommodity.append(cls_misc.Commodity(... | 64,806 |
def dispatch_per_device(games):
"""Helper fo split dataset per device."""
num_games = list(games._asdict().values())[0].shape[0]
num_devices = jax.local_device_count()
batch_size = batch_size_per_device(num_games, num_devices=num_devices)
def dispatch(x):
if hasattr(x, 'shape'):
return jnp.reshap... | 64,807 |
def setup_bridge(node, br="br0", if0="eth0", if1="eth1"):
"""
Creates a bridge interface and connects the two specified
network interfaces to it.
"""
print "Setting up bridge on node: %s" % node.name
# shutdown both interfaces
node.cmdPrint("ifconfig %s-%s 0.0.0.0 down" % (node.name, if0))
... | 64,808 |
def network_od_paths_assembly(points_dataframe,node_dict,graph,vehicle_wt,transport_mode,industry_columns,gdf_edges,save_edges = True,output_path ='',excel_writer =''):
"""
Assign net revenue to roads assets in Vietnam
Inputs are:
start_points - GeoDataFrame of start points for shortest path analysis.
end_points ... | 64,809 |
def secim_filter(
in_dir,
out_dir,
last_minutes=None,
neg_out_dir=None,
model_path=MODEL_PATH,
label_path=LABEL_PATH,
threshold=THRESHOLD,
min_num_objects=MIN_NUM_OBJECTS,
crop_fractions=[0, 0, 1, 1],
excluded_labels=['airplane', 'fire hydr... | 64,810 |
def test_collate_orf_tpms_and_counts_tsv(expected_fixture, output_dir):
"""
Test ``collate_tpms.R`` TSV files for equality. See
:py:func:`riboviz.utils.equal_tsv`.
:param expected_fixture: Expected data directory
:type expected_fixture: str or unicode
:param output_dir: Output directory, from c... | 64,811 |
def xml_prettify(elem):
"""Return a pretty-printed XML string for the XML element."""
text = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(text)
return reparsed.toprettyxml(indent=" ") | 64,812 |
def fix_matrix_gauge(emat):
"""Fix gauge of an energy matrix such that the minimum value
of each column is zero (columns correspond to positions), and
overall matrix norm is equal to 1."""
# fix mean
for j in range(emat.shape[1]):
emat[:,j] = emat[:,j] - sp.mean(emat[:,j])
# fix sum of v... | 64,813 |
def clean_html(X):
""" Strip html
:texts: collection - the collection of texts to change
:returns: list of texts cleaned from html
"""
return [re.sub('(\\<.*?\\>)','',text) for text in X if text!=None] | 64,814 |
def parse_datetime(value):
"""Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raises ``ValueError`` if the input isn't well formatted.
"""
match = DATETIME_RE.match(v... | 64,815 |
def mock_client_close():
"""Mock close method of clients at module scope."""
with patch(f"{INFLUXDB_CLIENT_PATH}.close") as close_v1, patch(
f"{INFLUXDB_CLIENT_PATH}V2.close"
) as close_v2:
yield (close_v1, close_v2) | 64,816 |
def segment_interpolation_points(beg, end, dx, n=0, equal=True, inc_end=True):
"""
Generator that returns segment interpolation points.
Can be either used by specifying an increment dx, or number of interpolated points.
If no interpolation can be done due to the dx or n given, the beg and end points wil... | 64,817 |
def test_output_type_neighborhood_map():
"""Check output type of neighborhood map."""
figure = neighborhood_map(*NBHD_DATA)
assert isinstance(figure, dict) | 64,818 |
def post(host, path, body=None, headers={}):
"""
HTTPS POST request
"""
return request('POST', host, path, body, headers) | 64,819 |
def issiso(sys, strict=False):
"""
Check to see if a system is single input, single output
Parameters
----------
sys : LTI system
System to be checked
strict: bool (default = False)
If strict is True, do not treat scalars as SISO
"""
if isinstance(sys, (int, float, compl... | 64,820 |
def get_optimizer(encoder, model, args, learning_rate, remove_pooler=False):
"""
get BertAdam for encoder / classifier or BertModel
:param model:
:param classifier:
:param args:
:param remove_pooler:
:return:
"""
param_optimizer = list(encoder.named_parameters())
para... | 64,821 |
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
:return: None
"""
if STRIPE_PLANS is None:
return None
for _, value in STRIPE_PLANS.iteritems():
plan = PaymentPlan.retrieve(value.get('id'))
if plan:
PaymentPlan.update(id=value.get('id'),
... | 64,822 |
def b32decode(todecode, casefold=False, map01=None):
"""Decode a Base32 encoded byte string.
todecode is the byte string to decode. Optional casefold is a flag
specifying whether a lowercase alphabet is acceptable as input.
For security purposes, the default is False.
RFC 3548 allows for optional... | 64,823 |
def _install_node_module_for(config, library_dir, library_name, dest_root_dir=None, include_tests=False):
"""
Installs the node module into the node module cache directory, which
includes downloading all dependencies. The dev dependencies are
loaded into the cache, but are not included in the inter... | 64,824 |
def check_visitors(cls):
"""Check that a checker's visitors are correctly named.
A checker has methods named visit_NODETYPE, but it's easy to mis-name
a visit method, and it will never be called. This decorator checks
the class to see that all of its visitors are named after an existing
node class... | 64,825 |
def flesch_reading_ease(n_syllables, n_words, n_sents, lang=None):
"""
Readability score usually in the range [0, 100], related (inversely) to
:func:`flesch_kincaid_grade_level()`. Higher value => easier text.
Note:
Constant weights in this formula are language-dependent;
if ``lang`` is ... | 64,826 |
def shufflenetv2_x1_5(pretrained=False, **kwargs):
"""shufflenetv2_x1_5 model
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
Examples:
.. code-block:: python
from paddle.vision.models import shufflenetv2_x1_5
# build ... | 64,827 |
def test_atomic_language_min_length_2_nistxml_sv_iv_atomic_language_min_length_3_3(mode, save_output, output_format):
"""
Type atomic/language is restricted by facet minLength with value 9.
"""
assert_bindings(
schema="nistData/atomic/language/Schema+Instance/NISTSchema-SV-IV-atomic-language-min... | 64,828 |
def gen_snv_transition_matrix(ts_tv_p=0.71,
ts_hm_ht_p=0.5,
tv_l_p=0.5,
tv_hm_ht_p=0.8):
""" Function to compute SNV matrix of transition probabilities,
default rates follow SInC reference (Fig1.a) """
G_ref = ... | 64,829 |
def make_event(action_type, device, file, timestamp, opt=None):
"""Create an audit event."""
if action_type == ACT_WRITE:
# Simulate writing data to the file. Create a new randomized file and
# copy _some_ of it's attributes.
mutation = make_file(opt=opt)
file.size = mutation.siz... | 64,830 |
def parse_config_file(config_file) -> dict:
"""Read config.yaml file with params.
Returns
-------
dict
Dict of config
"""
with open(config_file, 'r') as stream:
try:
CONFIG = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
... | 64,831 |
def pivot_on_matching_substrings(graph: "Graph", pivot_categories: dict, config: "Config"):
"""Create pivots between domains that share a common substring of
`config.longest_common_substring` chars long.
Note: SequenceMatcher has some known issues with not finding the longest match in very long
str... | 64,832 |
def Property(func): # pylint: disable = C0103
"""
Property with improved docs handling
:Parameters:
`func` : ``callable``
The function providing the property parameters. It takes no arguments
as returns a dict containing the keyword arguments to be defined for
``property``. Th... | 64,833 |
def add_files(struct: Structure, opts: ScaffoldOpts) -> ActionParams:
"""Add .pre-commit-config.yaml file to structure
Since the default template uses isort, this function also provides an
initial version of .isort.cfg that can be extended by the user
(it contains some useful skips, e.g. tox and venv)
... | 64,834 |
def get_subjectdirs() -> list:
"""
Returns subject directory names (not full path) based on the path_bidsdata (bids_data directory).
@rtype: list
@return: list of subdirectories in path_bidsdata that start with the prefix sub
"""
bidsdir_contents = os.listdir(cfg.path_bidsdata)
has_sub_pre... | 64,835 |
def get_entities_sentence(dataset_file, sentence):
"""
:param dataset_file:
:param sentence:
:return: sentence : [[entity1, id, char1, char2], [entity2, id, char3, char4],
relation], [[entity1, id, char1, char2], [entity2, id, char3, char4],
relation], et... | 64,836 |
def ground(expr, env):
"""Replace all variables with their values in expr."""
if scheme_symbolp(expr):
resolved = lookup(expr, env)
if expr != resolved:
return ground(resolved, env)
else:
return expr
elif scheme_pairp(expr):
return Pair(ground(expr.fir... | 64,837 |
def parse_maintainers_line(line):
"""Parse one line of Maintainers.txt, returning any match group and its key."""
for key, expression in EXPRESSIONS.items():
match = expression.match(line)
if match:
return key, match.group(key)
return None, None | 64,838 |
def open(name, mode="copyonwrite", memmap=0):
"""Factory function to open a FITS file and return an HDUList object.
name: Name of the FITS file to be opened.
mode: Open mode, 'readonly' (default), 'update', or 'append'.
memmap: Is memmory mapping to be used? default=0.
"""
# instantia... | 64,839 |
def query_other_gene_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short name
default: CVAP
... | 64,840 |
def cbc_cloud_api():
"""Create CBCloudAPI singleton."""
return CBCloudAPI(url="https://example.com",
org_key="test",
token="abcd/1234",
ssl_verify=False) | 64,841 |
def get_extension_manager():
"""Return the extension manager used by Review Board.
The same instance will be returned every time.
Returns:
ExtensionManager:
The extension manager used by Review Board.
"""
global _extension_manager
if not _extension_manager:
_extension_... | 64,842 |
def learning_curves(estimator, X, y, ylim=None, cv=10, title='', n_jobs=1,
train_sizes=np.linspace(.1, 1.0, 10), leg_loc='best',
scoring='accuracy', baseline=0, baseline_loc=1.0,
random_seed=None):
"""
Generate a simple plot of the tes... | 64,843 |
def get_title(dbname, page_id, replicas_port, user, password):
"""
Get title of the page with id as `page_id`.
:param dbname: Which database the module corresponds to.
:param page_id: The Id of the page whose page title is to be fetched.
:param replicas_port: port for connecting to meta table throu... | 64,844 |
def fuse_cfg():
"""Return a test telliot configuration for use on polygon-mumbai
If environment variables are defined, they will override the values in config files
"""
cfg = TelliotConfig()
# Override configuration for fuse testnet
cfg.main.chain_id = 122
accounts = find_accounts(chain_i... | 64,845 |
def resolve_url_param(param: UrlParam, context: Optional[Context] = None) -> ResolvedUrlParam:
"""
Resolve a URL parameter.
Args:
param: A URL parameter, which is one of the items below.
- A URL parameter value.
- A list of URL parameter values.
- A Value of a li... | 64,846 |
def fifo(jobs,num_frames):
""" Frame list
Each item in this list will be a tuple as follows:
Tuple[0] - represents the number of the page frame sequentially, 1,2,3, etc..
Tuple[1] - reresents the job current in this frame
Tuple[2] - represents the moment that job arrived (starting with 0 for fi... | 64,847 |
def _netcdf_gsm_plev(gsm_dir, fcst_time, tsel):
"""netCDFファイルを読み込む(GSM、pres)
Parameters:
----------
msm_dir: str
GSMデータを置いたディレクトリ、またはretrieve、force_retrieve
retrieve:データ取得を行う。既に存在している場合は取得しない。
force_retrieve:データ取得を行う。既に存在している場合にも再取得する。
ディレクトリ名:新たにデータ取得は行わず、指定ディレクトリにあるNet... | 64,848 |
def delete_index(index, force=False):
"""删除索引
:param index: 索引
:param force: 是否强制删除索引,如果索引存在true强制删除,false不删除
"""
if force and es.indices.exists(index):
es.indices.delete(index=index) | 64,849 |
def CMYKratio_to_CIE(cmykr):
"""Converts CMYK color space (ratio representation) to CIE"""
rgb = CMYKratio_to_RGB(cmykr)
return RGB_to_CIE(rgb) | 64,850 |
def laptops_list(request):
"""View a list of LNL's laptops"""
laptops = Laptop.objects.filter(retired=False)
return render(request, 'laptops/laptops_list.html', {"laptops": laptops}) | 64,851 |
def main():
"""Simple runner for marshmallow dataclass extraction."""
extract_pytorch_structures()
extract_marshmallow_structures() | 64,852 |
def get_bcl(signal_markers: pd.DataFrame):
"""Function to return estimates of the cycle length for a recording
For a given train of signal markers (either QRS start, AT, or other), will estimate the cycle length as the
difference between successive markers, with an estimate made that the last cycle length ... | 64,853 |
def test_fetch_users_case_sens():
"""fetch_users should be able to fetch Users with a case-insensitive filter"""
emails = ["abc@example.com", "def@example.com", "ghi@example.com"]
users = UserFactory.create_batch(len(emails), email=factory.Iterator(emails))
upper_emails = list(map(str.upper, emails))
... | 64,854 |
def test_validator_requirement_absolutized(tmp_path, monkeypatch, config):
"""'requirement' param: check it's made absolute."""
# change dir to the temp one, where we will have the reqs file
testfile = tmp_path / "reqs.txt"
testfile.touch()
monkeypatch.chdir(tmp_path)
validator = Validator(conf... | 64,855 |
def exponential_head_correction(r, V, cutoff):
"""Use an exponential function to smoothly force V to a finite value at V(0)
Parameters
----------
r : np.ndarray
Separation values
V : np.ndarray
Potential at each of the separation values
cutoff : int
The last real value o... | 64,856 |
def fa_to_en(string):
"""Convert Persian digits to EN
Usage::
>>> from persiantools import digits
>>> converted = digits.fa_to_en("۰۱۲۳۴۵۶۷۸۹")
:param string: A string, will be converted
:rtype: str
"""
digits_map = {
"۰": "0",
"۱": "1",
... | 64,857 |
def send_security_token(user, method, totp_secret, phone_number, send_magic_link=False):
""" Generate and send the security code.
:param user: The user to send the code to
:param method: The method in which the code will be sent
:param totp_secret: the unique shared secret of the user
:param phone_n... | 64,858 |
def _check_array_contains_all_integers(array: Iterable[int],
array_max_value: int,
array_name: str = 'Array') -> None:
"""Check that an array has all numbers between 0 and ``array_max``."""
if set(array) != set(range(array_max_value))... | 64,859 |
def plugin_get(request, plugin_id, fields):
"""Get plugin info."""
plugin = iotronicclient(request).plugin.get(plugin_id, fields)
return plugin | 64,860 |
def write_datefile(message, datetime_file="./date/ever_changing_date_file.txt"):
"""
Writes the message to a files
"""
# Update the file
with open(datetime_file, "w") as date_file:
date_file.write(message+"\n") | 64,861 |
def _bytes_list_feature(values):
"""
:param values:
:return:
"""
def _norm2bytes(value):
return value.encode() if isinstance(value, str) and six.PY3 else value
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[_norm2bytes(values)])) | 64,862 |
def quicklook_region(request, region_id=10000002, type_id=34):
"""
Generates system level overview for a specific type.
Defaults to tritanium & the forge.
"""
# Get the item type
type_object = InvType.objects.get(id=type_id)
# Get list of materials to build
materials = InvTypeMaterial.... | 64,863 |
def delete_event_subscription( context, id ):
"""
Deletes an event subscription
Args:
context: The Redfish client object with an open session
id: The identifier for the subscription
Returns:
The response of the DELETE
"""
# Get the current subscriptions
subscriptio... | 64,864 |
def close(fd):
"""Close file descriptor fd.
:type fd: int
:rtype: None
"""
pass | 64,865 |
def setup_hm_port():
"""Create a per unit Neutron and OVS port for Octavia Health Manager.
This is used to plug the unit into the overlay network for direct
communication with the octavia managed load balancer instances running
within the deployed cloud.
"""
neutron_ovs = reactive.endpoint_from... | 64,866 |
def preprocess_data(data_frame, label_columns_list, data_file_name):
"""
start preprocessing the data
"""
print '\npreprocessing..'
print Style.RESET_ALL
for col in label_columns_list:
data_frame[col] = data_frame[col].apply(lambda arr: arr.strip(""))
data_frame[col] = data_frame... | 64,867 |
def get_prayer(id):
"""Returns specific prayer from id."""
return Prayer.query.get(id) | 64,868 |
def PRandM(r_dprime, r_prime, b, k, m, kappa):
"""
r_dprime = random secret integer in range [0, 2^(k + kappa - m) - 1]
r_prime = random secret integer in range [0, 2^m - 1]
b = array containing bits of r_prime
"""
t = [[program.curr_block.new_reg('s') for j in range(2)] for i in range(m)]
t... | 64,869 |
def docstring_parameters_section(obj):
"""
Return the parameters section of a docstring
"""
return docstring_section_lines(obj.__doc__, 'parameters') | 64,870 |
def p_object_list_exp_1(p):
"""
object_list_exp : empty
"""
p[0] = [] | 64,871 |
def split_string_by_bytes(s: str, bytes_count: int) -> list[bytes]:
"""A function that splits a string into N-byte particles"""
s = s.encode()
return [s[i : i + bytes_count] for i in range(0, len(s), bytes_count)] | 64,872 |
def score_urls(*args, \
search_terms=config.search_terms, **kwargs):
"""
Returns urls ordered by search relevance
"""
def search_key(tokens, default=0):
score, _, _ = search_terms.replace_terms(tokens)
return -(score or default)
tags = collections.Counter()
score_by_tags ... | 64,873 |
def createconda(ctx):
""" Create a conda environment """
env = 'notebooks_env'
currentenv = os.getenv("CONDA_DEFAULT_ENV")
res = ctx.run("conda info -e", hide='out')
has_env = "notebooks_env" in res.stdout
if not has_env:
print('Creating conda environment')
with ctx.cd(repo_dir... | 64,874 |
def recipe(recipe_file, ctype=container_type.DOCKER, single_stage=False,
userarg=None):
"""Recipe builder"""
# Make user arguments available
USERARG = {} # pylint: disable=unused-variable
if userarg:
USERARG = userarg # alias
# Consider just 2 stages for the time being
stage... | 64,875 |
def set_cluster(cluster: Cluster) -> None:
"""
Set the current cluster context.
"""
__cluster.set(cluster) | 64,876 |
def get_collective_group_size(group_name: str = "default") -> int:
"""Return the size of the collective group with the given name.
Args:
group_name: the name of the group to query
Returns:
The world size of the collective group, -1 if the group does
not exist or the process doe... | 64,877 |
def collision(object1, object2):
"""detect collision between two objects using circles
Tests for collision between two objects by testing whether two circles
centered on the objects overlap. Objects must have a
a "radius" attribute, which is used to create the circle.
Args:
object1: First ... | 64,878 |
def _multiprocessing_save_sp(in_out_path):
"""
A function that saves spacy embeddings and is suitable for use
with the multiprocessing library because it is globally namespaced
and accepts just one argument as input.
"""
vp, np = in_out_path
if not os.path.exists(np + '.npz'):
save_c... | 64,879 |
def rm_standard_dev(var,window,ravelmodeltime,numOfEns):
"""
Smoothed standard deviation
"""
import pandas as pd
import numpy as np
print('\n\n-----------STARTED: Rolling std!\n\n')
if var.ndim == 3:
rollingstd = np.empty((var.shape))
for i in range(var.shape[1... | 64,880 |
def compute_purity(cluster_assignments, class_assignments):
"""Computes the purity between cluster and class assignments.
Compare to https://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html
Args:
cluster_assignments (list): List of cluster assignments for every point.
... | 64,881 |
def test_get_https_proxy_windows():
"""
Test to make sure that we correctly get the current proxy info on
Windows
"""
result = {
"vdata": "http=192.168.0.1:3128;https=192.168.0.2:3128;ftp=192.168.0.3:3128"
}
mock = MagicMock(return_value=result)
expected = {"server": "192.168.0.2... | 64,882 |
def add(a,b):
"""
Return the addition of the arguments
>>> add(1,2)
3
>>> add('a','b')
'ab'
>>> add(1, '2')
Traceback (most recent call last):
File "test.py", line 43, in <module>
add(1, '2')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
retu... | 64,883 |
def get_vlan_binding(netid):
"""Lists the vlan given a network_id."""
LOG.debug(_("get_vlan_binding() called"))
session = db.get_session()
try:
binding = (session.query(l2network_models.VlanBinding).
filter_by(network_id=netid).one())
return binding
except exc.NoRe... | 64,884 |
def direct_print(string):
"""
Generic output function via STDOUT
:param string: String to output
:return: None
"""
sys.stdout.write(f"{string}")
sys.stdout.flush() | 64,885 |
def ida_star(root, goal, heuristic):
""" Based on https://en.wikipedia.org/wiki/Iterative_deepening_A* """
bound = heuristic(root, goal)
path = StackSet([root])
while True:
t = search(path, 0, bound, goal, heuristic)
if t == 'FOUND':
return (path, bound)
... | 64,886 |
def extract_call(function, arguments, ignore_self=False):
"""Validates the a dict of arguments can be used to call the given function"""
require_type(dict, arguments, "arguments")
args, kwargs, varargs, varkwargs = get_args_spec_from_function(function, ignore_self=ignore_self)
if varargs:
signa... | 64,887 |
def getLiterature(movieID, indexF, dataF):
"""Return literature information for a movie."""
return _parseColonList(movieID, indexF, dataF, 'MOVI: ', _lit) | 64,888 |
def find_key_symptom(tariffs, cause_reduction, cause, endorsements,
rules=None):
"""Find the key endorsed symptom for a cause
Args:
tariffs (dict): processed tariff matrix
cause_reduction (dict): mapping from cause46 to cause34
cause (int): cause number at the cause... | 64,889 |
def main():
"""
Main function
"""
# Parse Command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--config', '-c',
dest='config_file',
default="watchdog.yaml",
help='Configuration file (required)')
... | 64,890 |
def init_availabe_commands() :
""" Use global cmd arr to populate global_available_cd """
global global_available_cd
global global_cmd_arr
length = len(global_cmd_arr)
if length == 0:
global_available_cd = {
'unis' : { 'help' : "Show unis servers" },
'blipp': { 'help... | 64,891 |
def all_gather(x, replication_factor, name):
""" Gather the data on all replicas to all other replicas. Each replica will
have the exact same output.
Args:
x: The tensor to gather
replication_factor: The replication factor of the model.
name: Optional op name.
Returns:
A tensor o... | 64,892 |
def test_redaction(client, unrestricted_case, elasticsearch):
"""Should allow various forms of citation, should redirect to normalized_cite"""
citation = unrestricted_case.citations.first()
url = api_reverse("cases-detail", args=[citation.normalized_cite]) + "?full_case=true"
response = client.get(url,... | 64,893 |
def generate_legend_file(split_names, legend_file_name, out_dir,
hdfs_client=None):
"""
generate legend file for each all the splits
"""
legend_file = '{0}/{1}'.format(out_dir, legend_file_name)
if hdfs_client is None:
with open(legend_file, 'a+') as f:
... | 64,894 |
def get_ip4_from_socket() -> str:
"""Get the public IPv4 of this system by inspecting a socket connection.
Warning: This returns a local IP address when running behind a NAT, e.g. on Docker.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((IP4_SOCKET_ENDPOINT, 80))
... | 64,895 |
def _get_parse(str_src, ns_args):
"""Return {'tree':, 'rulerrow':, 'alignments':} parse
from text and ArgParse options
"""
if ns_args.sourceformat != None:
e_fmt = ns_args.sourceformat
if e_fmt == FMT_CSV:
try:
o_dialect = csv.Sniffer().sniff(str_src)
... | 64,896 |
def _write_trigger_file_from_extraction(trigger_file: TextIO,
extraction: List[Tuple[str, str, str]]):
"""Writes triggers that have been extracted from a raw_data file to a
file."""
for trigger, targetness, timestamp in extraction:
trigger_file.write(f"{trigge... | 64,897 |
def transform(tokens):
"""
Accumulate tokens in lines.
Add token (and white spaces) to a line until it overflow 80 chars.
"""
lines = []
current_line = []
for t in tokens:
if sum([len(x) + 1 for x in current_line]) + len(t) > 80:
lines.append(current_line)
cu... | 64,898 |
def test_render_unknown_error() -> None:
"""It does not render an unknown error type."""
notebook_output = nbformat.from_dict({})
output = error.render_error(notebook_output)
with pytest.raises(StopIteration):
next(output) | 64,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.