content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _warn(warn_message, *args, **kwargs):
"""
Inputs: warn_message- the warning message
Used to override "warnings.formatwarning" to output only the warning
message.
"""
return f'{warn_message}\n\n' | 70,900 |
def rotate_half(x):
"""Helper that splits a tensor at last dim into half and rotate it."""
x1, x2 = jnp.split(x, 2, axis=-1)
x = jnp.concatenate([-x2, x1], axis=-1)
return x | 70,901 |
def Mag(*argv):
"""Return the magnitude of one or more vectors
This method computes the vector magnitude of the Numpy arrays in
*args*. Each array in *args* must have the same number of dimensions.
The arrays may be a mixture of staggered and unstaggered arrays. I.e.
for any axis the dimen... | 70,902 |
def stateful_linear(types, args, kwargs, pg):
"""Handles ``__torch_function__`` dispatch for ``torch.nn.functional.linear``.
This method computes a linear.
"""
input_tensor = args[0]
weight = args[1]
if version.parse(torch.__version__) > version.parse("1.11.0"):
if len(args) == 3:
... | 70,903 |
def sort_map(map):
"""
resume = {}
sort = []
for i in range(len(map)):
for j in range(len(map[i])):
resume[(i, j)] = map[i][j]
srtd = [k for k in sorted(resume.values())]
for e in srtd:
sort.append(list(list(resume.keys())[list(resume.values()).index(e)]))
sr... | 70,904 |
def encode2str(key=JWT_SECRET_KEY, algorithm="HS256", headers=None, json_encoder=None, **kwargs) -> str:
"""
生成json web token
:param key: 签名密钥
:param headers: token头信息
:param json_encoder:
:param kwargs:
:return:
"""
return encode(key=key, algorithm=algorithm, headers=headers, json_... | 70,905 |
def parallel_preprocess(
input_data, preprocess_pipeline, word_tokenize=None, num_pool=-1
):
"""
Process data in parallel using multiple CPUs.
Args:
input_data (list): List if input strings to process.
preprocess_pipeline (list): List of functions to apply on the input data.
word... | 70,906 |
def get_selection_value(source_obj, field, value):
"""Get the string of a selection field using
fields_get method to get the string
@param source_obj: Model that contains the field
@type source_obj: RecordSet
@param field: Database name of the field
@type field: str or unicode
@param value:... | 70,907 |
def batch_zipper(data_loaders):
"""Drain all loaders simultaneously"""
data_iterators = []
for a, b in data_loaders:
data_iterators.append((a, len(b), iter(b)))
num_batches = max(len(b) for a, b in data_loaders)
skip_idxs = {}
for a, b in data_loaders:
deficit = num_batches - l... | 70,908 |
def write_config_file(path, contents):
""" Write a configuration file. """
data = "{\n"
for key in sorted(contents.keys()):
data += " '%s': '%s',\n" % (key, contents[key])
data += "}\n"
write_file(path, data) | 70,909 |
async def imageToByte(image, session):
"""Attempts to auto-detect between URL link, bytes and local file path, and converts image to bytes.
Args:
image (string): Must be either bytes, URL link or local file path of image.
Raises:
ConvertImageError: Provided string is not an URL link, bytes... | 70,910 |
def extract_text_from_pdf_file_word() -> None:
"""Extract text from a pdf document (step: tet) - method word."""
cfg.glob.logger.debug(cfg.glob.LOGGER_START)
xml_variation = "word."
source_file_name, target_file_name = utils.prepare_file_names(xml_variation + cfg.glob.DOCUMENT_FILE_TYPE_XML)
tet ... | 70,911 |
def visualize6(M, name, nozero=False, k=2., useall=False, lim=1e-2, conc='c_w_l',W=46,color='crimson'):
""" visualize variation in the the profile shape"""
if useall:
val, c_w_l, idx = conditionVal2(name=name, nozero=nozero, conc=conc)
else:
val, c_w_l, idx = conditionVal(name=name, nozero=... | 70,912 |
def max_key(dict):
""" Returns the maximum key in an integer-keyed dictionary.
Args:
dict (dict): The integer-keyed dictionary.
Returns:
int: The maximum key.
"""
output = 0
for key, value in dict.items():
output = max(output, int(key))
return output | 70,913 |
def terminal_path_lengths(neurite):
"""Get the path lengths to each terminal point."""
return _map_sections(sf.section_path_length, neurite, Section.ileaf) | 70,914 |
def seperator(digits):
"""Seperate thousands into list container. e.g ['1', '000'] for 1000."""
strdigits = str(digits)
sep = []
while len(strdigits) > 3:
sep.insert(0, strdigits[-3: len(strdigits)])
strdigits = strdigits[0:-3]
# if strdigits not empty at the end of loop
if strdi... | 70,915 |
def print_mx(matrix):
""" pretty print of matrix """
for line in matrix:
print("\t".join(map(str, line))) | 70,916 |
def generate_analysis_list(analysis_ids, public_only=False):
"""Get general analysis information
Parameters
----------
analysis_ids : list of ints
The analysis ids to look for. Non-existing ids will be ignored
public_only : bool, optional
If true, return only public analyses. Defaul... | 70,917 |
def execute(request=''):
"""TODO: add documentation string.
:param request: json as a dict.
"""
status_writer = status.Writer()
status_writer.send_status(_('running pretend_task'))
for i in range(0, 25):
time.sleep(1)
status_writer.send_percent(float(i)/25, _('working on ... | 70,918 |
def normalization(epochs):
""" Normalizes each epoch e s.t mean(e) = 0 and var(e) = 1
Args:
epochs - Numpy structure of epochs
Returns:
epochs_n - mne data structure of normalized epochs (mean=0, var=1)
"""
for i in range(epochs.shape[0]): # TODO could switch to a 1... | 70,919 |
def all_gather_list(data, group=None, max_size=16384):
"""Gathers arbitrary data from all nodes into a list.
Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python
data. Note that *data* must be picklable.
Args:
data (Any): data from the local worker to be gathered on other wo... | 70,920 |
def test_readMiriadwriteMiriad_check_time_format():
"""
test time_array is converted properly from Miriad format
"""
# test read-in
fname = os.path.join(DATA_PATH, "zen.2457698.40355.xx.HH.uvcA")
uvd = UVData()
uvd.read(fname)
uvd_t = uvd.time_array.min()
uvd_l = uvd.lst_array.min()
... | 70,921 |
def build_get_method_query_valid_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get method with unencoded query parameter with value 'value1&q2=value2&q3=value3'.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
... | 70,922 |
def build_adj_neighborhoods(L, K, symmetric=True):
"""Build Adjacent Neighborhoods with periodic boundary conditions"""
V = []
M = (K-1)/2
for i in range(L):
if symmetric:
start = np.floor(i-M)
else:
start = i
Vi = [int(((start + j) % L)+1) for j in range(... | 70,923 |
def namelambda(name):
"""Rename a function. Decorator.
This can be used to give a lambda a meaningful name, which is especially
useful for debugging in cases where a lambda is returned as a closure,
and the actual call into it occurs much later (so that if the call crashes,
the stack trace will rep... | 70,924 |
def get_arguments():
"""
parses the command line arguments.
:return:
"""
parser = argparse.ArgumentParser(
description='Analyse the estimator_status and ekf2_innovation message data for the '
'.ulg files in the specified directory')
parser.add_argument("directory_path... | 70,925 |
def maximum_iou(evt_gt, evt_pr, input_events, **kwargs):
"""Implements Maximum Intersection over Union from
Startsev, M., Agtzidis, I., & Dorr, M. (2019). 1D CNN with BLSTM for automated
classification of fixations, saccades, and smooth pursuits.
Behavior research methods, 51(2), 556-572.
"""
ev... | 70,926 |
def _tpos_to_gpos(transcript, start, end=None):
"""Compute the equivalent gene position for a transcript position.
Args:
transcript: `pyensembl.Transcript` instance
start (int): position relative to the transcript
end (int): optional, second position relative to the transcript
... | 70,927 |
def parse_func(x: str) -> Tuple[str, List[str]]:
"""
Parses out the components of a function string.
:returns: First element is the name of the function, second argument are the function arguments.
"""
try:
name = x.split("(")[0]
args = x.split("(")[1].split(")")[0]
except IndexE... | 70,928 |
def test_list_non_positive_integer_enumeration_nistxml_sv_iv_list_non_positive_integer_enumeration_1_5(mode, save_output, output_format):
"""
Type list/nonPositiveInteger is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/nonPositiveInteger/Schema+Instance/NISTSchema-... | 70,929 |
def write_model(model, filename):
"""
Writes the given model to the given file.
:param NMF model
:param str filename
"""
logging.info('Writing model to {}'.format(filename))
joblib.dump(model, filename) | 70,930 |
def unconfigure_ip_mtu(device, intf, mtu):
""" Unconfiguring ip mtu on device
Args:
device ('str'): Device str
intf ('str') : interface to configure
mtu ('str'): mtu size to configure
Returns:
None
Raises:
SubCommandFailure
"... | 70,931 |
def volume_get_all(context, marker=None, limit=None, sort_keys=None,
sort_dirs=None, filters=None, offset=None):
"""Retrieves all volumes.
If no sort parameters are specified then the returned volumes are sorted
first by the 'created_at' key and then by the 'id' key in descending
ord... | 70,932 |
def test_positions_result_relax(vasprun_parser):
"""
Check that the parsed positions are of type ArrayData.
Also check that the entries are as expected, e.g. correct value and
that the first and last entry is the same (static run).
"""
quantity = vasprun_parser.get_quantity('trajectory')
... | 70,933 |
def parse(text: Text, morphind_loc="lib/morphind/MorphInd.pl"):
"""
Do morphological parsing with Morphind. for example:
menggunakan => ^meN+guna<n>+kan_VSA$
:param text:
:param morphind_loc:
:return:
"""
cleaned_text = re.sub("[^a-zA-Z0-9 ]", "", text)
cleaned_text = cleane... | 70,934 |
def gmos_longslit_gaiasyn(name, ra1, dec1, pm_ra_cosdec=0.0, pm_dec=0.0, pa=0.0, slitwidth=1, pnum='Gemini GMOS Spectroscopy', frame='fk5', unit='deg', epoch='J2000', time_obs='J2020', corner='bottom left'):
"""
Function to create gmos finding charts from synthetic gaia images, given the target coordinates, p... | 70,935 |
def get_views(string : str) -> Tuple[int, int]:
"""A helper function that takes a string reresentation of total something and
daily amount of that same thing and returns both as a tuple of ints.
Parameters
------------
string : str
The string containing the numbers both total and daily
... | 70,936 |
def pakk_bytes(key, data: List[bytes], output: io.BufferedIOBase):
"""Encrypt and pakk an input :class:`list` of :class:`bytes` into a single buffered output.
.. note::
Appends to the current position in the output stream.
Args:
key (bytes): the key to encrypt the incoming blobs with, usi... | 70,937 |
def set_input(interpreter, size, resize):
"""Copies a resized and properly zero-padded image to the input tensor.
Args:
interpreter: Interpreter object.
size: original image size as (width, height) tuple.
resize: a function that takes a (width, height) tuple, and returns an RGB
image resiz... | 70,938 |
def mkdir(dirname: str):
"""
Make a directory on the local filesystem, starting from the active directory.
"""
pathlib.Path(dirname).mkdir(exist_ok=True) | 70,939 |
def get_batches(iterable: Iterable, size: int = 100) -> Generator:
"""
Returns a generator of the iterable which yields batches of the given size
Given an iterable, uses the size parameter to create a generator which
yields batches of the iterable of the given size.
Parameter:
iterable: Th... | 70,940 |
def crawl_naver_datalab():
"""
datalab.naver.com/robots.txt
(21/11/05)
User-Agent: *
Allow: /$
Allow: /index.naver
Disallow: /
"""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36"
... | 70,941 |
def all_datasets():
"""
Return all data sets from the data set table.
:return: a list of dictionaries {name: (string), description: (string), id: (int) }
"""
#print('all_datasets: current_user:', current_user)
return db.session.query(Dataset).all() | 70,942 |
def main():
"""
entry point for the application
"""
hmm() | 70,943 |
def check_publications_associations():
""" Check the publications associations """
publications = Publication.objects.all().order_by('num')
pub_list = []
for publication in publications:
pub_id = publication.id
is_associated = 0
if Score.objects.filter(publication=publication):... | 70,944 |
def GetYoungestPlayer(cur, con):
""" Gets the age of youngest player in the database """
# Query to be executed
query = """
SELECT *
FROM (
SELECT *, TIMESTAMPDIFF(YEAR, DateOfBirth, CURDATE()) AS Age
FROM Players
) AS DervivedTable1
... | 70,945 |
def min_dist(coord, surface):
"""Return minimum distance between coord and surface."""
d = surface - coord
d2 = numpy.sum(d * d, 1)
return numpy.sqrt(min(d2)) | 70,946 |
def get_keys_by_mode(mode):
"""Filtres `KEYS` by mode."""
return (key for key in KEYS if mode in key.modes) | 70,947 |
def test_key_lookaside_all():
""" Test getting variable arguments after keyword """
parser = isccfg.IscConfigParser(options_lookaside_manual)
assert len(parser.FILES_TO_CHECK) == 1
opt = find_options(parser)
assert isinstance(opt, isccfg.ConfigSection)
values = parser.find_values(opt, "dnssec-lo... | 70,948 |
def bytes2np(bytesarray):
"""
bytes two numpy->array
:param bytesarray:
:return:
"""
nparr = np.frombuffer(bytesarray, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # cv2.IMREAD_COLOR in OpenCV 3.1
return img_np | 70,949 |
def cohort_membership(cohort_id):
"""
If full_detail flag is set to 'true', it returns a json with
a list of wikiusers grouped by username.
Otherwise, it renders the html with basic cohort information.
"""
session = db.get_session()
try:
cohort = g.cohort_service.get_for_display(
... | 70,950 |
def worker(pid: int,
module_path: str,
config_queue: Queue,
result_queue: Queue,
error_queue: Queue,
terminated: QueueEmpty,
cancel):
""" Worker to be executed in its own process
Args:
cancel: if true terminates when an error is encounte... | 70,951 |
def evaluate_on_dev(model, filename, batch_size=32):
"""Prints predictions and metrics by model on development dataset."""
lemmas, tags, inflected_forms = read_dataset(filename)
predictions = generate_predictions(model, lemmas, tags, batch_size)
for prediction in predictions:
print(prediction)... | 70,952 |
def quote_identifier(dialect: Dialect, name: str) -> str:
"""
Add quotes around an identifier (e.g. a table or column name), and escape special characters in the name.
Note that the result of this function is not always a valid column name and/or table name. e.g. The
following string can be quoted by t... | 70,953 |
def run_style_formatter() -> None: # pragma: no cover
"""Run style formatter (autopep8)."""
print("Running autopep8...")
subprocess.call(['autopep8', '-r', '-i',
kineticstoolkit.config.root_folder],
env=kineticstoolkit.config.env) | 70,954 |
def mesh_update_attributes(mesh):
"""Update the attributes of a mesh.
Parameters
----------
mesh : :class:`compas.datastructures.Mesh`
A mesh object.
Returns
-------
bool
True if the update was successful.
False otherwise.
"""
names = sorted(mesh.attributes... | 70,955 |
def ipu_jit_scope(ipu_scope):
"""Provides a scope for compilation of operations.
If you would like to compile several sets of operations together, then this
can provide that mechanism.
Args:
ipu_scope: A name to differentiate between different JIT scopes
Returns:
A context
"""
scope = "jit_sc... | 70,956 |
def load_data(database_filepath):
"""
Loading Data From Database.
Splitting X And Y Columns As TimeSeries Data By Calling get_rolling_data Method.
Parameters:
database_filepath (str): Filepath Where Database Is Located.
Returns:
X (DataFrame): Features
Y (DataFrame): Labe... | 70,957 |
def rillaget(url, dir_name, header):
"""信頼できるダウンローダー"""
filename = url.split("/")[-1]
total_path = dir_name + '/' + filename
attempts = 0
success = False
while success is not True and attempts < 8:
time.sleep(random.uniform(1.1, 3.4)) # サーバーフライヤーを回避するためにランダムな待機を追加します
try:
... | 70,958 |
def test_exception_early_stop_asap():
"""Even the first partitions have finished to process, the partition before
the failed partition should be killed as soon as possible.
"""
class ExpectedException(Exception):
pass
class Pass(nn.Module):
def forward(self, x):
return x... | 70,959 |
def recover_path(shortest_path: tuple, path_to: dict, action_to: dict, time_to: dict) -> list:
"""Recover and return the path from start to goal."""
path = [time_to[shortest_path], shortest_path, action_to[shortest_path]]
previous = path_to[shortest_path]
while previous:
path.append(previous)
... | 70,960 |
def create_instances():
"""
Creates EC2 Instance
"""
print(_green("Started..."))
print(_yellow("...Creating EC2 instance(s)..."))
ec2_region = config.get(Config.AWS, Config.AWS_EC2_REGION)
ec2_key = config.get(Config.AWS, Config.AWS_ACCESS_KEY)
ec2_secret = config.get(Config.AWS, Config... | 70,961 |
def wait_timeout(proc):
"""
This function waits for a process to finish, else raises exception after timeout
"""
start = time.time()
end = start + float(sys_experiment_timeout)
interval = min(float(sys_experiment_timeout) / 1000.0, .25)
while True:
result = proc.poll()
if res... | 70,962 |
def ensure_requirements(requires):
"""Ensure scheduling meets requirements.
Verify the state of the requirements to make sure the activity can be
scheduled.
Args:
requires (list): list of all requirements.
Throws:
ActivityInstanceNotReadyException: if one of the activity in the
... | 70,963 |
async def arun(config: rc.robot_config = None,
port: str = None):
""" Asynchronous entrypoint for the server
:param config: Optional config override
:param port: Optional smoothie port override
"""
rconf = config or rc.load()
hc = await API.build_hardware_controller(rconf, port) | 70,964 |
def centerxz(vertices):
"""Center model around X and Z.
"""
bb = bbox(vertices)
cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
cy = 0
cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
translate(vertices, [-cx,-cy,-cz]) | 70,965 |
def polaritySanitizer(polarity):
"""Sanitize input polarity values.
Renames the, case-insensitive, values 'positive', 'pos', or '+' to 'positive'
and 'negative', 'neg', or '-' to 'negative'.
Errors on unrecognized polarity value.
Arguments:
polarity (str): unsanitized polarity type
""... | 70,966 |
def downloaded_datasets():
"""Lists downloaded datasets in ~/.agml/datasets"""
return [d for d in os.listdir(
data_save_path()) if os.path.isdir(
os.path.join(data_save_path(), d))] | 70,967 |
def get_certificate_chain(host: str, port: int) -> List[str]:
"""Connect to the host on the port and obtain certificate chain"""
func_name: str = "get_certificate_chain"
cert_chain: list = []
soc = socket(AF_INET, SOCK_STREAM, proto=0)
soc.settimeout(3)
try:
soc.connect((host, port)... | 70,968 |
def evaluation_step(loss_from_logits_fn, model,
per_device_batch: dt.BatchedTrainTocopoData,
rng: jnp.ndarray):
"""An evaluation step, running on each device.
Note the use of `pmean` to combine gradients and loss across devices (and
hosts).
Args:
loss_from_logits_fn... | 70,969 |
def read_pkg_ini(path):
"""Read and check the `flit.ini` file with data about the package.
"""
cp = _read_pkg_ini(path)
return _validate_config(cp, path) | 70,970 |
def verifyCallback(connection, x509, errnum, errdepth, ok):
"""
Check SSL certificates.
@return (bool) True when the certificates are valid, else False.
"""
if not ok:
print 'invalid cert from subject:', x509.get_subject()
return False
else:
#Certs are fine
p... | 70,971 |
def get_data_granularity(
user: Optional[BlossomUser], after: Optional[datetime], before: Optional[datetime]
) -> str:
"""Determine granularity of the graph.
It should be as detailed as possible, but only require 1 API call in the best case.
"""
if not user:
return "week"
# T... | 70,972 |
def build_file_response(path, content_type=None):
"""
path (str) : Path to file relative to www-root folder next to your server script
content_type (str) : Mimetype; if set to None mimetype will automatically be determined
----
Return (bytes) HTTP response containing file data. If content_type is se... | 70,973 |
def NewSimulationRunAddDatastoreInit(builder, datastoreInit):
"""This method is deprecated. Please switch to AddDatastoreInit."""
return AddDatastoreInit(builder, datastoreInit) | 70,974 |
def build_condensed_graph(G, min_epsilon, min_cluster_size, dont_merge=[]):
"""
Finds nodes in the graph that have edges weight weights above min_epsilon,
and both children have a size larger than min_cluster_size.
"""
def filter_node(n):
return G.nodes[n]['size'] > min_cluster_size
de... | 70,975 |
def morph(doclike: types.DocLike) -> Dict[str, Dict[str, int]]:
"""
Count the number of times each value for a morphological feature appears
as a token annotation in ``doclike``.
Args:
doclike
Returns:
Mapping of morphological feature to value counts of occurrence.
See Also:
... | 70,976 |
def input_values_into_grid(grid: Grid, known_values: List[Tuple[int, int, int]]):
"""Adds the known values to the grid."""
for known_value in known_values:
grid.insert_known_value(*known_value) | 70,977 |
def validate(val_loader, model, criterion, verbose, args):
"""
验证
"""
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
# top5 = AverageMeter()
recall = AverageMeter()
aver_acc = AverageMeter()
aver_loss = AverageMeter()
aver_recall = AverageMeter()
... | 70,978 |
def _tx_executor(contract_function):
""" modifies the contract instance interface function such that whenever a transaction is performed
it automatically waits until the transaction in included in the blockchain
(unless wait=False is specified, in the case the default the api acts as usual)
"""
... | 70,979 |
def _does_nothing() -> None:
"""Does nothing.""" | 70,980 |
def add_dtv(dtv):
"""
Given values for a date time value, generate the RDF necessary to add the
datetime value to VIVO
date_time datetime value
datetime_precision text string in tag format of VIVO date time precision,
example 'vivo:yearMonthDayPrecision'
"""
... | 70,981 |
def num_svas():
""" Calculate the number of surrogate variables
"""
raise NotImplementedError | 70,982 |
def L2Norm(inputList):
"""
Return the norm of the supplied list
"""
return math.sqrt(SumSquare(inputList)) | 70,983 |
def parse_json_file_to_dict(path):
"""
Convert JSON file into a project-specific representation of the data
internally.
NOTE: it's not the most Pythonic or elegant code you will find. It was
written "just to work".
"""
with open(path, 'r') as json_file:
json_contents = json.load(jso... | 70,984 |
def hash_table_size(item, tablesize):
"""
A hashing technique that involves
1. Converting the characters in a string to a list of ordinal values
2. Get the sum of the list
3. Get the remained by doing a modulo using tablesize
item - string
tablesize
"""
ordinal_list = [ord(i)... | 70,985 |
def get_scheduler_plugin(name):
"""Return a scheduler plugin
:param str name: The name of the scheduler plugin.
:rtype: SchedulerPlugin
"""
if _SCHEDULER_PLUGINS is None:
raise SchedulerPluginError("No scheduler plugins loaded.")
if name not in _SCHEDULER_PLUGINS:
raise Schedul... | 70,986 |
def ferret_custom_axes(id):
"""
Custom axis information for stats_probplot_values Ferret PyEF
"""
size = 1
for axis in ( pyferret.X_AXIS, pyferret.Y_AXIS, pyferret.Z_AXIS,
pyferret.T_AXIS, pyferret.E_AXIS, pyferret.F_AXIS ):
axis_info = pyferret.get_axis_info(id, pyferret.... | 70,987 |
def get_service_bus_namespace(name=None,resource_group_name=None,opts=None):
"""
Use this data source to access information about an existing ServiceBus Namespace.
:param str name: Specifies the name of the ServiceBus Namespace.
:param str resource_group_name: Specifies the name of the Resource Grou... | 70,988 |
def extract_default_context(context, response, url):
""" Gets default information if not all info is retrieved
"""
context = Context() if not context else context
if not context.url or not context.permalink:
current_app.logger.debug('getting default url info: %s', url)
context.url = con... | 70,989 |
def destroy_all(ctx, yes):
"""destroy all muacrypt state.
By default this command creates account(s) state in a directory with
a default "catch-all" account which matches all email addresses
and uses default settings. If you want to have more fine-grained
control (which gpg binary to use, which ex... | 70,990 |
def test_get_with_time_must_be_implemented(base_limiter):
"""Verify BaseLimiter.reset raises NotImplementedError."""
_test_must_be_implemented(base_limiter.reset, ("key", None)) | 70,991 |
def grib_index_select_long(indexid,key,val):
"""
@brief Select the message subset with key==value. The value is an integer.
The key must have been created with integer type or have integer as native type if the type was not explicitly defined in the index creation.
\b Examples: \ref index.py "... | 70,992 |
def get_raasi(raagam_index=None):
"""
Get raasi of the specified raagam index
@param raagam_index:ID of the raaga
@return: raasi
"""
if raagam_index==None:
raagam_index=settings.RAAGA_INDEX
return _get_raaga_attribute("Raasi",raagam_index) | 70,993 |
def runner_crypto(opts, verbose=False):
"""Create Crypto-material by either using CAs or save Cryptogen material.
Args:
opts (dict): Nephos options dict.
verbose (bool): Verbosity. False by default.
"""
# TODO: Limited by the fact that we manually specify MSPs
# Set up Admin MSPs
... | 70,994 |
def test_get_domain_range_switch(c):
"""
test get domain range switch
"""
response = c.get_domain_range_switch('test-sdk.sys-qa.com')
print(response) | 70,995 |
def make_work_dir(args):
"""Make directory to store outputs, logs, and intermediate data.
If not provided, create a timestamped directory in current working
directory.
"""
work_dir = args.work_dir
if not work_dir:
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
wo... | 70,996 |
def check_array_1d(a: np.ndarray) -> None:
"""Checks if array is one dimensional."""
assert len(a.shape) == 1, "Array a with shape {} is not 1D.".format(a.shape)
assert a.ndim == 1, "Array a with shape {} is not 1D.".format(a.shape) | 70,997 |
def _player_id(player):
"""Lookup and return the NHL API player ID for an idividual player"""
players = _all_player_ids()
player_id = players.get(player)
if not player:
raise JockBotNHLException(f"Player Not Found {player}")
return player_id | 70,998 |
def test_open028_open028_v3_xml(mode, save_output, output_format):
"""
A valid extension Derived type has suffix open content, base type does
not
"""
assert_bindings(
schema="saxonData/Open/open028.xsd",
instance="saxonData/Open/open027.v3.xml",
class_name="Doc",
vers... | 70,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.