content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def decrypt(private, ciphertext, output):
"""Decrypt ciphertext with private key.
Requires PRIVATE key file and the CIPHERTEXT encrypted with
the corresponding public key.
"""
privatekeydata = json.load(private)
assert 'pub' in privatekeydata
pub = load_public_key(privatekeydata['pub'])
... | 24,000 |
def nearest(a, num):
"""
Finds the array's nearest value to a given num.
Args:
a (ndarray): An array.
num (float): The value to find the nearest to.
Returns:
float. The normalized array.
"""
a = np.array(a, dtype=float)
return a.flat[np.abs(a - num).argmin()] | 24,001 |
def hex_string(data):
"""Return a hex dump of a string as a string.
The output produced is in the standard 16 characters per line hex +
ascii format:
00000000: 40 00 00 00 00 00 00 00 40 00 00 00 01 00 04 80 @....... @.......
00000010: 01 01 00 00 00 00 00 01 00 00 00 00 ........ .... | 24,002 |
def team_2_adv():
"""
Google Doc: https://docs.google.com/document/d/19jYjDRX_WR4pPynsAYmeglDpQWDvNVMDgYvd4EUWqm8/edit?usp=sharing
Goes through the berea section of the story. Asks if you want to go to dining or go do homework.
Choosing either will take you to two possibilities of being "dead" or being ... | 24,003 |
def load_codes_mat(backup_dir, savefile=False, thread_num=1):
""" load all the code mat file in the experiment folder and summarize it into nparrays"""
if "codes_all.npz" in os.listdir(backup_dir):
# if the summary table exist, just read from it!
with np.load(os.path.join(backup_dir, "codes_all.... | 24,004 |
def extract_ego_time_point(history: SimulationHistory) -> npt.NDArray[int]:
"""
Extract time point in simulation history.
:param history: Simulation history.
:return An array of time in micro seconds.
"""
time_point = np.array(
[sample.ego_state.time_point.time_us for sample in history.... | 24,005 |
def compare_data_identifiers(a, b):
"""Checks if all the identifiers match, besides those that are not in both lists"""
a = {tuple(key): value for key, value in a}
b = {tuple(key): value for key, value in b}
matching_keys = a.keys() & b.keys()
a = {k: v for k, v in a.items() if k in matching_keys}
... | 24,006 |
def expand_abbr(abbr, doc_type = 'html'):
"""
Разворачивает аббревиатуру
@param abbr: Аббревиатура
@type abbr: str
@return: str
"""
tree = parse_into_tree(abbr, doc_type)
if tree:
result = tree.to_string(True)
if result:
result = re.sub('\|', insertion_point, result, 1)
return re.sub('\|', sub_inserti... | 24,007 |
def SaveSettings (event=None, SettingsNotebook=None, filename = "settings.hdf5", title="Open HDF5 file to save settings", OpenDialog=True ) :
"""
Method for saving setting
"""
if OpenDialog :
# Ask user to select the file
openFileDialog = wx.FileDialog(SettingsNotebook, title, "", filename, "HDF5 files (*.hdf5... | 24,008 |
def primes_above(x):
"""Convenience function that yields primes strictly greater than x.
>>> next(primes_above(200))
211
"""
_validate_num(x)
it = primes()
# Consume the primes below x as fast as possible, then yield the rest.
p = next(it)
while p <= x:
p = next(it)
yie... | 24,009 |
def getAfinityCenter(width, height, point, center, radius=7, img_affinity=None):
"""
Function to create the affinity maps,
e.g., vector maps pointing toward the object center.
Args:
width: image wight
height: image height
point: (x,y)
center: (x,y)
radius: pix... | 24,010 |
def win_array_to_buf_32(data_array, memhandle, first_point, count):
"""Copies 32-bit data from an array into a Windows memory buffer.
Parameters
----------
data_array : POINTER(c_ushort)
The C array containing the data to be copied
memhandle : int
This must be a memory handle that w... | 24,011 |
def test_add_pass_existing():
"""Add to existing set."""
context = Context({
'arbset': {1, 2},
'add': {
'set': 'arbset',
'addMe': 3
}})
add.run_step(context)
context['add']['addMe'] = 4
add.run_step(context)
assert context['arbset'] == {1, 2, 3... | 24,012 |
def unwrap_phase_iterative_fft(mat, iteration=4, win_for=None, win_back=None,
weight_map=None):
"""
Unwrap a phase image using an iterative FFT-based method as described in
Ref. [1].
Parameters
----------
mat : array_like
2D array. Wrapped phase-image in t... | 24,013 |
def wallunderground(idf, bsdobject, deletebsd=True, setto000=False):
"""return a wall:underground if bsdobject (buildingsurface:detailed) is an
underground wall"""
# ('WALL:UNDERGROUND', Wall, s.startswith('Ground'))
# test if it is an underground wall
if bsdobject.Surface_Type.upper() == 'WALL': #... | 24,014 |
def loadBar(self, days, symbol='', exchange=''):
"""载入1分钟K线"""
symbol = self.vtSymbol if symbol == '' else symbol
exchange = self.exchange if exchange == '' else exchange
url = 'http://122.144.129.233:60007/hismin?instrumentid={}&datatype=0&exchangeid={}&startday={}&secretkey=1&daynum={}&rtnnum=20'.form... | 24,015 |
def canonical_order(match):
"""
It does not make sense to define a separate bond between atoms 1 and 2,
and between atoms 2 and 1. This function will swap the atoms in the bond
if the first atom > second atom.
"""
# match[0][0:2] contains the ID numbers for the 2 atoms in the match
atom0 =... | 24,016 |
def grant_db_access_to_role(role, db): # pylint: disable=invalid-name
"""Grant the role 'database_name', returns grant permission."""
return grant_obj_permission_to_role(role, db, 'database_access') | 24,017 |
def execute_compute_job():
"""Call the execution of a workflow.
---
tags:
- services
consumes:
- application/json
parameters:
- name: consumerAddress
in: query
description: The consumer address.
required: true
type: string
- name: serviceAgree... | 24,018 |
def files_filter_ext(files: List[Path], ext: str) -> List[Path]:
"""Filter files from a list matching a extension.
Args:
files: List of files.
ext: Extension to filter.
Returns:
List of files that have the extension.
"""
return [f for f in files if f.suffix == ext] | 24,019 |
def update(locale_dir, pot_dir, languages, line_width=76):
"""
Update specified language's po files from pot.
:param unicode locale_dir: path for locale directory
:param unicode pot_dir: path for pot directory
:param tuple languages: languages to update po files
:param number line_width: maximu... | 24,020 |
def interp_to_grid(tran,v,expand_x=True,expand_y=True):
"""
Return dense matrix for X,Y and V (from v, or tran[v] if v is str)
expand_x: defaults to 1 more value in the X dimension than in V, suitable for
passing to pcolormesh.
expand_y: defaults to 1 more value in the Y dimension than in V, for pco... | 24,021 |
def simulation(G, tau, gamma, rho, max_time, number_infected_before_release, release_number, background_inmate_turnover,
stop_inflow_at_intervention, p, death_rate, percent_infected, percent_recovered, social_distance,
social_distance_tau, initial_infected_list):
"""Runs a simulation o... | 24,022 |
def relative(link : str):
"""Convert relative link to absolute"""
return f"#{document.URL.split('#')[1]}/{link}" | 24,023 |
def pypiserver_cmd(root, cmd='run', *args):
"""Yield a command to run pypiserver.
:param Union[str, pathlib.Path] root: the package root from which
to serve packages.
:param args: extra arguments for ``pypiserver <cmd>``
:returns: arguments suitable for passing to ``Popen()``
:rtype: Itera... | 24,024 |
def test_normalized_frequency_outliers_for_multi_columns(agencies):
"""Test frequency outlier detection using normalized frequencies for tuples
of values from multiple columns.
"""
# Use default divide by total as the normalization function. The pair
# ('BK', 'NY') occurs in 6 out of ten rows in the... | 24,025 |
def _get_axes_names(ndim: int) -> Tuple[List[str], List[str]]:
"""Get needed axes names given the number of dimensions.
Parameters
----------
ndim : int
Number of dimensions.
Returns
-------
axes : List[str]
Axes names.
coords : List[str]
Coordinates names.
... | 24,026 |
def multi_replace(text, replace_dict):
"""Perform multiple replacements in one go using the replace dictionary
in format: { 'search' : 'replace' }
:param text: Text to replace
:type text: `str`
:param replace_dict: The replacement strings in a dict
:type replace_dict: `dict`
:return: `str`
... | 24,027 |
def function_expr(fn: str, args_expr: str = "") -> str:
"""
DEPRECATED. Please do not add anything else here. In order to manipulate the
query, create a QueryProcessor and register it into your dataset.
Generate an expression for a given function name and an already-evaluated
args expression. This ... | 24,028 |
def node_delete(node):
"""Delete node.
If the node does not exist, a NotFoundError will be raised.
"""
get_auth_backend().require_admin()
node = get_or_404(model.Node, node)
if node.project:
raise errors.BlockedError(
"Node %r is part of project %r; remove from "
... | 24,029 |
def entry_point(action_name: str):
"""Entry point for execute an action"""
__logger.info('Launch action <%s>...', action_name)
action_inst = utils.collection.list.pnext(__actions, lambda a: a.name == action_name)
if action_inst:
action_inst.entry_point(args)
else:
raise Exception('Un... | 24,030 |
def many_to_one(nrows=[1000], N=5, percentages=[0.025], p=0.5):
"""
"""
def update_joinable_relation_rows(table1, nrows, selecivity_percentage, \
N, relation_from_percentage=-1, \
relation_to_percentage=-1):
"""
Sa... | 24,031 |
def distribute(tensor: np.ndarray,
grid_shape: Sequence[int],
pmap: bool = True) -> pxla.ShardedDeviceArray:
"""
Convert a numpy array into a ShardedDeviceArray (distributed according to
`grid_shape`). It is assumed that the dimensions of `tensor`
are evenly divided by `grid`.
A... | 24,032 |
def input_files_exist(paths):
"""Ensure all the input files actually exist.
Args:
paths (list): List of paths.
Returns:
bool: True if they all exist, False otherwise.
"""
for path in paths:
if not os.path.isfile(path):
return False
return True | 24,033 |
def predict(w, X):
"""
Returns a vector of predictions.
"""
return expit(X.dot(w)) | 24,034 |
def get_argument_parser():
"""
Parse CLI arguments and return a map of options.
"""
parser = argparse.ArgumentParser(
description="DC/OS Install and Configuration Utility")
mutual_exc = parser.add_mutually_exclusive_group()
mutual_exc.add_argument(
'--hash-password',
act... | 24,035 |
def run_report_results(args, probe, dataset, model, loss, reporter, regimen):
"""
Reports results from a structural probe according to args.
By default, does so only for dev set.
Requires a simple code change to run on the test set.
"""
probe_params_path = os.path.join(args['reporting']['root'],args['probe'... | 24,036 |
def move_wm_id_to_d(wm_id, d_num):
"""
Given a wmctrl window manager ID `wm_id`, move the corresponding window to the
desktop number `d_num`, by calling `wmctrl -i -r WM_ID -t D_NUM`.
N.B. wmctrl does not give an informative error code so no way to check it succeeded
without querying wmctrl ag... | 24,037 |
def test_eval_policy(config, tmpdir):
"""Smoke test for imitation.scripts.eval_policy"""
config_updates = {
'render': False,
'log_root': tmpdir,
}
config_updates.update(config)
run = eval_policy_ex.run(config_updates=config_updates,
named_configs=['fast'])
assert run.s... | 24,038 |
def maskrgb_to_class(mask, class_map):
""" decode rgb mask to classes using class map"""
h, w, channels = mask.shape[0], mask.shape[1], mask.shape[2]
mask_out = -1 * np.ones((h, w), dtype=int)
for k in class_map:
matches = np.zeros((h, w, channels), dtype=bool)
for c in range(channels)... | 24,039 |
def translate_error_code(error_code):
"""
Return the related Cloud error code for a given device error code
"""
return (CLOUD_ERROR_CODES.get(error_code) if error_code in
CLOUD_ERROR_CODES else error_code) | 24,040 |
def download(local_dir, project_name):
""" Copy from S3 to local directory
"""
print | 24,041 |
def generate_oi_quads():
"""Return a list of quads representing a single OI, OLDInstance.
"""
old_instance, err = domain.construct_old_instance(
slug='oka',
name='Okanagan OLD',
url='http://127.0.0.1:5679/oka',
leader='',
state=domain.NOT_SYNCED_STATE,
is_auto... | 24,042 |
def graph_intersection(pred_graph, truth_graph):
"""
Use sparse representation to compare the predicted graph
and the truth graph so as to label the edges in the predicted graph
to be 1 as true and 0 as false.
"""
array_size = max(pred_graph.max().item(), truth_graph.max().item()) + 1
l1 = ... | 24,043 |
def get_qid_for_title(title):
"""
Gets the best Wikidata candidate from the title of the paper.
"""
api_call = f"https://www.wikidata.org/w/api.php?action=wbsearchentities&search={title}&language=en&format=json"
api_result = requests.get(api_call).json()
if api_result["success"] == 1:
r... | 24,044 |
def experiment(L, T, dL, dT, dLsystm = 0):
"""
Performs a g-measurement experiment
Args:
L: A vector of length measurements of the pendulum
T: A vector of period measurements of the pendulum
dL: The error in length measurement
dT: The error in period measurement
... | 24,045 |
def find_jobs(schedd=None, attr_list=None, **constraints):
"""Query the condor queue for jobs matching the constraints
Parameters
----------
schedd : `htcondor.Schedd`, optional
open scheduler connection
attr_list : `list` of `str`
list of attributes to return for each job, default... | 24,046 |
def create_vocab(sequences, min_count, counts):
"""Generate character-to-idx mapping from list of sequences."""
vocab = {const.SOS: const.SOS_IDX, const.EOS: const.EOS_IDX,
const.SEP: const.SEP_IDX}
for seq in sequences:
for token in seq:
for char in token:
i... | 24,047 |
def get_ind_sphere(mesh, ind_active, origin, radius):
"""Retreives the indices of a sphere object coordintes in a mesh."""
return (
(mesh.gridCC[ind_active, 0] <= origin[0] + radius)
& (mesh.gridCC[ind_active, 0] >= origin[0] - radius)
& (mesh.gridCC[ind_active, 1] <= origin... | 24,048 |
def find_frame_times(eegFile, signal_idx=-1, min_interval=40, every_n=1):
"""Find imaging frame times in LFP data using the pockels blanking signal.
Due to inconsistencies in the fame signal, we look for local maxima. This
avoids an arbitrary threshold that misses small spikes or includes two
nearby tim... | 24,049 |
def _interpolate_signals(signals, sampling_times, verbose=False):
"""
Interpolate signals at given sampling times.
"""
# Reshape all signals to one-dimensional array object (e.g. AnalogSignal)
for i, signal in enumerate(signals):
if signal.ndim == 2:
signals[i] = signal.flatten()... | 24,050 |
def mean_standard_error_residuals(A, b):
"""
Mean squared error of the residuals. The sum of squared residuals
divided by the residual degrees of freedom.
"""
n, k = A.shape
ssr = sum_of_squared_residuals(A, b)
return ssr / (n - k) | 24,051 |
def cel2gal(ra, dec):
"""
Convert celestial coordinates (J2000) to Galactic
coordinates. (Much faster than astropy for small arrays.)
Parameters
----------
ra : `numpy.array`
dec : `numpy.array`
Celestical Coordinates (in degrees)
Returns
-------
glon : `numpy.array`
... | 24,052 |
def index(request):
"""Renders main website with welcome message"""
return render(request, 'mapper/welcome.html', {}) | 24,053 |
def tidy_output(differences):
"""Format the output given by other functions properly."""
out = []
if differences:
out.append("--ACLS--")
out.append("User Path Port Protocol")
for item in differences:
#if item[2] != None: #En algunos casos salían procesos con puerto None
out.append("%s %s %... | 24,054 |
def get_issues_overview_for(db_user: User, app_url: str) -> Dict[str, Collection]:
"""
Returns dictionary with keywords 'user' and 'others', which got lists with dicts with infos
IMPORTANT: URL's are generated for the frontend!
:param db_user: User
:param app_url: current applications url
:retu... | 24,055 |
def load_file(file):
"""Returns an AdblockRules object using the rules specified in file."""
with open(file) as f:
rules = f.readlines()
return AdblockRules(rules) | 24,056 |
def isSV0_QSO(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,
gsnr=None, rsnr=None, zsnr=None, w1snr=None, w2snr=None,
dchisq=None, maskbits=None, objtype=None, primary=None):
"""Target Definition of an SV0-like QSO. Returns a boolean array.
Parameters
----------
... | 24,057 |
def show_df_nans(df, columns=None, plot_width=10, plot_height=8):
"""
Input: df (pandas dataframe), collist (list)
Output: seaborn heatmap plot
Description: Create a data frame for features which may be nan. Set NaN values be 1 and
numeric values to 0. Plots a heat map where dark squar... | 24,058 |
def nocheck():
"""Test client for an app that ignores the IP and signature."""
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['VALIDATE_IP'] = False
app.config['VALIDATE_SIGNATURE'] = False
return app.test_client() | 24,059 |
def evaluate_accuracy(file1, file2):
"""
evaluate accuracy
"""
count = 0
same_count = 0
f1 = open(file1, 'r')
f2 = open(file2, 'r')
while 1:
line1 = f1.readline().strip('\n')
line2 = f2.readline().strip('\n')
if (not line1) or (not line2):
break
... | 24,060 |
def append_binified_csvs(old_binified_rows: DefaultDict[tuple, list],
new_binified_rows: DefaultDict[tuple, list],
file_for_processing: FileToProcess):
""" Appends binified rows to an existing binified row data structure.
Should be in-place. """
for dat... | 24,061 |
def find_files(top, exts):
"""Return a list of file paths with one of the given extensions.
Args:
top (str): The top level directory to search in.
exts (tuple): a tuple of extensions to search for.
Returns:
a list of matching file paths.
"""
return [os.path.join(dirpath, nam... | 24,062 |
def add_hp_label(merged_annotations_column, label_type):
"""Adds prefix to annotation labels that identify the annotation as
belonging to the provided label_type (e.g. 'h@' for host proteins).
Parameters
----------
merged_annotations_column : array-like (pandas Series))
An array containing ... | 24,063 |
def decal_component_test():
"""
Basic test for the Decal(Atom) component attached to an entity.
"""
# Create child entity 'decal_1' under Default entity and add decal component to it
component_name = "Decal (Atom)"
search_filter = azlmbr.entity.SearchFilter()
search_filter.names = ['default_... | 24,064 |
def JsonObj(data):
""" Returns json object from data
"""
try:
if sys.version >= '3.0':
return json.loads(str(data))
else:
return compat_json(json.loads(str(data), object_hook=compat_json),
ignore_dicts=True)
except Exception as e: #... | 24,065 |
def _serialize_value(
target_expr: str, value_expr: str, a_type: mapry.Type,
auto_id: mapry.py.generate.AutoID, py: mapry.Py) -> str:
"""
Generate the code to serialize a value.
The code serializes the ``value_expr`` into the ``target_expr``.
:param target_expr: Python expression of th... | 24,066 |
def return_union_close():
"""union of statements, close statement"""
return " return __result" | 24,067 |
def parse_unchanged(value: Union[str, List[str]]) -> Tuple[bool, Union[str, List[str]]]:
"""Determine if a value is 'unchanged'.
Args:
value: value supplied by user
"""
unchanges = [
SETTING_UNCHANGED,
str(SETTING_UNCHANGED),
SETTING_UNCHANGED[0],
str(SETTING_UNC... | 24,068 |
def get_val(tup):
"""Get the value from an index-value pair"""
return tup[1] | 24,069 |
def get_slurm_job_nodes():
"""Query the SLURM job environment for the number of nodes"""
nodes = os.environ.get('SLURM_JOB_NUM_NODES')
if nodes is None:
nodes = os.environ.get('SLURM_NNODES')
if nodes:
return int(nodes)
print("Warning: could not determine the number of nodes in this ... | 24,070 |
def log(level: str, *messages: str) -> None:
"""Log a message to ``qualichat`` logger.
Parameters
----------
level: :class:`str`
The logger level to send.
*args: :class:`str`
The log messages to send.
"""
for message in messages:
getattr(logger, level)(message) | 24,071 |
def headers(**kwargs):
"""
Отправка нескольких заголовков
"""
for name, value in kwargs:
header(name, value)
print() | 24,072 |
def getresuid(*args, **kwargs): # real signature unknown
""" Return a tuple of the current process's real, effective, and saved user ids. """
pass | 24,073 |
def insert_item(store: dict, cache: dict):
"""
Function Name: insert_item
Input:
:param dict store: Categories created by load_categories().
:param dict cache: The cache of the queries.
Output: None
Function Operation: The function gets a list of categories from the admin as well as ... | 24,074 |
def repoinit(testconfig, profiler=None):
"""Determines revision and sets up the repo. If given the profiler optional
argument, wil init the profiler repo instead of the default one."""
revision = ''
#Update the repo
if profiler == "gnu-profiler":
if testconfig.repo_prof is not None:
... | 24,075 |
def test_export_formatted_data(
ref_tree,
res_tree_equal,
ref_csv,
res_csv_equal,
tmp_conftest,
pytester,
do_export,
export_suffix,
registry_reseter,
):
"""Test that the formatted files are properly exported."""
args = []
if not do_export:
expected_dir = """res_pa... | 24,076 |
def test_nested_evented_model_serialization():
"""Test that encoders on nested sub-models can be used by top model."""
class NestedModel(EventedModel):
obj: MyObj
class Model(EventedModel):
nest: NestedModel
m = Model(nest={'obj': {"a": 1, "b": "hi"}})
raw = m.json()
assert ra... | 24,077 |
def lnprior_d(d,L=default_L):
""" Expotentially declining prior. d, L in kpc (default L=0.5) """
if d < 0: return -np.inf
return -np.log(2) - 3*np.log(L) + 2*np.log(d) - d/L | 24,078 |
def test_isomorphism_known_outcome(node_data1, edges1, node_data2, edges2, expected):
"""
Tests for the function ``isomorphism``. May give a false failure (!) if
a different (but still correct) answer is returned due to an implementation
change.
"""
reference = basic_molecule(node_data1, edges1)... | 24,079 |
def textile(text, **args):
"""This is Textile.
Generates XHTML from a simple markup developed by Dean Allen.
This function should be called like this:
textile(text, head_offset=0, validate=0, sanitize=0,
encoding='latin-1', output='ASCII')
"""
return Textiler(text).pro... | 24,080 |
def binary_info_gain(df, feature, y):
"""
:param df: input dataframe
:param feature: column to investigate
:param y: column to predict
:return: information gain from binary feature column
"""
return float(sum(np.logical_and(df[feature], df[y])))/len(df[feature]) | 24,081 |
def draw_shapes(shapes):
"""
Renders the shapes to a separate display surface and then blits them to the main screen too
:arg
shapes: list of shapes classes to render
"""
for i in range(0, len(shapes)):
shapes[i].draw_shape()
main_screen.blit(image_screen, (0, 0)) | 24,082 |
def load_inputs(mod, switch_data, inputs_dir):
"""
The cost penalty of unserved load in units of $/MWh is the only parameter
that can be inputted. The following file is not mandatory, because the
parameter defaults to a value of 500 $/MWh.
optional input files:
lost_load_cost.dat
... | 24,083 |
def get_all_instances(region):
"""
Returns a list of all the type of instances, and their instances, managed
by the scheduler
"""
ec2 = boto3.resource('ec2', region_name=region)
rds = boto3.client('rds', region_name=region)
return {
'EC2': [EC2Schedulable(ec2, i) for i in ec2.instan... | 24,084 |
def futures_navigating(urls: list, amap: bool = True) -> dict:
"""
异步 基于 drive url list 通过请求高德接口 获得 路径规划结果
:param urls:
:param amap: 开关
:return:
"""
data_collections = [None] * len(urls)
pack_data_result = {}
all_tasks = []
# 准备
with warnings.catch_warnings():
warning... | 24,085 |
def getdim(s):
"""If s is a representation of a vector, return the dimension."""
if len(s) > 4 and s[0] == "[" and s[-1] == "]":
return len(splitargs(s[1:-1], ["(", "["], [")", "]"]))
else:
return 0 | 24,086 |
def unstruct2grid(coordinates,
quantity,
cellsize,
k_nearest_neighbors=3,
boundary=None,
crop=True):
"""Convert unstructured model outputs into gridded arrays.
Interpolates model variables (e.g. depth, velocity) from an
... | 24,087 |
def users_bulk_update(file, set_fields, jump_to_index, jump_to_user, limit,
workers):
"""
Bulk-update users from a CSV or Excel (.xlsx) file
The CSV file *must* contain a "profile.login" OR an "id" column.
All columns which do not contain a dot (".") are ignored. You can only
... | 24,088 |
def numToString(num: int) -> str:
"""Write a number in base 36 and return it as a string
:param num: number to encode
:return: number encoded as a base-36 string
"""
base36 = ''
while num:
num, i = divmod(num, 36)
base36 = BASE36_ALPHABET[i] + base36
return base36 or BASE36... | 24,089 |
def real_check(*args, stacklevel=2):
"""Check if arguments are *real numbers* (``int`` and/or ``float``).
Args:
*args: Arguments to check.
stacklevel (int): Stack level to fetch originated function name.
Raises:
RealError: If any of the arguments is **NOT** *real number* (``int`` a... | 24,090 |
def cir(request):
"""
Return current cirplot
"""
config={
"markerSizeFactor": float(request.GET.get('marker-size-factor', 1)),
"markerColorMap": request.GET.get('marker-color-map', 'winter'),
"xAxisLabels": [
(math.radians(10), 'Kontra'),
(math.radians(9... | 24,091 |
def parse_enumeration(enumeration_bytes):
"""Parse enumeration_bytes into a list of test_ids."""
# If subunit v2 is available, use it.
if bytestream_to_streamresult is not None:
return _v2(enumeration_bytes)
else:
return _v1(enumeration_bytes) | 24,092 |
def freeze_blobs(input_file, output_file):
"""Write the frozen blobs to the output file"""
blob_lines = []
for line in input_file:
if line.startswith('//!'):
output_file.write(b'const char '
+ bytearray(line[4:].strip(), 'ascii')
... | 24,093 |
def register_user(username, passwd, email): # type: (str, str, str) -> Optional[str]
"""Returns an error message or None on success."""
if passwd == "":
return "The password can't be empty!"
if email: # validate the email only if it is provided
result = validate_email_address(email)
... | 24,094 |
def _request_helper_chunked(rxgobj, tid):
"""Private helper to get requests with chunks.
Potentially multiple threads will execute this, each with a unique tid."""
thisrequest = rxgobj.get_next_xorrequest(tid)
#the socket is fixed for each thread, so we only need to do this once
socket = thisrequest[0]['sock']
r... | 24,095 |
def refresh_kubeconfig(ctx,
**_):
"""
Refresh access token in kubeconfig for cloudify.nodes.aws.eks.Cluster
target node type.
"""
if utils.is_node_type(ctx.target.node,
CLUSTER_TYPE):
resource_config = ctx.target.instance.runtime_properties.ge... | 24,096 |
def _train_n_hmm(data: _Array, m_states: int, n_trails: int):
"""Trains ``n_trails`` HMMs each initialized with a random tpm.
Args:
data: Possibly unporcessed input data set.
m_states: Number of states.
n_trails: Number of trails.
Returns:
Best model regarding to log... | 24,097 |
def get_metric_function(name):
"""
Get a metric from the supported_sklearn_metric_functions dictionary.
Parameters
----------
name : str
The name of the metric to get.
Returns
-------
metric : function
The metric function.
"""
if name in supported_sklearn_metric... | 24,098 |
def ping(enode, count, destination, interval=None, quiet=False, shell=None):
"""
Perform a ping and parse the result.
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param int count: Number of packets to send.
:param str destination: The destination... | 24,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.