content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def view_video(file_path):
"""View the video file
# Arguments
file_path [str]: the path to file
# Returns
[HTML Video]: the video prompt pointing to correct file
"""
relative_url = transfer_file_to_public_dir(file_path)
# convert to mp4 transferable file
path, ext = os.pat... | 5,300,100 |
def ensure_path( path, inc_file=False ):
"""
extension: ensures that the input path exists, creating directories as needed
input: string (path/to/file), Boolean (see notes)
output: None
notes: if inc_file is True the last element of path is assumed to be a file
this file is created if it do... | 5,300,101 |
def matrix_active_subspaces(generators,rep_out,rep_in):
""" Like get_active_subspaces, this function returns function that maps to the
subspace of linear maps from the input representation to the output representation.
Inputs: [generators seq(tensor(d,d))] [rep_out seq(tuple(q,p)] [rep_in... | 5,300,102 |
def compute_normalized_license(declared_license):
"""
Return a normalized license expression string detected from a list of
declared license items.
"""
if not declared_license:
return
detected_licenses = []
for declared in declared_license:
if isinstance(declared, str):
... | 5,300,103 |
def generate_key(dict_data, daily=True):
"""generate key from a dictionary"""
cache_dict = copy.copy(dict_data)
json_data = json.dumps(cache_dict)
return hashlib.md5(json_data.encode('utf-8')).hexdigest() | 5,300,104 |
def caller_add_contexts(h_ea, mnem, ops, i_curf, er_ctx, dst_eas):
"""
At a function call, adds a caller context and callee context for the
callsite. Multiple caller contexts are created but only one callee context
is created
:param h_ea: effective address of the call instruction
:param mnem: mn... | 5,300,105 |
def count_attrib_correct(pred, label, idx):
"""
:param pred:
:param label:
:param idx:
:return:
"""
assert pred.size(0) == label.size(0)
correct_num = 0
for one, two in zip(pred, label):
if one[idx] == two[idx]:
correct_num += 1
return correct_num | 5,300,106 |
def login():
"""Endpoint to manage user login"""
con = sqlite3.connect('example.db')
cur = con.cursor()
# Insert a row of data
uname = request.json["username"]
passwd = request.json["password"]
ns = request.json["ns"]
try:
if ns == net_sec :
temp = 0
for ... | 5,300,107 |
def extract_feature(sig1 : Dict[str, dict],
sig2 : Dict[str, dict],
attribute : str) -> float :
"""
Returns 1 if attribute is equal in sig1 and sig2 otherwise 0.
If attribute is missing, returns np.nan
"""
if (sig1.get(attribute, None) is not None) and (sig2.... | 5,300,108 |
def _eval_expr(expr):
"""
https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string
>>> _eval_expr('2^6')
4
>>> _eval_expr('2**6')
64
>>> _eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0
"""
operators = {
ast.Add: operator.add,
ast.S... | 5,300,109 |
def avg_fuel_per_hour(iterable):
"""
>>> round(avg_fuel_per_hour(clean_data(row_merge(log_rows))), 3)
0.48
"""
return mean(row.fuel_per_hour for row in iterable) | 5,300,110 |
def transpose(matrix):
"""Transpose a list of lists.
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']])
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f']])
[['a', 'd'], ['b', 'e'], ['c', 'f']]
>>> transpose([['a', 'b'], ['d', '... | 5,300,111 |
def get_handlers_callable() -> Dict[str, Type[PotentialHandler]]:
"""Map Foyer-style handlers from string identifiers."""
return {
"vdW": FoyerVDWHandler,
"Electrostatics": FoyerElectrostaticsHandler,
"Bonds": FoyerHarmonicBondHandler,
"Angles": FoyerHarmonicAngleHandler,
... | 5,300,112 |
def test_data_parallel_dense():
"""test_data_parallel_dense"""
context.set_context(mode=context.GRAPH_MODE)
context.reset_auto_parallel_context()
context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, mirror_mean=True, device_num=8)
inp = Tensor(np.ones([32, 128]).astype(np.floa... | 5,300,113 |
def the_config_parameter_is_unset(run_context, parameter_name: str):
"""the {parameter_name} config parameter is set to {parameter_value}"""
if parameter_name in run_context.parameters:
del run_context.parameters[parameter_name] | 5,300,114 |
def MotroMove():
"""
获取 slidebar 的值,向舵机发送 mqtt 指令
"""
global motorValue, mqclient
value = motorValue.get()
cmd = "DRVZ+" + str(value)
mqclient.pubMotorZ(cmd) | 5,300,115 |
def get_json_line(data):
"""Get json string from data."""
return json.dumps(data,
ensure_ascii=False,
sort_keys=True,
cls=_MetaEncoder) | 5,300,116 |
def fetch_group(gid):
"""Return the group with the specified gid, or 404 if there isn't one."""
groups = find_groups(gid=gid)
if groups:
return groups[0]._asdict()
return ("Not found", 404) | 5,300,117 |
def get_latent_variable(batchsize, latent_dimension, device):
"""Creates a random vector of size (batchsize, latent_dimension)
from normal distribution.
"""
latent_var = randn(
(batchsize, latent_dimension), requires_grad=True
).to(device)
return latent_var / torch.linalg.norm(la... | 5,300,118 |
def reduce(tensor: torch.Tensor, reduction: str) -> torch.Tensor:
"""Reduces the given tensor using a specific criterion.
Args:
tensor (torch.Tensor): input tensor
reduction (str): string with fixed values [elementwise_mean, none, sum]
Raises:
ValueError: when the reduction is not ... | 5,300,119 |
def get_rdr_color_label(obsid):
"""Download the COLOR PRODUCT_ID label for `obsid`.
Parameters
----------
obsid : str
HiRISE obsid in the standard form of ESP_012345_1234
Returns
-------
None
Storing the label file in the `labels_root` folder.
"""
get_rdr_some_label... | 5,300,120 |
def safe_read_tensor_value(variable):
"""Reads variable value or raises an exception."""
value = variable.tensor_value
if value is None:
raise ValueError("".join((
"Attempted to read a TensorVariable in a context where it has no ",
"value. This commonly happens for one of two reasons:",
... | 5,300,121 |
def wrap_insecure_channel(insecure_channel_func, tracer=None):
"""Wrap the grpc.insecure_channel."""
def call(*args, **kwargs):
channel = insecure_channel_func(*args, **kwargs)
try:
target = kwargs.get('target')
tracer_interceptor = OpenCensusClientInterceptor(tracer, ta... | 5,300,122 |
def obliquity (T : float) -> float :
"""
Returns the obliquity angle of the ecliptic [rads]
"""
return pipe(obliq_pol(T)/3600.0,deg2rad) | 5,300,123 |
def learning_rate_scheduler(epoch):
"""Outputs the learning rate as a function of the current epoch (2^-n)"""
return args.learning_rate * (2 ** -epoch) | 5,300,124 |
def file_grey(db_path, image_path, suffix="_cv_grey", file_ext="png"):
"""
Generate the greyscale of an image file. Uses opencv cvtColor
for the conversion.
arguments:
db_path : string
POSIX path for the Cinema database
image_path : string
relative POSIX path t... | 5,300,125 |
def construct_outgoing_unicast_answers(
answers: _AnswerWithAdditionalsType, ucast_source: bool, questions: List[DNSQuestion], id_: int
) -> DNSOutgoing:
"""Add answers and additionals to a DNSOutgoing."""
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, multicast=False, id_=id_)
# Adding the ques... | 5,300,126 |
def test_ui_dashboard_index_exists(sqlalchemy_engine):
"""
Even though it looks redundant, this index is necessary because of how Hasura generates SQL for the "flows" table on the UI dashboard. Without it that
table takes forever to load.
This could be fixed either by optimizing that query, or better S... | 5,300,127 |
def parabola(list1, list2, list3, plo=False, pri=False, **kwargs):
"""Plots a parabola on pre-existing graph between points
list1, list2, and list3,
returns the parameters of the parabola
as in the form y = ax^2 + bx + c,
and optionally prints the equation of the parabola
in the form y = ax^2 + ... | 5,300,128 |
def attention_mask(nd, ns, *, dtype):
"""1's in the lower triangle, counting from the lower right corner.
Same as tf.matrix_band_part(tf.ones([nd, ns]), -1, ns-nd), but doesn't produce garbage on TPUs.
"""
i = np.arange(nd)[:, None]
j = np.arange(ns)
m = i >= j - ns + nd
return np.array(m, ... | 5,300,129 |
def package_extension(path, key):
""" Uses Chrome to compile the build directory into an extension package """
path = os.path.abspath(path)
key = os.path.abspath(key)
subprocess.check_output([find_build_executable(), '--pack-extension={0}'.format(path), '--pack-extension-key={0}'.format(key)]) | 5,300,130 |
def builtin_if(self, context, looping=False):
"""
Given 'cond', 'then', and 'else': if 'cond' is true, apply 'then';
otherwise apply 'else'.
"""
do_else = context.pop()
do_then = context.pop()
if context.pop():
do_then.apply(context)
else:
do_else.apply(context) | 5,300,131 |
def blank(n=1):
"""Prints a blank line to the terminal. Taken from Matt Burbidge (mmb90)."""
for i in range(n):
print("") | 5,300,132 |
def preview_progress(Task_Options, net, device, preview_loader):
"""Returns preprocessed and augmented input and target data.
For details on all input parameter dictionaries, see:
/spectrai/spectrai/configs/*.yml
Arguments:
Task_Options: dictionary of task options
net: PyTorch neural ... | 5,300,133 |
def is_cellv2_init_ready():
"""Determine if we're ready to initialize the cell v2 databases
Cells v2 init requires transport_url and database connections to be set
in nova.conf.
"""
amqp = ch_context.AMQPContext()
shared_db = nova_cc_context.NovaCellV2SharedDBContext()
if (ch_utils.CompareO... | 5,300,134 |
def get_calendar(obj: Any, dim: str = "time") -> str:
"""Return the calendar of an object.
Parameters
----------
obj : Any
An object defining some date.
If `obj` is an array/dataset with a datetime coordinate, use `dim` to specify its name.
Values must have either a datetime64 dtype o... | 5,300,135 |
def twilio_settings_doctype_in_integrations() -> bool:
"""Check Twilio Settings doctype exists in integrations module or not.
"""
return frappe.db.exists("DocType", {'name': 'Twilio Settings', 'module': 'Integrations'}) | 5,300,136 |
async def item_unoshield(ctx):
"""
Okay so we're playing uno now apparently,
this acually seems pretty useful though.
The reverse shield can reverse a single rob or nuke.
After that it just disappears. like, \*poof\*, and its gone.
*\* oh yeah, and it doubles the amount robbed. so thats nice..... | 5,300,137 |
def test_target_index_value():
"""
test the values of target_index
"""
with pytest.raises(ValueError):
sp.splitter(TOY_X, target_index=4, split_size=0.2, seed=1) | 5,300,138 |
def merge_two(n1,n2):
"""
Given two sorted linked list with head nodes
n1 and n2, merges n2 into n1 so that the resulting
list is still sorted.
"""
if n1 is None:
return n2
if n2 is None:
return n1
n_prev1 = None; n_prev2 = None
while True:
while (n1 i... | 5,300,139 |
def run_timeit(func_1, func_2, num=1):
"""Run timeit.timeit for the given function names (input args)"""
t1 = timeit.timeit("{0}".format(func_1),
setup="from __main__ import {0}".format(func_1), number=num)
t2 = timeit.timeit("{0}".format(func_2),
setup="from __main__ import {0}".for... | 5,300,140 |
def find_golden_token():
"""
Function indentical to the 'find_silver_token', excepts for the fact that the sought token now are golden.
Also in this case the tokens are searched only in the semi-plane in front of the robot (-90 < token.rot_y < 90).
"""
dist=100
for token in R.see():
... | 5,300,141 |
def filter_data_of_insts(data, to_remove=set()):
"""
Remove midi.Pattern or MidiObj from an iterable data container if they contain
instrument numbers in 'to_remove'. These numbers are same as midi standard -1.
"""
ret = []
for x in data:
keep = True
for evnt in utils.evnt_gen(x)... | 5,300,142 |
def build_text_row(node):
"""Build a row for the french data"""
french_word = bhsa2french.get(str(node), {})
row_data = {'bhsa_node': node}
ref = french_word.get('ref')
row_data.update({
'french': french_word.get('french', ''),
'french_verse': frenchverses.get(ref, ''),
})
... | 5,300,143 |
def to_json_schema(
schema: Dict[str, Any], *, nullable_name: str, copy: bool = True, is_response_schema: bool = False
) -> Dict[str, Any]:
"""Convert Open API parameters to JSON Schema.
NOTE. This function is applied to all keywords (including nested) during a schema resolving, thus it is not recursive.
... | 5,300,144 |
def harm_longterm(
out_dep: pd.DataFrame,
out_ctl: pd.DataFrame,
selected: np.array,
outcomes: Dict,
) -> Tuple[float, int]:
"""Calculate the harm from a long-term credit outcome."""
# Impact rates
sel_acq_nsuc = np.logical_and(out_dep.success == 0, out_dep.acquired == 1)
ctl_acq_nsuc = ... | 5,300,145 |
async def upload_nextcloud_zipfile(file_name: str):
""" Upload a .zip File to later be imported into Mealie """
file = BACKUP_DIR.joinpath(file_name)
if file.is_file:
return FileResponse(
file, media_type="application/octet-stream", filename=file_name
)
else:
return ... | 5,300,146 |
def rotators_encrypt(_rotators, _text):
"""
The rotators work by being given both an initial value as well as a
frequency of how often it shifts up.
The last rotator always increments one for every character encoded/decoded
and other rotators can be configured for different frequencies.
If Rotat... | 5,300,147 |
def start_redis_server():
"""Start the redis server with the daemonize argument to prevent
the redis-server from exiting on its own.
"""
if is_windows_os():
raise Exception(
'The redis command line interface is not installed because your '
'machine is on the Windows opera... | 5,300,148 |
def ms_ssim(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5,
k1=0.01, k2=0.03, weights=None):
"""Return the MS-SSIM score between `img1` and `img2`.
This function implements Multi-Scale Structural Similarity (MS-SSIM) Image
Quality Assessment according to Zhou Wang's paper, "Multi-sca... | 5,300,149 |
def estimate_corr(data, algorithm="ica", lower_limit=0.01, prior_knowledge=None):
"""Generate DAG of pair-wise LiNGAM coefficient"""
import lingam
def _model(alg, _kwargs):
if alg == "ica":
return lingam.ICALiNGAM(**_kwargs)
elif alg == "direct":
return lingam.Direct... | 5,300,150 |
def fluo_amplitude(elem, line, excitation=None, barn_unit=False):
"""Get the fluorescence cross section for a given element/line
Parameters
----------
elem : string or number
element
line : string
emission line Siegban (e.g. 'LA1') or IUPAC (e.g. 'L3M5')
excitation : float (opti... | 5,300,151 |
def test_embed_opengraph_album(meta_tags: List[element.Tag], img_tags: List[element.Tag]):
"""Test."""
og_images = [t for t in meta_tags if t.get("property", "") == "og:image"]
assert not og_images
og_image_alts = [t for t in meta_tags if t.get("property", "") == "og:image:alt"]
assert not og_image_... | 5,300,152 |
def fmt_sec(sec):
"""Take a time in seconds and convert it to mm:ss.ms"""
return fmt_ms(int(sec) * 1000) | 5,300,153 |
def store_peer_info(info_hash, peer_id, ip, port, status):
"""Store the information about the peer.
"""
db = get_db()
if info_hash in db:
if (peer_id, ip, port, status) not in db[info_hash]:
db[info_hash].append((peer_id, ip, port, status))
else:
db[info_hash] = [(peer_id... | 5,300,154 |
def accountingEnabledForRecord(record):
"""
Determine if accounting is enabled for the given record.
"""
enabledRecordGUIDs = config.AccountingPrincipals
if "*" in enabledRecordGUIDs:
return True
return record.uid in enabledRecordGUIDs | 5,300,155 |
def start_recurring_cycles():
"""Start recurring cycles by cron job."""
with benchmark("contributed cron job start_recurring_cycles"):
today = date.today()
workflows = models.Workflow.query.filter(
models.Workflow.next_cycle_start_date <= today,
models.Workflow.recurrences == True # noqa
... | 5,300,156 |
def rhsso_setup(lifecycle_hooks, rhsso_service_info):
"""Have application/service with RHSSO auth configured"""
# , accessTokenLifespan=24*60
lifecycle_hooks.append(OIDCClientAuthHook(rhsso_service_info)) | 5,300,157 |
def initialize_weights(session_id, tir_graph, bindings):
"""Initialize weights for graph in the Session.
Parameters
----------
session_id : int
The Session in which the graph is initialized.
tir_graph : tvm.tg.TIRGraph
The graph for which to initialize weights.
bindings : dict... | 5,300,158 |
def inventory_reset():
""" Removes all inventory from the database """
Inventory.remove_all()
return make_response('', status.HTTP_204_NO_CONTENT) | 5,300,159 |
def make_data_fn(is_training, timesteps2use):
"""returns data function for processing and returning a feed dictionary to be passed to model"""
def data_fn(data):
text_batch = Variable(data[0].long(), requires_grad=False, volatile=not is_training)
mask = Variable(data[1], requires_grad=False, volatile=not is_train... | 5,300,160 |
def shift_left(x, axis=1):
"""Shift the input to the right by padding and slicing on axis."""
pad_widths = [(0, 0)] * len(x.shape)
pad_widths[axis] = (0, 1)
padded = jnp.pad(
x, pad_widths, mode='constant', constant_values=x.dtype.type(0)
)
# print(padded)
return lax.dynamic_slice_in... | 5,300,161 |
def process_swap(swap_id):
"""
Process validator swap depends on it's status
"""
info('check swap')
try:
with transaction.atomic():
swap = ValidatorSwap.displayed_objects.select_for_update(
nowait=True
) \
.filter(id=swap_id) \
... | 5,300,162 |
def load_cows(filename):
"""
Read the contents of the given file. Assumes the file contents contain
data in the form of comma-separated cow name, weight pairs, and return a
dictionary containing cow names as keys and corresponding weights as values.
Parameters:
filename - the name of the data ... | 5,300,163 |
def test_cookies2():
"""Test to make sure that we don't override user specified cookies"""
http_ua = http.HttpUA()
x = ruleset.Input(dest_addr="ieee.org",headers={"Host":"ieee.org"})
http_ua.send_request(x)
x = ruleset.Input(dest_addr="ieee.org",headers={"Host":"ieee.org","cookie":"TS01293935=012f35... | 5,300,164 |
def find_bin_edges(cbins):
""" Given bin centres, find the bin edges.
Examples
--------
>>> print find_bin_edges([1, 2.1, 3.3, 4.6])
[ 0.45 1.55 2.7 3.95 5.25]
"""
cbins = np.asarray(cbins)
edges = cbins[:-1] + 0.5 * (cbins[1:] - cbins[:-1])
edges = np.concatenate( ([2*cbins[0]... | 5,300,165 |
def run():
"""
prepare txt data
"""
args = parse_args()
test_size = int(args.train_line_count * args.test_size)
all_indices = [i for i in range(args.train_line_count)]
np.random.seed(args.seed)
np.random.shuffle(all_indices)
print("all_indices.size:{}".format(len(all_indices)))
t... | 5,300,166 |
def retrieval_collate(data):
"""Creates mini-batch tensors from the list of tuples (src_seq, trg_seq)."""
# separate source and target sequences
t2i_batch, i2t_batch = list(zip(*data))
# t2i
def generate_inputs(_batch):
sent, att_feats, img_masks, box_feats, obj_labels, pos_labels, img_ids,... | 5,300,167 |
def index():
"""
represents dashboard home page
"""
member = Member.query.count()
product = Product.query.count()
paid_off = Order.query.filter_by(paid_off=True).count()
unpaid_off = Order.query.filter_by(paid_off=False).count()
return render_template(
"dashboard/index.html",
... | 5,300,168 |
def test_args_parses_job_identifier():
"""The application defines arguments that correspond to the identifier."""
ji = JobIdentifier(RecipeIdentifier(32, "estimate_location", "female"), "draws")
app = DismodAT()
parser = ArgumentParser()
parser = app.add_arguments(parser)
arg_list = ["--mvid", "... | 5,300,169 |
def show_search_results(
log_rec,
code_view=True,
json_view=False,
show_message_details=False):
"""show_search_results
Show search results like rsyslog or as pretty-printed
JSON dictionaries per log for debugging drill-down fields
:param log_rec: log record from splunk
... | 5,300,170 |
def wrap_hashlib(hasher, length=None):
"""
Wraps hashlib's functions, returning a function that returns the hex-digest of its input.
>>> from hashlib import sha1
>>> wrap_hashlib(sha1)(b'heyo')
'f8bb1031d6d82b30817a872b8a2ec31d5380cee5'
:param hasher: A function from :mod:`hashlib`
:return... | 5,300,171 |
def main():
""" check ssl expired info """
logger.info('################################################################################')
logger.info('start check the ssl info on this cluster')
logger.info('################################################################################')
args = ... | 5,300,172 |
def export_fhir_store_gcs(project_id, location, dataset_id, fhir_store_id, gcs_uri):
"""Export resources to a Google Cloud Storage bucket by copying
them from the FHIR store.
See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
before running the sample... | 5,300,173 |
async def read_fastq_headers(path: Path) -> list:
"""
Return a list of FASTQ headers for the FASTQ file located at `path`. Only accepts uncompressed FASTQ files.
:param path: the path to the FASTQ file
:return: a list of FASTQ headers
"""
headers = list()
had_plus = False
async with ... | 5,300,174 |
def install(append, shell, path):
"""Install the click-completion-command completion."""
# Install
shell, path = click_completion.core.install(
shell=shell, path=path, append=append
)
# Report back
click.echo("%s completion installed in %s" % (shell, path)) | 5,300,175 |
def batch_status():
"""
Same as status, but for a list of IDs.
INput message shall be { "ids": [id1, id2, ...] } where ids are task-ids
The returned global status will be PENDING unless all tasks are SUCCESSful
:return: json message with {"status": global status, "progress": progress-message, "detai... | 5,300,176 |
def download_wukrii(program_abs_path, wukrii_page_num):
"""Downloads latest Wukrii comics."""
# Create/change appropriate comic folder.
comic_folder = os.path.join(program_abs_path, "wukrii")
if os.path.exists(comic_folder):
os.chdir(comic_folder)
else:
os.mkdir(comic_folder)
... | 5,300,177 |
def test_change_scoring_strategy(regression_data, experiment):
"""check same scoring value in convex objective"""
df, y = regression_data
model = TunedKNNRegressorBlock(name='test', n_trials=1,
scoring='neg_root_mean_squared_error',
scori... | 5,300,178 |
def _get_lastword_range(prefix, stringlist, tokenizer=None):
"""
Get the range of lastword tokenized index in label_ids
Args:
prefix: list(str), list of text with its last word removed(a.k.a. "prefix") in form of str
stringlist: list(str), list of text, same as it is in split_by_last_word
... | 5,300,179 |
def is_valid_solution(G, c, k):
"""
Checks whether D is a valid mapping of G, by checking every room adheres to the stress budget.
Args:
G: networkx.Graph
c: List of cities to remove
k: List of edges to remove (List of tuples)
Returns:
bool: false if removing k and c disc... | 5,300,180 |
def get_loss_layer(mlp_out, action, precision, batch_size):
"""The loss layer used for the MLP network is obtained through this class."""
scale_factor = tf.constant(2*batch_size, dtype='float')
uP = batched_matrix_vector_multiply(action - mlp_out, precision)
uPu = tf.reduce_sum(uP*(action - mlp_out)) #... | 5,300,181 |
def view_task_info(token, dstore):
"""
Display statistical information about the tasks performance.
It is possible to get full information about a specific task
with a command like this one, for a classical calculation::
$ oq show task_info:classical
"""
args = token.split(':')[1:] # cal... | 5,300,182 |
def revision_exists(git_dir, revision):
"""
check if the provided revision exists
With attempt to find if the provided revision values (be it a branch, tag or
hash value) exists in the provided Git directory.
Args:
git_dir: the Git directory
revision: the revision (branch, tag, has... | 5,300,183 |
def isOldEnough(nzbFile):
""" Determine if the NZB file's modification time is > Hellanzb.NZBQUEUE_MDELAY """
mtime = os.stat(nzbFile).st_mtime
now = time.time()
if mtime < now and now - mtime < Hellanzb.NZBQUEUE_MDELAY:
debug('Delaying enqueue of %s: mtime: %i Hellanzb.NZBQUEUE_MDELAY: %i' % \
... | 5,300,184 |
def isBlank(s):
""" Returns True if string contains only space characters."""
return bool(re.compile("^\s*$").match(s)) | 5,300,185 |
def nicedit_image_upload():
"""
Controller to upload images with nicedit
"""
from gluon.contrib.simplejson import dumps
from os import mkdir
page_id = request.args(0)
pathname = path.join(request.folder,'static','images', 'pages_content', page_id)
if not path.exists(pathname):
... | 5,300,186 |
def __extract_tzd(m):
"""Return the Time Zone Designator as an offset in seconds from UTC."""
if not m:
return 0
tzd = m.group("tzd")
if not tzd:
return 0
if tzd == "Z":
return 0
hours = int(m.group("tzdhours"), 10)
minutes = m.group("tzdminutes")
if minutes:
... | 5,300,187 |
def measure(dataframe, lasers=[405, 488, 561, 638], channels=[1, 2, 3, 4, 5, 6],
create_fcs=False, outfile_name='sample_output.fcs'):
"""
This is a function that will measure fluorescence
intensity for any given sample DataFrame and laser/channel
parameters. Output will be just a pandas Data... | 5,300,188 |
def print_errors_result(result, verbose=False):
"""
"""
spacers = 4
if verbose:
print(f"\nTotal Stats\n{spacers*' '}max. err.: {result[0]:6.3f};")
print(f"{(spacers-2)*' '}c-avg. err.: {result[1]:6.3f};")
print(f"{(spacers-2)*' '}t-avg. err.: {result[2]:6.3f}")
r... | 5,300,189 |
def test_snmp_interfaces(localhost, creds, duthosts, enum_dut_hostname, enum_asic_index):
"""compare the snmp facts between observed states and target state"""
duthost = duthosts[enum_dut_hostname]
hostip = duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars['ansible_host']
namesp... | 5,300,190 |
def get_multilabeled_data(tup, vocab, labeldict, max_len):
"""
used for val, since we have contradictory labelings...
tup is (sent, [rels]);
each rel is
((ent_start, ent_end, ent_str), (num_start, num_end, num_str), label)
"""
sent = [vocab[wrd] if wrd in vocab else vocab["UNK"] for wrd in t... | 5,300,191 |
def add_date_annotations(annotations, matches):
"""
Converts matches to TextDateAnnotation objects and adds them to the
annotations array specified.
"""
for match in matches:
if match['type'] in ["DATE"]:
annotations.append(TextDateAnnotation(
start=match['start']... | 5,300,192 |
def filter_country_stats(stats, top_n, latest_date):
"""Filter the top n country statistics
Arguments:
stats {dict} -- The country statistics
top_n {int} -- The top n results to retrieve
latest_date {datetime} -- The latest date
Returns:
dict -- The filtered country... | 5,300,193 |
def list_dict(l):
"""
return a dictionary with all items of l being the keys of the dictionary
"""
return dict([(i,None) for i in l]) | 5,300,194 |
def readnetcdfInitial(name, value,default = 0.0):
"""
load initial condition from netcdf format
"""
filename = os.path.normpath(name)
try:
nf1 = Dataset(filename, 'r')
except:
msg = "Netcdf Initial file: \n"
raise CWATMFileError(filename,msg)
if value in nf1.variable... | 5,300,195 |
def value_at_location(x, single_vol=False, single_pts=False, force_post_absolute_val=True):
"""
Extracts value at given point.
"""
# vol is batch_size, *vol_shape, nb_feats
# loc_pts is batch_size, nb_surface_pts, D or D+1
vol, loc_pts = x
fn = lambda y: ne.utils.interpn(y[0], y[1])
... | 5,300,196 |
def _check_dataclass_item_pyclass(item_pyclass: Optional[Type[Any]], registry: Optional[ExtensionTypeRegistry]) -> None:
"""Check an input Python class is a supported dataclass definition.
TODO: check if the dataclass field are supported, i.e.:
- Field types is a base type or part of the Arrowbic regis... | 5,300,197 |
def is_reference(key: str) -> bool:
"""
Does this key represent a berglas reference
"""
return key.startswith(REFERENCE_PREFIX) | 5,300,198 |
def extract_data(path: str) -> None:
"""Extract GZIP file from path.
Parameters
----------
path : str
Path to GZIP file
"""
tar = tarfile.open(path, mode="r")
tar.extractall(path="data/")
tar.close() | 5,300,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.