content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def encrypt(plaintext, a, b):
"""
加密函数:E(x) = (ax + b)(mod m) m为编码系统中的字母数,一般为26
:param plaintext:
:param a:
:param b:
:return:
"""
cipher = ""
for i in plaintext:
if not i.isalpha():
cipher += i
else:
n = "A" if i.isupper() else "a... | 5,347,600 |
def threshold(alpha):
"""Only two-to-one mapping is supported.
"""
alpha[0] = min(1., max(0., (1. + alpha[0] - alpha[1]) * .5))
alpha[1] = 1. - alpha[0] | 5,347,601 |
def construct_gn_command(output_path, gn_flags, python2_command=None, shell=False):
"""
Constructs and returns the GN command
If shell is True, then a single string with shell-escaped arguments is returned
If shell is False, then a list containing the command and arguments is returned
"""
gn_arg... | 5,347,602 |
def reads_in_file(file_path):
""" Find the number of reads in a file.
Count number of lines with bash wc -l and divide by 4 if fastq, otherwise by 2 (fasta) """
return round(int(subprocess.check_output(["wc", "-l", file_path]).split()[0]) /
(4 if bin_classify.format == "fastq" else ... | 5,347,603 |
def _url_as_filename(url: str) -> str:
"""Return a version of the url optimized for local development.
If the url is a `file://` url, it will return the remaining part
of the url so it can be used as a local file path. For example,
'file:///logs/example.txt' will be converted to
'/logs/example.txt'... | 5,347,604 |
def hard_max(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX Hardmax to XLayer AnyOp conversion function
Input tensor shape: N dims
Output tensor shape: 2D
"""
logger.info("ONNX Hardmax -> XLayer AnyOp")
assert len(node.get_output... | 5,347,605 |
def sol_files_by_directory(target_path: AnyStr) -> List:
"""Gathers all the .sol files inside the target path
including sub-directories and returns them as a List.
Non .sol files are ignored.
:param target_path: The directory to look for .sol files
:return:
"""
return files_by_directory(tar... | 5,347,606 |
def _call(sig, *inputs, **kwargs):
"""Adds a node calling a function.
This adds a `call` op to the default graph that calls the function
of signature `sig`, passing the tensors in `inputs` as arguments.
It returns the outputs of the call, which are one or more tensors.
`sig` is OpDefArg.a `_DefinedFunction`... | 5,347,607 |
def api_url_for(view_name, _absolute=False, _xml=False, *args, **kwargs):
"""Reverse URL lookup for API routes (that use the JSONRenderer or XMLRenderer).
Takes the same arguments as Flask's url_for, with the addition of
`_absolute`, which will make an absolute URL with the correct HTTP scheme
based on ... | 5,347,608 |
def cov(x, rowvar=False, bias=False, ddof=None, aweights=None):
"""Estimates covariance matrix like numpy.cov"""
# ensure at least 2D
if x.dim() == 1:
x = x.view(-1, 1)
# treat each column as a data point, each row as a variable
if rowvar and x.shape[0] != 1:
x = x.t()
if ddof ... | 5,347,609 |
def threadsafe_generator(f):
"""A decorator that takes a generator function and makes it thread-safe.
Args:
f(function): Generator function
Returns:
None
"""
def g(*args, **kwargs):
"""
Args:
*args(list): List of non-key worded,variable length arguments.
... | 5,347,610 |
def load_many_problems(file, collection):
"""Given a ZIP file containing several ZIP files (each one a problem),
insert the problems into collection"""
problems = list()
try:
with ZipFile(file) as zfile:
for filename in zfile.infolist():
with zfile.open(filename) a... | 5,347,611 |
def CheckStructuralModelsValid(rootGroup, xyzGridSize=None, verbose=False):
"""
**CheckStricturalModelsValid** - Checks for valid structural model group data
given a netCDF root node
Parameters
----------
rootGroup: netCDF4.Group
The root group node of a Loop Project File
xyzGri... | 5,347,612 |
def get_load_balancers():
"""
Return all load balancers.
:return: List of load balancers.
:rtype: list
"""
return elbv2_client.describe_load_balancers()["LoadBalancers"] | 5,347,613 |
def init_app(app):
"""Makes sure the db gets closed and init-db command works.
:param type app: flask.Flask.
"""
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command) | 5,347,614 |
def get_datasets(folder):
"""
Returns a dictionary of dataset-ID: dataset directory paths
"""
paths = glob(f"{folder}/*")
return {os.path.split(p)[-1]: p for p in paths if os.path.isdir(p)} | 5,347,615 |
def create_dir(path):
"""
This routine creates directories.
"""
try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path) | 5,347,616 |
def file_preview(request):
"""
Live preview of restructuredtext payload - currently not wired up
"""
f = File(
heading=request.POST['heading'],
content=request.POST['content'],
)
rendered_base = render_to_string('projects/doc_file.rst.html', {'file': f})
rendered = restructur... | 5,347,617 |
def makeMask(n):
"""
return a mask of n bits as a long integer
"""
return (long(2) << n - 1) - 1 | 5,347,618 |
def link_name_to_index(model):
""" Generate a dictionary for link names and their indicies in the
model. """
return {
link.name : index for index, link in enumerate(model.links)
} | 5,347,619 |
def create_audio_dataset(
dataset_path: str, dataset_len=100, **kwargs
) -> pd.DataFrame:
""" Creates audio dataset from file structure.
Args:
playlist_dir: Playlist directory path.
# TODO dataset_len (optional): Number of audio files to include.
Returns:
df: Compiled dataframe... | 5,347,620 |
def _run_plugins(st,
make_all=False,
run_id=test_run_id_nT,
**proces_kwargs):
"""
Try all plugins (except the DAQReader) for a given context (st) to see if
we can really push some (empty) data from it and don't have any nasty
problems like that we are r... | 5,347,621 |
def unzip_file(file_to_unzip, destination_to_unzip="unzip_apk"):
"""
Extract all directories in the zip to the destination.
:param str file_to_unzip:
:param str destination_to_unzip:
"""
if not os.path.isdir(destination_to_unzip):
os.makedirs(destination_to_unzip)
try:
zippe... | 5,347,622 |
def photos_page():
"""
Example view demonstrating rendering a simple HTML page.
"""
context = make_context()
with open('data/featured.json') as f:
context['featured'] = json.load(f)
return make_response(render_template('photos.html', **context)) | 5,347,623 |
def get_user_by_id(current_user, uid):
""" Получение одного пользователя по id в json"""
try:
user_schema = CmsUsersSchema(exclude=['password'])
user = CmsUsers.query.get(uid)
udata = user_schema.dump(user)
response = Response(
response=json.dumps(udata.data),
... | 5,347,624 |
def update_bond_lists_mpi(bond_matrix, comm, size, rank):
"""
update_bond_lists(bond_matrix)
Return atom indicies of angular terms
"""
N = bond_matrix.shape[0]
"Get indicies of bonded beads"
bond_index_full = np.argwhere(bond_matrix)
"Create index lists for referring to in 2D arrays"
indices_full = create_... | 5,347,625 |
def RepoRegion(args, cluster_location=None):
"""Returns the region for the Artifact Registry repo.
The intended behavior is platform-specific:
* managed: Same region as the service (run/region or --region)
* gke: Appropriate region based on cluster zone (cluster_location arg)
* kubernetes: The run/region... | 5,347,626 |
def html(ctx, **kwargs):
"""Formats meeting HTML"""
ensure_config(ctx.obj)
ctx.obj.update(kwargs)
args = AttrDict(ctx.obj)
context = Context(args)
context.prerender()
content = context.render()
logger.info(f'Generated {len(content)//1000}KB of HTML content')
logger.info(f'Total meeti... | 5,347,627 |
def install_nightly_packs(client: demisto_client,
host: str,
packs_to_install: List,
request_timeout: int = 999999):
"""
Install content packs on nightly build.
We will catch the exception if pack fails to install and send the req... | 5,347,628 |
def compile(expr: ibis.Expr, params=None):
"""Compile a given expression.
Note you can also call expr.compile().
Parameters
----------
expr : ibis.Expr
params : dict
Returns
-------
compiled : string
"""
from ibis.omniscidb.compiler import to_sql
return to_sql(expr, d... | 5,347,629 |
def get_border(border, size):
"""
Get border
"""
i = 1
while size - border // i <= border // i: # size > 2 * (border // i)
i *= 2
return border // i | 5,347,630 |
def load_normalized_data(file_path, log1p=True):
"""load normalized data
1. Load filtered data for both FACS and droplet
2. Size factor normalization to counts per 10 thousand
3. log(x+1) transform
4. Combine the data
Args:
file_path (str): file path.
Returns:
adata_combin... | 5,347,631 |
def from_copy_number(
model: cobra.Model,
index: pd.Series,
cell_copies: pd.Series,
stdev: pd.Series,
vol: float,
dens: float,
water: float,
) -> cobra.Model:
"""Convert `cell_copies` to mmol/gDW and apply them to `model`.
Parameters
----------
model: cobra.Model
cob... | 5,347,632 |
def test_exclude_crds_mask_pix():
"""Test that bad pixel images are differentiated correctly
"""
common_bad = ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])
bad1_only = ([0, 1, 3, 4], [4, 3, 1, 0])
bad2_only = ([3, 3, 3, 3], [0, 1, 2, 4])
bad1 = np.zeros((5, 5), dtype=np.uint8)
bad1[common_bad] = 1
... | 5,347,633 |
def getstatusoutput(cmd):
"""Return (exitcode, output) of executing cmd in a shell.
Execute the string 'cmd' in a shell with 'check_output' and
return a 2-tuple (status, output). The locale encoding is used
to decode the output and process newlines.
A trailing newline is stripped from the output.
... | 5,347,634 |
def _get_values(attribute, text):
"""Match attribute in text and return all matches.
:returns: List of matches.
"""
regex = '{}\s+=\s+"(.*)";'.format(attribute)
regex = re.compile(regex)
values = regex.findall(text)
return values | 5,347,635 |
def time_axis(tpp=20e-9, length=20_000) -> np.ndarray:
"""Return the time axis used in experiments.
"""
ts = tpp * np.arange(length)
ten_percent_point = np.floor(length / 10) * tpp
ts -= ten_percent_point
ts *= 1e6 # convert from seconds to microseconds
return ts | 5,347,636 |
def _has_perm(user, ctnr, action, obj=None, obj_class=None):
"""
Checks whether a user (``request.user``) has permission to act on a
given object (``obj``) within the current session CTNR. Permissions will
depend on whether the object is within the user's current CTNR and
the user's permissions leve... | 5,347,637 |
def log_level(bot: Bot, event: Event, irc: connection_wrapper, args: List[str]):
"""<level>
Changes the logging level"""
try:
log.setLevel(getattr(log, args[0].upper()))
irc.reply(event, f"Set log level to {args[0]}")
except AttributeError:
irc.reply(event, f"Invalid log l... | 5,347,638 |
def read_chunk(file: File, size: int=400) -> bytes:
""" Reads first [size] chunks from file, size defaults to 400 """
file = _path.join(file.root, file.name) # get full path of file
with open(file, 'rb') as file:
# read chunk size
chunk = file.read(size)
return chunk | 5,347,639 |
def plot_tensorflow_log(args):
"""
Plot data from tensorboard event file.
"""
# Loading too much data is slow...
tf_size_guidance = {'scalars': args.num_load}
event_acc = EventAccumulator(args.log_name, tf_size_guidance)
event_acc.Reload()
assert event_acc.Tags()["scalars"] != [],... | 5,347,640 |
def parse_input(file_path):
"""
Turn an input file of newline-separate bitrate samples into
input and label arrays. An input file line should look like this:
4983 1008073 1591538 704983 1008073 1008073 704983
Adjacent duplicate entries will be removed and lines with less than
two samples will ... | 5,347,641 |
def read(rel_path):
""" Docstring """
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, rel_path), 'r') as fp:
return fp.read() | 5,347,642 |
def main(argv=None):
"""Main command line interface."""
if argv is None:
argv = sys.argv[1:]
cli = CommandLineTool()
try:
return cli.run(argv)
except KeyboardInterrupt:
print('Canceled')
return 3 | 5,347,643 |
def extract_attrs_for_lowering(mod: nn.Module) -> Dict[str, Any]:
"""If `mod` is in `module_fetch_book`, fetch the mod's attributes that in the `module_fetch_book`
after checking module's version is compatible with the `module_fetch_book`.
"""
attrs_for_lowering: Dict[str, Any] = {}
attrs_for_loweri... | 5,347,644 |
def get_filter_fields(target: str, data_registry_url: str, token: str) -> Set[str]:
"""
Returns a list of filterable fields from a target end point by calling OPTIONS
:param target: target end point of the data registry
:param data_registry_url: the url of the data registry
:param token: personal a... | 5,347,645 |
def cli_invitation():
"""`crcr invitation`の起点."""
pass | 5,347,646 |
def azimuthalAverage(image, center=None):
"""
Calculate the azimuthally averaged radial profile.
image - The 2D image
center - The [x,y] pixel coordinates used as the center. The default is
None, which then uses the center of the image (including
fracitonal pixels).
http... | 5,347,647 |
def run_tasks(api,
logger,
config):
"""Launch CGC tasks.
Parameters
----------
api: SevenBridges API instance
Api
logger: logger instance
Log
config: dict
YAML configuration file
"""
logger.info('Running tasks!')
project = config... | 5,347,648 |
def train_transforms_fisheye(sample, image_shape, jittering):
"""
Training data augmentation transformations
Parameters
----------
sample : dict
Sample to be augmented
image_shape : tuple (height, width)
Image dimension to reshape
jittering : tuple (brightness, contrast, sat... | 5,347,649 |
def build_json_output_request(**kwargs: Any) -> HttpRequest:
"""A Swagger with XML that has one operation that returns JSON. ID number 42.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.core.rest.H... | 5,347,650 |
def merge_extended(args_container: args._ArgumentContainer, hold: bool, identificator: str) -> int:
"""
Merge the args_container into the internal, like merge_named, but hold specifies if the internal container should not be cleared.
:param args_container: The argument container with the data to merge
... | 5,347,651 |
def video_path_file_name(instance, filename):
""" Callback for video node field to get path file name
:param instance: the image field
:param filename: the file name
:return: the path file name
"""
return path_file_name(instance, 'video', filename) | 5,347,652 |
def setup_platform(opp, config, add_entities, discovery_info=None):
"""Set up the cover platform for ADS."""
ads_hub = opp.data[DATA_ADS]
ads_var_is_closed = config.get(CONF_ADS_VAR)
ads_var_position = config.get(CONF_ADS_VAR_POSITION)
ads_var_pos_set = config.get(CONF_ADS_VAR_SET_POS)
ads_var_... | 5,347,653 |
def _suppress_hotkey(steps, timeout):
"""
Adds a hotkey to the list of keys to be suppressed.
To unsuppress all hotkeys use `clear_all_hotkeys()`.
"""
_key_table.suppress_sequence(steps, timeout) | 5,347,654 |
def radiative_processes_mono(flux_euv, flux_fuv,
average_euv_photon_wavelength=242.0,
average_fuv_photon_wavelength=2348.0):
"""
Calculate the photoionization rate of helium at null optical depth based
on the EUV spectrum arriving at the planet.
... | 5,347,655 |
def handle_exception(exc):
"""
:return: void
Tries to handle it
"""
print("[CRITICAL ERROR]:", str(exc).replace("\n", ".") + "!!!")
print("pyhodl stopped abruptly, but your data is safe, don't worry.")
user_input = UserInput()
if user_input.get_yes_no("Want to fill a bug report?"):
... | 5,347,656 |
def date_yyyymmdd(now: typing.Union[datetime.datetime, None] = None, day_delta: int = 0, month_delta: int = 0) -> str:
"""
:param day_delta:
:param month_delta:
:return: today + day_delta + month_delta -> str YYYY-MM-DD
"""
return date_delta(now, day_delta, month_delta).strftime("%Y-%m-%d") | 5,347,657 |
def description_for_number(*args, **kwargs):
"""Return a text description of a PhoneNumber object for the given language.
The description might consist of the name of the country where the phone
number is from and/or the name of the geographical area the phone number
is from. This function explicitly ... | 5,347,658 |
def get_pathway_nodes(pathway):
"""Return single nodes in pathway.
:param pathme_viewer.models.Pathway pathway: pathway entry
:return: BaseAbundance nodes
:rtype: list[pybel.dsl.BaseAbundance]
"""
# Loads the BELGraph
graph = from_bytes(pathway.blob)
collapse_to_genes(graph)
# Ret... | 5,347,659 |
def restore_modifiers(scan_codes):
"""
Like `restore_state`, but only restores modifier keys.
"""
restore_state((scan_code for scan_code in scan_codes if is_modifier(scan_code))) | 5,347,660 |
def check_currrent_user_privilege():
"""
Check if our user has interesting tokens
"""
# Interesting Windows Privileges
# - SeDebug
# - SeRestore
# - SeBackup
# - SeTakeOwnership
# - SeTcb
# - SeCreateToken
# - SeLoadDriver
# - SeImpersonate
# - SeAssignPrimaryToken
... | 5,347,661 |
def handle_domain_addition_commands(client: Client, demisto_args: dict) -> CommandResults:
"""
Adds the domains to the inbound blacklisted list.
:type client: ``Client``
:param client: Client to use.
:type demisto_args: ``dict``
:param demisto_args: The demisto arguments.
... | 5,347,662 |
def _tc4(dom: AbsDom):
""" Validate that my AcasNet module can be optimized at the inputs. """
mse = nn.MSELoss()
max_retries = 100
max_iters = 30 # at each retry, train at most 100 iterations
def _loss(outputs_lb):
lows = outputs_lb[..., 0]
distances = 0 - lows
distances =... | 5,347,663 |
def delete_image(inputkey, inputName):
"""Function to delete image"""
folder = get_image_path(inputkey, inputName)
os.remove(folder) | 5,347,664 |
def skip_url(url):
"""
Skip naked username mentions and subreddit links.
"""
return REDDIT_PATTERN.match(url) and SUBREDDIT_OR_USER.search(url) | 5,347,665 |
def assert_dataset_like(
ds1: timeseries.MultiRegionDataset,
ds2: timeseries.MultiRegionDataset,
*,
drop_na_timeseries=False,
drop_na_latest=False,
drop_na_dates=False,
compare_tags=True,
):
"""Asserts that two datasets contain similar date, ignoring order."""
ts1 = _timeseries_sorte... | 5,347,666 |
def test_not_connected():
"""Test send commands without connection."""
device = _TestDevice(SERIAL, CREDENTIAL)
with pytest.raises(DysonNotConnected):
device.request_current_status()
assert device._status is None
with pytest.raises(DysonNotConnected):
device._send_command("COMMAND") | 5,347,667 |
def registry():
"""
Return a dictionary of problems of the form:
```{
"problem name": {
"params": ...
},
...
}```
where `flexs.landscapes.AdditiveAAVPackaging(**problem["params"])` instantiates the
additive AAV packaging landscape for the given set of paramet... | 5,347,668 |
def ecm(n, rounds, b1, b2, wheel=2310, output=True):
"""Elliptic Curve Factorization Method. In each round, the following steps are performed:
0. Generate random point and curve.
1. Repeatedly multiply the current point by small primes raised to some power, determined
by b1.
2. S... | 5,347,669 |
def FBSleep(MilliSeconds):
"""
Sleep function Puts system to sleep for specified time.
MilliSeconds : Time to sleep for.
"""
pass | 5,347,670 |
def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
"""Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
Args:
doc: The XML document. May be modified by this function.
min_sdk_version: The requested minSdkVersion attribute.
target_sdk_version: The requested ... | 5,347,671 |
def dc_mode_option(update: Update, contex: CallbackContext) -> Optional[int]:
"""Get don't care response mode option"""
ndc = contex.user_data[0]
if ndc.response_mode == DoesntCare.ResponseMode.TIME:
if not re.match(r"[0-9]+:[0-9]+:[0-9]+", update.effective_message.text):
update.effecti... | 5,347,672 |
def is_in_period(datetime_, start, end):
"""指定した日時がstartからendまでの期間に含まれるか判定する"""
return start <= datetime_ < end | 5,347,673 |
def consume(url):
"""Consume messages"""
ctx = zmq.Context.instance()
s = ctx.socket(zmq.PULL)
s.connect(url)
print("Consuming")
for i in range(MSGS * PRODUCERS):
msg = s.recv()
print(msg.decode('ascii'))
print("Consumer done")
s.close() | 5,347,674 |
def set_shared_params(a, b):
"""
Args:
a (chainer.Link): link whose params are to be replaced
b (dict): dict that consists of (param_name, multiprocessing.Array)
"""
assert isinstance(a, chainer.Link)
for param_name, param in a.namedparams():
if param_name in b:
share... | 5,347,675 |
def create_experiment_summary():
"""Returns a summary proto buffer holding this experiment"""
# Convert TEMPERATURE_LIST to google.protobuf.ListValue
temperature_list = struct_pb2.ListValue().extend(TEMPERATURE_LIST)
return summary.experiment_pb(
hparam_infos=[
api_pb2.HParamInfo(name="initial_t... | 5,347,676 |
def get_session(token, custom_session=None):
"""Get requests session with authorization headers
Args:
token (str): Top secret GitHub access token
custom_session: e.g. betamax's session
Returns:
:class:`requests.sessions.Session`: Session
"""
session = custom_sessio... | 5,347,677 |
def mass_to_tbint_to_energy_map(dpath, filterfn=lambda x: True,
fpath_list=None):
"""Given a directory, creates a mapping
mass number -> ( a, b, c, d, j -> energy )
using the files in the directory
:param fpath_list:
:param dpath: the directory which is a direct p... | 5,347,678 |
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = unicodedata.normalize('NFD', text)
text = text.encode('ascii', 'ignore')
text = text.decode("utf-8")
r... | 5,347,679 |
def write_png(filename, image):
"""Writes a PNG image file."""
image = tf.squeeze(image, 0)
if image.dtype.is_floating:
image = tf.round(image)
if image.dtype != tf.uint8:
image = tf.saturate_cast(image, tf.uint8)
string = tf.image.encode_png(image)
tf.io.write_file(filename, str... | 5,347,680 |
def json_formatter(result, _verbose):
"""Format result as json."""
if isinstance(result, list) and "data" in result[0]:
res = [json.dumps(record) for record in result[0]["data"]]
output = "\n".join(res)
else:
output = json.dumps(result, indent=4, sort_keys=True)
return output | 5,347,681 |
def show_all_companies():
"""Show all companies a user has interest in."""
# redirect if user is not logged in
if not session:
return redirect('/')
else:
# get user_id from session
user_id = session['user_id']
user = User.query.filter(User.user_id == user_id).one()
... | 5,347,682 |
def add_atstop_proc(func):
"""At serving server stop, execute function"""
global at_stop_list
at_stop_list.append(func) | 5,347,683 |
def run_sim(G, numsteps=100):
"""
Run a simulation for numsteps steps and plot the resulting curves
:param G: A networkx graph
:param numsteps: The number of steps to run the simulation for
:return: None
"""
num_s = []
num_i = []
num_r = []
for i in range(numsteps):
upda... | 5,347,684 |
def test_duo_one_disconnect(opt, server_url):
"""Tests whether disconnects properly cause a task to fail and let the
non-disconnecting partner complete the HIT. Also tests reconnecting after
a partner disconnect or after a disconnect.
"""
global completed_threads
print('{} Starting'.format(DUO_O... | 5,347,685 |
def ll_combined_grad(x, item_ids, judge_ids, pairwise=[], individual=[]):
"""
This function computes the _negative_ gradient of the loglikelihood for
each parameter in x, for both the individual and pairwise data.
Keyword arguments:
x -- the current parameter estimates.
item_ids -- the ids... | 5,347,686 |
def relu(inp): # ReLu function as activation function
"""
ReLu neural network activation function
:param inp: Node value before activation
:return: Node value after activation
"""
return np.max(inp, 0) | 5,347,687 |
def getCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Creates a generator to perform one or more SNMP GET queries.
On each iteration, new SNMP GET request is send (:RFC:`1905#section-4.2.1`).
The iterator blocks waiting for response to arrive or error to occur.... | 5,347,688 |
def augment_sentence(tokens: List[str], augmentations: List[Tuple[List[tuple], int, int]], begin_entity_token: str,
sep_token: str, relation_sep_token: str, end_entity_token: str) -> str:
"""
Augment a sentence by adding tags in the specified positions.
Args:
tokens: Tokens of ... | 5,347,689 |
def evaluate_model_recall_precision(mat, num_items, testRatings, K_recall, K_precision, num_thread):
"""
Evaluate the performance (Hit_Ratio, NDCG) of top-K recommendation
Return: score of each test rating.
"""
global _mat
global _testRatings
global _K_recall
global _K_precision
glob... | 5,347,690 |
def pipe_hoop_stress(P, D, t):
"""Calculate the hoop (circumferential) stress in a pipe
using Barlow's formula.
Refs: https://en.wikipedia.org/wiki/Barlow%27s_formula
https://en.wikipedia.org/wiki/Cylinder_stress
:param P: the internal pressure in the pipe.
:type P: float
:param D: the ou... | 5,347,691 |
def node_constraints(node):
"""
Returns all constraints a node is linked to
:param node: str
:return: list(str)
"""
return maya.cmds.listRelatives(node, type='constraint') | 5,347,692 |
def save_data_file(sourceFile, destination = None, subdirectory = None, user = None, verbose = True):
""" Function used to save (i.e copy) a data file into a directory of choice after an experimental session
Parameters: sourceFile - the path of the file that was generated by the experimental session and t... | 5,347,693 |
def parse_file_name(filename):
"""
Parse the file name of a DUD mol2 file to get the target name and the y label
:param filename: the filename string
:return: protein target name, y_label string (ligand or decoy)
"""
bname = os.path.basename(filename)
splitted_bname = bname.split('_')
i... | 5,347,694 |
def load_opencv_stereo_calibration(path):
"""
Load stereo calibration information from xml file
@type path: str
@param path: video_path to xml file
@return stereo calibration: loaded from the given xml file
@rtype calib.data.StereoRig
"""
tree = etree.parse(path)
stereo_calib_elem = ... | 5,347,695 |
def _IsSingleElementTuple(token):
"""Check if it's a single-element tuple."""
close = token.matching_bracket
token = token.next_token
num_commas = 0
while token != close:
if token.value == ',':
num_commas += 1
if token.OpensScope():
token = token.matching_bracket
else:
token = to... | 5,347,696 |
def exportBufferView(gltf: GLTF2, primaryBufferIndex: int, byteOffset: int, byteLength: int) -> GLTFIndex:
"""Creates a glTF bufferView with the specified offset and length, referencing the default glB buffer.
Args:
gltf: Gltf object to append new buffer onto.
primaryBufferIndex: Index of the p... | 5,347,697 |
def ReadCan(filename):
"""Reads the candump in filename and returns the 4 fields."""
trigger = []
trigger_velocity = []
trigger_torque = []
trigger_current = []
wheel = []
wheel_velocity = []
wheel_torque = []
wheel_current = []
trigger_request_time = [0.0]
trigger_request_c... | 5,347,698 |
def retrieve(func):
"""
Decorator for Zotero read API methods; calls _retrieve_data() and passes
the result to the correct processor, based on a lookup
"""
def wrapped_f(self, *args, **kwargs):
"""
Returns result of _retrieve_data()
func's return value is part of a URI, and ... | 5,347,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.