content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def poll(module, function, args=(), kwargs={}, cron="", time="", delta_seconds=0, timeout=None, id_=None):
"""
create a poll job
will polling a url then use result as kwargs to call callback function
:param module: callback function's module name
:param function: callback function's function name
... | 5,337,700 |
def get_piesocket_api_key():
"""
Retrieves user's Piesocket API key.
Returns:
(str) Piesocket API key.
Raises:
(ImproperlyConfigured) if the Piesocket API key isn't specified in settings.
"""
return get_setting_or_raise(
setting="PIESOCKET_API_KEY", setting_str="PieSoc... | 5,337,701 |
def downsample(myarr,factor,estimator=np.mean):
"""
Downsample a 2D array by averaging over *factor* pixels in each axis.
Crops upper edge if the shape is not a multiple of factor.
This code is pure numpy and should be fast.
keywords:
estimator - default to mean. You can downsample by sum... | 5,337,702 |
def getActiveWindow():
"""Returns a Window object of the currently active Window."""
# Source: https://stackoverflow.com/questions/5286274/front-most-window-using-cgwindowlistcopywindowinfo
windows = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements | Quartz.kCGWindowListOpti... | 5,337,703 |
def _derivative_log(x):
"""Chain rule on natural log = (1/x)*(dx/dr)"""
return _protected_inverse(x[0])[:, :, np.newaxis, np.newaxis]*x[1] | 5,337,704 |
def svn_wc_merge_props(*args):
"""
svn_wc_merge_props(svn_wc_notify_state_t state, char path, svn_wc_adm_access_t adm_access,
apr_hash_t baseprops, apr_array_header_t propchanges,
svn_boolean_t base_merge,
svn_boolean_t dry_run, apr_pool_t pool) -> svn_error_t
"""
return _w... | 5,337,705 |
def is_paused():
"""
Return True if is_paused is set in the global settings table of the database.
"""
try:
is_paused_val = Settings.objects.get().is_paused
except ObjectDoesNotExist:
is_paused_val = False
return is_paused_val | 5,337,706 |
def info_request(request):
"""Information request form."""
if request.method == 'POST':
form = InfoRequestForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
# create out recipient list
to = []
# cleaned_data converts the data to a list s... | 5,337,707 |
def make_content_based_dataset(main_set):
"""
Make a dataset to work on for the content based filtering approach
"""
main_columns = [
"appid",
"english",
"name",
"developer",
"steamspy_tags",
"positive_ratings",
"negative_ratings"
]
desc_co... | 5,337,708 |
def test_protocol_configuration_schema_is_valid_wrt_draft_04():
"""Test that the JSON schema for the protocol configuration file is compliant with the specification Draft 04."""
protocol_config_schema = json.load(
open(
os.path.join(
ROOT_DIR,
"aea",
... | 5,337,709 |
def validate_did_management_ext_ids_v100(ext_ids):
"""
Validates the ExtIDs of a DIDManagement entry.
Parameters
----------
ext_ids: list of bytes
The ExtIDs of the entry
Raises
------
MalformedDIDManagementEntry
If the ExtIDs are not valid.
"""
if not (
... | 5,337,710 |
async def delete_workflow_revision(
# pylint: disable=W0622
id: UUID,
) -> None:
"""Delete a transformation revision of type workflow from the data base.
Deleting a transformation revision is only possible if it is in state DRAFT.
This endpoint is deprecated and will be removed soon,
use DELET... | 5,337,711 |
def test_invalid_isbn(talker):
"""Sometimes Marvel API sends number for isbn"""
murpg = talker.comics({"id": 1143}).comics[0]
assert murpg.isbn == "785110283"
assert murpg.prices.print == 9.99 | 5,337,712 |
def get_accurate(clustering_res_df, cluster_number, error=False):
"""
:param clustering_res_df: a pandas DataFrame about clustering result
:param cluster_number: the number of the cluster
(the first column is the index,
the second column is the right information,
the third column is the clusteri... | 5,337,713 |
def remove_old_now_linear_bend(atoms, intcos):
"""For given bend [A,B,C], remove any regular bends as well as any torsions
which contain it
"""
logger = logging.getLogger(__name__)
b = bend.Bend(atoms[0], atoms[1], atoms[2])
logger.info("Removing Old Linear Bend")
logger.info(str(b) + "\n")
... | 5,337,714 |
def odict_to_json(odict):
"""
Dump an OrderedDict into JSON series
"""
import json
json_series = json.dumps(odict)
return json_series | 5,337,715 |
def parenthesize(node: ast.AST, _nl_able: bool = False) -> str:
"""Wrap the un-parsed node in parentheses."""
return f"({unparse(node, True)})" | 5,337,716 |
def stack_nested_arrays(nested_arrays):
"""Stack/batch a list of nested numpy arrays.
Args:
nested_arrays: A list of nested numpy arrays of the same shape/structure.
Returns:
A nested array containing batched items, where each batched item is obtained
by stacking corresponding items from the list ... | 5,337,717 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Serial sensor platform."""
name = config.get(CONF_NAME)
port = config.get(CONF_SERIAL_PORT)
baudrate = config.get(CONF_BAUDRATE)
bytesize = config.get(CONF_BYTESIZE)
parity = config.get(CONF_PARI... | 5,337,718 |
def test_HollowSphereSelector():
"""
Test that the HollowSphereSelector selects the right number of entities
"""
sphere = (
cq.Workplane().sphere(5).polarArray(7, 30, 120, 2, rotate=True).box(1, 2, 1)
)
vertices = sphere.vertices(HollowSphereSelector((0, 0, 0), 7, 5.5, debug=True))
e... | 5,337,719 |
def temporal_statistics(da, stats):
"""
Obtain generic temporal statistics using the hdstats temporal library:
https://github.com/daleroberts/hdstats/blob/master/hdstats/ts.pyx
last modified June 2020
Parameters
----------
da : xarray.DataArray
DataArray should contain a 3... | 5,337,720 |
def encode_data(data):
"""
Helper that converts :class:`str` or :class:`bytes` to :class:`bytes`.
:class:`str` are encoded with UTF-8.
"""
# Expect str or bytes, return bytes.
if isinstance(data, str):
return data.encode('utf-8')
elif isinstance(data, bytes):
return data
... | 5,337,721 |
def get_apps_final(the_apps_dummy):
"""
计算出:
1.每个用户安装app的数量;
2.每个用户安装小众app的数量;
3.每个用户安装大众app的数量;
4.根据每个用户安装app的向量进行Mean-shift聚类的结果
"""
core_data = the_apps_dummy.drop(['id'], axis=1)
the_apps_final = get_minor_major(core_data, 'apps', 5, 90)
# new_core_data = col_cluster(core_d... | 5,337,722 |
def get_linked_events(user, dt, limit=None, load_also=()):
"""Get the linked events and the user's roles in them
:param user: A `User`
:param dt: Only include events taking place on/after that date
:param limit: Max number of events
"""
from indico.modules.events.abstracts.util import (get_even... | 5,337,723 |
def QA_SU_save_etf_min(client=DATABASE, ui_log=None, ui_progress=None):
"""save etf_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
__index_list = QA_fetch_get_stock_list('etf')
coll = client.index_min
coll.create_index(
[
('code',
... | 5,337,724 |
def test_hapd_ctrl_level(dev, apdev):
"""hostapd and LEVEL ctrl_iface command"""
ssid = "hapd-ctrl"
params = { "ssid": ssid }
hapd = hostapd.add_ap(apdev[0], params)
if "FAIL" not in hapd.request("LEVEL 0"):
raise Exception("Unexpected LEVEL success on non-monitor interface") | 5,337,725 |
def get_run_callback(run_text, output_dir):
"""
function to generate tf run callback for tensor board
"""
root_logdir = f'{output_dir.rstrip("/")}/tensorboard_logs/'
run_id = time.strftime(f'{run_text}_%Y_%m_%d-%H-%M-%S')
log_path = os.path.join(root_logdir, run_id)
tensorboad_callback = tf.... | 5,337,726 |
def set_seed(seed: int):
"""
Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch``.
Args:
seed (:obj:`int`): The seed to set.
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) | 5,337,727 |
def bert_keyword_expansion(keywords: str,
num_similar: int,
bert_model,
tokenizer,
bert_embedding_dict):
"""
Keyword expansion outputs top N most similar words from vocabulary.
@param keywords: stri... | 5,337,728 |
def utc_to_tt_offset(jday=None):
"""Returns the offset in seconds from a julian date in Terrestrial Time (TT)
to a Julian day in Coordinated Universal Time (UTC)"""
if use_numpy:
return utc_to_tt_offset_numpy(jday)
else:
return utc_to_tt_offset_math(jday) | 5,337,729 |
async def get_async_request(url: str) -> [int, Any]:
"""Get the data from the url provided.
Parameters
----------
url: str
url to get the data from
Returns
-------
[int, Any]
Tuple with the Response status code and the data returned from the request
"""
async with a... | 5,337,730 |
def scattering_probability(H, psi0, n_emissions, c_ops, tlist,
system_zero_state=None,
construct_effective_hamiltonian=True):
"""
Compute the integrated probability of scattering n photons in an arbitrary
system. This function accepts a nonlinearly space... | 5,337,731 |
def analytical_value_cond_i_shannon(distr, par):
""" Analytical value of the conditional Shannon mutual information.
Parameters
----------
distr : str-s
Names of the distributions; 'normal'.
par : dictionary
Parameters of the distribution. If distr is 'normal':
... | 5,337,732 |
def upload_file(localpath, s3path):
"""
Uploads a file to s3
:param localpath: The local path
:param s3path: The s3 path in format s3://mybucket/mydir/mysample.txt
"""
bucket, key = get_bucketname_key(s3path)
if key.endswith("/"):
key = "{}{}".format(key, os.path.basename(localpath))
... | 5,337,733 |
def convert_to_tub_v2(paths, output_path):
"""
Convert from old tubs to new one
:param paths: legacy tub paths
:param output_path: new tub output path
:return: None
"""
empty_record = {'__empty__': True}
if type(paths) is str:
paths = [pa... | 5,337,734 |
def approve(credentials, assignment_id):
"""Approve an assignment"""
# Connect to MTurk
mturk = connect(credentials['PRODUCTION'])
# Skip if already processed
assignment = mturk.get_assignment(AssignmentId=assignment_id)
if assignment['Assignment']['AssignmentStatus'] == 'Submitted':
# ... | 5,337,735 |
def print_cuda_memory(gpu: int = 0):
""" Prints current memory stats of gpu. """
t = torch.cuda.get_device_properties(gpu).total_memory
c = torch.cuda.memory_cached(gpu)
a = torch.cuda.memory_allocated(gpu)
print("GPU {}".format(gpu))
print("\tTotal memory: {}".format(t))
print("\tCached me... | 5,337,736 |
def zexp(input, i=None):
"""
Point-wise complex exponential.
:param input array:
:param i bool: imaginary
"""
usage_string = "zexp [-i] input output"
cmd_str = f'{BART_PATH} '
cmd_str += 'zexp '
flag_str = ''
opt_args = f''
multituples = []
if i is not None:
... | 5,337,737 |
def ekin2wl(ekin):
"""Convert neutron kinetic energy in electronvolt to wavelength in Angstrom"""
if _np and hasattr(ekin,'__len__'):
#reciprocals without zero division:
ekinnonzero = ekin != 0.0
ekininv = 1.0 / _np.where( ekinnonzero, ekin, 1.0)#fallback 1.0 wont be used
return ... | 5,337,738 |
def add_jinja2_extension(config, ext, name='.jinja2'):
"""
This function is added as a method of a :term:`Configurator`, and
should not be called directly. Instead it should be called like so after
``pyramid_jinja2`` has been passed to ``config.include``:
.. code-block:: python
config.add_... | 5,337,739 |
def show_subscription(conn, customer):
"""
Retrieves authenticated user's plan and prints it.
- Return type is a tuple, 1st element is a boolean and 2nd element is the response message from messages.py.
- If the operation is successful; print the authenticated customer's plan and return ... | 5,337,740 |
def check_atoms_coordinates(mol):
"""
Function to check if a molecule contains zero coordinates in all atoms.
Then this molecule must be eliminated.
Returns True if molecules is OK and False if molecule contains zero coordinates.
Example:
# Load test set to a frame
... | 5,337,741 |
def update_hosts_file(*flags):
"""
Wrapper around running updateHostsFile.py
Parameters
----------
flags : varargs
Commandline flags to pass into updateHostsFile.py. For more info, run
the following command in the terminal or command prompt:
```
python updateHostsFi... | 5,337,742 |
def maybe_gen_fake_data_based_on_real_data(
image, label, reso, min_fake_lesion_ratio, gen_fake_probability):
"""Remove real lesion and synthesize lesion."""
# TODO(lehou): Replace magic numbers with flag variables.
gen_prob_indicator = tf.random_uniform(
shape=[], minval=0.0, maxval=1.0, dtype=tf.float... | 5,337,743 |
def is_primitive_type (v) :
""" Check to see if v is primitive. Primitive in this context
means NOT a container type (str is the exception):
primitives type are: int, float, long, complex, bool, None, str
"""
return type(v) in {int:0, float:0, long:0, complex:0, bool:0, None:0, str:0} | 5,337,744 |
def _get_bit(h, i):
"""Return specified bit from string for subsequent testing"""
h1 = int.from_bytes(h, 'little')
return (h1 >> i) & 0x01 | 5,337,745 |
def go_down_right_reward(nobs, high_pos, agent_num, act):
"""
Return a reward for going to the low or right side of the board
:param nobs: The current observation
:param high_pos: Tuple of lowest and most-right position
:param agent_num: The id of the agent to check (0-3)
:return: The ... | 5,337,746 |
def getChannelBoxMenu():
"""
Get ChannelBox Menu, convert the main channel box to QT and return the
Edit QMenu which is part of the channel box' children.
:return: Maya's main channel box menu
:rtype: QMenu
"""
channelBox = getChannelBox()
# find widget
menus = channelBox.... | 5,337,747 |
def make_sid_cookie(sid, uri):
"""Given a sid (from a set-cookie) figure out how to send it back"""
# sometime near 0.92, port got dropped...
# uritype, uribody = urllib.splittype(uri)
# host, path = urllib.splithost(uribody)
# host, port = urllib.splitnport(host)
# if port == -1:
# port... | 5,337,748 |
def identity_filter(element_tuple):
"""
element_tuple est consitute des (name, attrs) de chaque element XML recupere par la methode startElement
"""
return element_tuple | 5,337,749 |
def EoZ(N2, w0, f, ):
"""
Wave ray energy when variations can only occur in the vertical (i.e. N2 and
flow only vary with depth not horizontally) - Olbers 1981
"""
Ez = np.squeeze((w0**2 * (N2 - f**2))
/ ((w0**2 - f**2)**(3 / 2) * (N2 - w0**2)**(1 / 2)))
return Ez | 5,337,750 |
def safe_string(value: Any) -> str:
"""
Consistently converts a value to a string.
:param value: The value to stringify.
"""
if isinstance(value, bytes):
return value.decode()
return str(value) | 5,337,751 |
def test_example_4p2():
"""Test example 4.2 in Pozar."""
# X-band waveguide dimensions
a = 2.285 * sc.centi
b = 1.016 * sc.centi
# Rexolite
er_mag = 2.54
# Frequency
f = 10 * sc.giga
# Propagation constants
beta_a = wg.phase_constant(f, a, b, er=1)
beta_d =... | 5,337,752 |
def handle_older_version(upstream_version: Box) -> bool:
"""
Checks if the current version (local) is older than the upstream one
and provides a message to the end-user.
:return:
:py:class:`True` if local is older. :py:class:`False` otherwise.
"""
version_utility = VersionUtility(PyFun... | 5,337,753 |
def silent_unlink(path):
"""like os.unlink but does not raise error if the file does not exist"""
try:
os.unlink(path)
except OSError, e:
if e.errno != errno.ENOENT:
raise | 5,337,754 |
def tp(selector:Union[str, tuple]="@s", selector2:Union[str, tuple]=("~", "~", "~")):
"""
selector:Union[str, tuple] -> The position to be moved from
selector2:Union[str, tuple] -> The position to be moved to
"""
if not ((isinstance(selector, str) or isinstance(selector, tuple)) and (isinstance(sel... | 5,337,755 |
def new_product() -> Product:
"""Generates an instance of Product with default values."""
return Product(
product_id='',
desc='',
display_name='',
capacity=0,
image='') | 5,337,756 |
def _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype, algorithm):
"""Calls RBG in a loop and stacks the results."""
key, = batched_args
bd, = batch_dims
if bd is batching.not_mapped:
return lax.rng_bit_generator_p.bind(key, shape=shape, dtype=dtype,
... | 5,337,757 |
def count_short_tail_keywords(keywords: List[str]) -> int:
"""
Returns the count of short tail keywords in a list of keywords.
Parameters:
keywords (List[str]): list with all keywords as strings.
Returns:
total (int): count of short tail keywords (1 o 2 words per keyword)... | 5,337,758 |
def test_assets_are_known(mock_bitfinex):
"""This tests only exchange (trades) assets (not margin, nor futures ones).
"""
unsupported_assets = set(UNSUPPORTED_BITFINEX_ASSETS)
common_items = unsupported_assets.intersection(set(WORLD_TO_BITFINEX.values()))
assert not common_items, f'Bitfinex assets {... | 5,337,759 |
def is_odd(number):
"""Determine if a number is odd."""
if number % 2 == 0:
return False
else:
return True | 5,337,760 |
def test_service_account_token_create_out_of_scope_service_account(
permission_manage_service_accounts,
staff_api_client,
superuser_api_client,
staff_user,
permission_manage_orders,
):
"""Ensure user can't create token for service account with wider
scope of permissions.
Ensure superuse... | 5,337,761 |
def fmt_quil_str(raw_str):
"""Format a raw Quil program string
Args:
raw_str (str): Quil program typed in by user.
Returns:
str: The Quil program with leading/trailing whitespace trimmed.
"""
raw_quil_str = str(raw_str)
raw_quil_str_arr = raw_quil_str.split('\n')
trimmed_qu... | 5,337,762 |
def get_source_plate_uuid(barcode: str) -> Optional[str]:
"""Attempt to get a UUID for a source plate barcode.
Arguments:
barcode {str} -- The source plate barcode.
Returns:
{str} -- The source plate UUID; otherwise None if it cannot be determined.
"""
try:
source_plates_co... | 5,337,763 |
def find_largest_digit(n):
"""
:param n: integers
:return: the largest digit
"""
n = abs(n) # absolute the value
if n < 10:
return n
else:
return find_helper(n, 0) | 5,337,764 |
def test_deny_this_without_attribute_access(code):
"""`this` object can't be used as a dependency directly."""
class Foo:
pass
with pytest.raises(DependencyError) as exc_info:
code(Foo)
message = str(exc_info.value)
assert message == "You can not use 'this' directly in the 'Inject... | 5,337,765 |
def print_to_file(fname: Union[str, Path], fn: Callable, args=None, kwargs=None):
""" All `print` function calls in `fn(*args, **kwargs)`
uses a text file `fname`.
:param fname:
:param fn:
:param args: args for fn
:param kwargs: kwargs for fn
:return:
"""
if fname:
... | 5,337,766 |
def extractChrononTranslations(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
item['title'] = item['title'].replace('’', '')
if 'Weapons cheat'.lower() in item['title'].lower():
return bui... | 5,337,767 |
def run_feature_selection(X, y, select_k_features):
"""Use a gradient boosting tree regressor as a proxy for finding
the k most important features in X, returning indices for those
features as output."""
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import Select... | 5,337,768 |
def add_path_to_syspath() -> None:
"""
>>> add_path_to_syspath()
"""
path_to_append = pathlib.Path(__file__).resolve().parent
sys_paths_resolved = [pathlib.Path(path).resolve() for path in sys.path]
if path_to_append not in sys_paths_resolved:
sys.path.append(str(path_to_append)) | 5,337,769 |
def _not_json_encodable(message: str, failure_callback: Optional[Callable[[str], None]]) -> Literal[False]:
""" Utility message to fail (return `False`) by first calling an optional failure callback. """
if failure_callback:
failure_callback(message)
return False | 5,337,770 |
def requires(*commands: str) -> RequiresT:
"""Decorator to require the given commands."""
def inner(func: ReturnT) -> ReturnT:
"""Decorates the function and checks for the commands."""
for command in commands:
if not check_availability(command):
raise errors.MissingS... | 5,337,771 |
def _build_model(input_dim, num_classes, num_hidden_layers=0,
hidden_dimension=128,
normalize_inputs=False, dropout=0):
"""
Macro to generate a Keras classification model
"""
inpt = tf.keras.layers.Input((input_dim))
net = inpt
# if we're normalizing input... | 5,337,772 |
def get_client(
project_id, cloud_region, registry_id, device_id, private_key_file,
algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port):
"""Create our MQTT client. The client_id is a unique string that identifies
this device. For Google Cloud IoT Core, it must be in the format below."""... | 5,337,773 |
def fake_image_sct_custom(data):
"""
:return: an Image (3D) in RAS+ (aka SCT LPI) space
"""
i = fake_image_custom(data)
img = msct_image.Image(i.get_data(), hdr=i.header,
orientation="LPI",
dim=i.header.get_data_shape(),
)
return img | 5,337,774 |
def copy_sensor_image(input_sensor_file, output_sensor_file,
raft_slot, sensor_slot, **kwargs):
"""
Copies a FITS file, with hooks to update the various image headers
Parameters
----------
input_sensor_file : str
Name of the file to be copied
output_sensor_file : s... | 5,337,775 |
def test_version():
"""Test version number of released package."""
assert __version__ == "0.2.0" | 5,337,776 |
def _get_property_header(resource, resource_type):
"""
Create a dictionary representing resources properties
:param resource: The name of the resource for which to create a
property header
:param resource_type: The type of the resource (model, seed, etc.)
:return: A dictionary representing ... | 5,337,777 |
def create_metapaths_parameters(filename, folder):
""" creates a parameters file from the default """
default_filename = folder + PATHDELIM + 'resources'+ PATHDELIM + "template_param.txt"
try:
filep = open(default_filename, 'r')
except:
eprintf("ERROR: cannot open the default parameter ... | 5,337,778 |
def test_series() -> None:
"""Tests for :meth:`NDRepr.repr_Series`."""
s1 = pd.Series(np.ones(10, dtype='float64'))
s2 = pd.Series(np.ones(10, dtype='int64'))
ref1 = '0 1.0\n1 1.0\n2 1.0\n3 1.0\n4 1.0\n5 1.0\n6 1.0\n7 1.0\n8 1.0\n9 1.0\ndtype: float64' # noqa: E501
re... | 5,337,779 |
def deploy(args: argparse.Namespace) -> None:
"""
Handler for `lambada deploy`, which creates an AWS Lambda from a Simiotics function
Args:
args
`argparse.Namespace` object containing parameters to the `deploy` command
Returns: None, prints AWS Lambda ARN
"""
simiotics = client_fro... | 5,337,780 |
def dist_prune(DELTA, prune=True):
""" transform similarity matrix to distance matrix
- prune matrix by removing edges that have a distance larger
than condition cond (default mean distance)
"""
w = np.max(DELTA)
DELTA = np.abs(DELTA - w)
np.fill_diagonal(DELTA, 0.)
if prune:
... | 5,337,781 |
def bitwise_dot(x, y):
"""Compute the dot product of two integers bitwise."""
def bit_parity(i):
n = bin(i).count("1")
return int(n % 2)
return bit_parity(x & y) | 5,337,782 |
def check_limit():
"""
Empty function for enabling global rate limiting.
"""
return | 5,337,783 |
def fit (samples, degree, sample_weights=None):
"""
Fit a univariate polynomial function to the 2d points given in samples, where the rows of
samples are the points. The return value is the vector of coefficients of the polynomial
(see p below) which minimizes the squared error of the polynomial at the... | 5,337,784 |
def section_underline_overindented_and_contentless(): # noqa: D416
"""Toggle the gizmo.
Returns
-------
""" | 5,337,785 |
def get_engines():
""" Returns a list of all engines for tests """
engines = []
base_dir = os.getcwd()
engines_dir = os.path.join(base_dir, 'search_engine_parser', 'core', 'engines')
for filename in os.listdir(engines_dir):
if os.path.isfile(os.path.join(engines_dir, filename)) and filenam... | 5,337,786 |
def IsEncryptedCoredump(path):
""" Function to find if the coredump is encrypted or not. """
if not os.path.exists('/bin/vmkdump_extract'):
raise Exception('vmkdump_extract not present.')
result, rc = RunCmd("/bin/vmkdump_extract -E {0}".format(path))
if rc != 0:
raise Exception(
... | 5,337,787 |
def test_ap_ht40_5ghz_match(dev, apdev):
"""HT40 co-ex scan on 5 GHz with matching pri/sec channel"""
clear_scan_cache(apdev[0]['ifname'])
try:
hapd = None
hapd2 = None
params = { "ssid": "test-ht40",
"hw_mode": "a",
"channel": "36",
... | 5,337,788 |
def get_ahead_mask(tokens, i_pad=0):
"""
ahead mask 계산하는 함수
:param tokens: tokens (bs, n_seq)
:param i_pad: id of pad
:return mask: ahead and pad mask (ahead or pad: 1, other: 0)
"""
n_seq = tf.shape(tokens)[1]
ahead_mask = 1 - tf.linalg.band_part(tf.ones((n_seq, n_seq)), -1, 0)
ahea... | 5,337,789 |
def check_containment(row, query_index, reference_index, percent_identity=PERCENT_IDENTITY, covered_length=COVERED_LENGTH):
"""Checks if a row from a blast out format 6 file is a containment
Takes in a row from a blast out format 6 table, a DataFrames with query sequence and reference sequence data.
"""
... | 5,337,790 |
def get_mgga_data(mol, grid, rdm1):
"""
Get atomic orbital and density data.
See eval_ao and eval_rho docs for details.
Briefly, returns 0-3 derivatives of the atomic orbitals
in ao_data;
and the density, first derivatives of density,
Laplacian of density, and kinetic energy density
in r... | 5,337,791 |
def bgp_prefix_tc1_remove(duthost, community):
""" Test to remove prefix config
"""
json_patch = [
{
"op": "remove",
"path": "/BGP_ALLOWED_PREFIXES"
}
]
tmpfile = generate_tmpfile(duthost)
logger.info("tmpfile {}".format(tmpfile))
try:
output... | 5,337,792 |
def _stringify_lmer_warnings(fg_lmer):
"""create grid w/ _ separated string of lme4::lmer warning list items, else "" """
warning_grids = fitgrid.utils.lmer.get_lmer_warnings(
fg_lmer
) # dict of indicator dataframes
warning_string_grid = pd.DataFrame(
np.full(fg_lmer._grid.shape, ""),... | 5,337,793 |
def test_rm_token_cache(
httpx_mock: HTTPXMock,
check_token_callback: Callable,
check_credentials_callback: Callable,
settings: Settings,
auth_url: str,
account_id_url: str,
account_id_callback: Callable,
provider_callback: Callable,
provider_url: str,
access_token: str,
) -> Non... | 5,337,794 |
def index():
"""Loads the index page for the 'Admin' controller
:returns: a dictionary to pass to the view with the list of ctr_enabled and the active module ('admin')
"""
ctr_data = get_ctr_data()
users = db().select(db.auth_user.ALL)
approvals = db(db.auth_user.registration_key=='pending').select(db.auth_user.... | 5,337,795 |
def get_language_codes():
"""Returns a list of available languages and their 2 char input codes
"""
languages = get_languages()
two_dig_codes = [k for k, v in languages.items()]
return two_dig_codes | 5,337,796 |
def fun_evaluate_ndcg(user_test_recom_zero_one):
"""
计算ndcg。所得是单个用户test的,最后所有用户的求和取平均
:param test_lst: 单个用户的test集
:param zero_one: 0/1序列
:param test_mask: 单个用户的test列表对应的mask列表
:return:
"""
test_lst, zero_one, test_mask, _ = user_test_recom_zero_one
test_lst = test_lst[:np.sum(test_ma... | 5,337,797 |
def prettyDataSize(size_in_bytes):
""" Takes a data size in bytes and formats a pretty string. """
unit = "B"
size_in_bytes = float(size_in_bytes)
if size_in_bytes > 1024:
size_in_bytes /= 1024
unit = "kiB"
if size_in_bytes > 1024:
size_in_bytes /= 1024
unit = "MiB"
... | 5,337,798 |
def test_projectlocale_latest_activity_success(translation_a):
"""
If the matching ProjectLocale has a latest_translation, return
it's latest_activity.
"""
project = translation_a.entity.resource.project
locale = translation_a.locale
assert ProjectLocale.get_latest_activity(project, locale)
... | 5,337,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.