content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def matches_filters(row, field_to_index, transformed_filters):
"""
Validate field name in transformed filter_expressions, return TRUE for rows matching all filters
Parameters
------------
row : str
row in `list` registry table (manager.show())
field_to_index : dict
key = column ... | 5,349,700 |
def div(f, other):
"""Element-wise division applied to the `Functional` objects.
# Arguments
f: Functional object.
other: A python number or a tensor or a functional object.
# Returns
A Functional.
"""
validate_functional(f)
inputs = f.inputs.copy()
if is_functiona... | 5,349,701 |
def select_latest_versions(files):
"""Select only the latest version of files."""
result = []
def same_file(file):
"""Return a versionless identifier for a file."""
# Dataset without the version number
dataset = file.dataset.rsplit('.', 1)[0]
return (dataset, file.name)
... | 5,349,702 |
def _gen_input(storyline, nsims, mode, site, chunks, current_c, nperc, simlen, swg_dir, fix_leap):
"""
:param storyline: loaded storyline
:param SWG_path: path to the directory with contining the files from the SWG
:param nsims: number of sims to run
:param mode: one of ['irrigated', 'dryland']
... | 5,349,703 |
def guess_mime_mimedb (filename):
"""Guess MIME type from given filename.
@return: tuple (mime, encoding)
"""
mime, encoding = None, None
if mimedb is not None:
mime, encoding = mimedb.guess_type(filename, strict=False)
if mime not in ArchiveMimetypes and encoding in ArchiveCompressions:... | 5,349,704 |
def get_paths(uast_file, max_length, max_width, token_extractor, split_leaves=True):
"""
Creates a list of all the paths given the max_length and max_width restrictions.
:param uast_file: file containing a bblfsh UAST as string and binary-coded
:param max_length:
:param max_width:
:param token_e... | 5,349,705 |
def get_members():
"""
Get a list of all members in FreeIPA
"""
members = []
ldap_conn = ldap.get_con()
res = ldap_conn.search_s(
"cn=users,cn=accounts,dc=csh,dc=rit,dc=edu",
pyldap.SCOPE_SUBTREE,
"(uid=*)",
["uid", "displayName"],
)
for member in res:
... | 5,349,706 |
def _unicode_decode_extracted_tb(extracted_tb):
"""Return a traceback with the string elements translated into Unicode."""
return [(_decode(file), line_number, _decode(function), _decode(text))
for file, line_number, function, text in extracted_tb] | 5,349,707 |
def load_table(source, version):
"""Load synth table from file
"""
filepath = get_table_filepath(source, version=version)
return pd.read_table(filepath, delim_whitespace=True) | 5,349,708 |
def single_spaces(string: str) -> str:
"""Replaces all instances of whitespace-like chars with single spaces
Args:
string (str): The string to modify
Returns:
str: The cleaned string
"""
return UGLY_SPACES_RE.sub(" ", string) | 5,349,709 |
def make_zip(folder_path, output_filename):
"""将目录中除zip之外的文件打包成zip文件(包括子文件夹)
空文件夹不会被打包
example
----------------
make_zip('results','zips//招标信息结果_2017-05-09.zip')
"""
cwd = os.getcwd()
# 获取需要打包的文件列表
file_lists = []
for root, dirs, files in os.walk(folder_path):
for file ... | 5,349,710 |
def pandas_to_tsv(df, save_file_path, index=False, mode='w', header=True):
"""
Save pre-processed DataFrame as tsv file.
Params
------
df : pandas DataFrame
DataFrame to save as tsv
save_file_path : str
File save path. if path does not exist, it will be
created automati... | 5,349,711 |
def snmp_count(
address,
oid,
port=161,
community="public",
version=SNMP_v2c,
timeout=10,
bulk=False,
filter=None,
max_repetitions=BULK_MAX_REPETITIONS,
tos=None,
ioloop=None,
udp_socket=None,
):
"""
Perform SNMP get request and returns Future to be used
insid... | 5,349,712 |
def create_group(api_key: str, board_id: str, group_name: str, *args, **kwargs):
"""Creates a new group in a specific board.
__________
Parameters
api_key : `str`
The monday.com v2 API user key.
board_id : `str`
The board's unique identifier.
group_name ... | 5,349,713 |
def test_delete_course(user_drf_client, courses):
"""Test the view that handles a request to delete a Course"""
course = courses[0]
resp = user_drf_client.delete(
reverse("courses_api-detail", kwargs={"pk": course.id})
)
assert resp.status_code == status.HTTP_405_METHOD_NOT_ALLOWED | 5,349,714 |
def _solve_qp_ik_vel(vel, jac, joint_pos, joint_lims=None, duration=None, margin=0.2):
"""
Solves the IK for a given pusher velocity using a QP solver, imposing joint limits.
If the solution is optimal, it is guaranteed that the resulting joint velocities will not
cause the joints to reach their limits ... | 5,349,715 |
def distance_straight(power, inches, freeze=True):
"""
:param power: range -100 to 100
:param inches: inches
:param freeze: True stops motors at end
"""
clear_motor_position_counter(c.LEFT_MOTOR)
clear_motor_position_counter(c.RIGHT_MOTOR)
blind(power, power)
distance = inches * 180.... | 5,349,716 |
def channel_will_be_next(crontab: str):
"""Checks if the given notification channel will be activated on the
next channel, in an hour."""
return pycron.is_now(crontab, now + timedelta(hours=1)) | 5,349,717 |
def update_plot_force(force_est, rplt, app, ratio, box=None, muscle_names=None, plot_type="progress_bar"): # , box):
"""
update force plot
----------
force_est: np.ndarray
array of force estimate size
rplt, app, box:
values from init f... | 5,349,718 |
def hospital_resident(residents, hospitals, optimal="resident"):
"""Solve an instance of HR using an adapted Gale-Shapley algorithm
:cite:`Rot84`. A unique, stable and optimal matching is found for the given
set of residents and hospitals. The optimality of the matching is found with
respect to one part... | 5,349,719 |
def log_request(response):
"""Log request.
:param response:
:return:
"""
ip = request.headers.get('X-Forwarded-For', request.remote_addr)
host = request.host.split(':', 1)[0]
app.logger.info(f"method={request.method}, path={request.path}, "
f"status={response.status_cod... | 5,349,720 |
def reduce(path, n_procs, column, function):
""" Calculate an aggregate value from IMB output.
Args:
path: str, path to file
n_procs: int, number of processes
column: str, column name
function: callable to apply to specified `column` of table for `n_procs` in... | 5,349,721 |
def output_file_path(status_id, phase):
"""
"""
BASE_DIR = Path(__file__).resolve().parent.parent
return f"%s/logs/stage/{status_id}-{phase}.txt" %str(BASE_DIR) | 5,349,722 |
def clean(some_string, uppercase=False):
"""
helper to clean up an input string
"""
if uppercase:
return some_string.strip().upper()
else:
return some_string.strip().lower() | 5,349,723 |
def to_title(value):
"""Converts a string into titlecase."""
t = re.sub("\s+", ".", value)
t = filter(LETTER_SET.__contains__, t)
t = re.sub("([a-z])'\W([A-Z])", lambda m: m.group(0).lower(), t.title())
return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t) | 5,349,724 |
def parse_config_or_kwargs(config_file, **kwargs):
"""parse_config_or_kwargs
:param config_file: Config file that has parameters, yaml format
:param **kwargs: Other alternative parameters or overwrites for config
"""
with open(config_file) as con_read:
yaml_config = yaml.load(con_read, Load... | 5,349,725 |
def sig_generacion(m):
"""Devuelve la matriz resultante de aplicar las reglas del juego a cada celda"""
FILAS = len(m)
COLUMNAS = len(m[0]) if len(m) else 0
new_m = [] # matriz resultado
for i in range(FILAS):
l = [] # Una lista para ir generando una fila
for j in range(COLUMNAS):
... | 5,349,726 |
def calc_file_signature(data: str, password: str = None) -> str:
"""
Função que calcula o has da assinatura de um arquivo
@param data: string assinada
@param password: senha da assinatura
@return: hash da assinatura
"""
if (password):
digest = hmac.new(bytes(password), msg=bytes(dat... | 5,349,727 |
def processIRMovie(measurement, rotation, inputfolder, exportpath,
timeshift=0, doRotation=True, doRenaming=True):
"""Process TMC-files of IR camera into CSV files in movie mode.
Movie mode means, that one frame-sequence (movie) per datapoint was taken
instead of one frame per datapoint ... | 5,349,728 |
def get_angle_from_coordinate(lat1, long1, lat2, long2):
"""https://stackoverflow.com/questions/3932502/calculate-angle-between-two-latitude-longitude-points"""
dLon = (long2 - long1)
y = np.sin(dLon) * np.cos(lat2)
x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(dLon)
brng ... | 5,349,729 |
def get_predictions():
"""Return the list of predications as a json object"""
results = []
conn = None
columns = ("pid", "name", "location", "latitude", "longitude", "type", "modtime")
try:
conn = psycopg2.connect(db_conn)
# create a cursor
cur = conn.cursor()
cur.e... | 5,349,730 |
def parse_packageset(packageset):
"""
Get "input" or "output" packages and their repositories from each PES event.
:return: set of Package tuples
"""
return {parse_package(p) for p in packageset.get('package', packageset.get('packages', []))} | 5,349,731 |
def download_nyiso_csv(month, data_type, zone = None):
"""Downloads a NYISO csv dataset for a specific data type, month, and zone.
Args:
month: string denoting the first day of the month to be downloaded in
yyyymmdd format
data_type: string denoting the type of NYISO d... | 5,349,732 |
def pretty_print_large_number(number):
"""Given a large number, it returns a string of the sort: '10.5 Thousand' or '12.3 Billion'. """
s = str(number).ljust(12)
if number > 0 and number < 1e3:
pass
elif number >= 1e3 and number < 1e6:
s = s + " (%3.1f Thousand)" % (number * 1.0 / 1e3)... | 5,349,733 |
def find_aligning_transformation(skeleton, euler_frames_a, euler_frames_b):
"""
performs alignment of the point clouds based on the poses at the end of
euler_frames_a and the start of euler_frames_b
Returns the rotation around y axis in radians, x offset and z offset
"""
point_cloud_a = convert_... | 5,349,734 |
def find_all_visit(tx):
"""
Method that queries the database to find all VISIT relationships
:param tx: session
:return: nodes of Person , Location
"""
query = (
"""
MATCH (p:Person)-[r:VISIT]->(l:Location)
RETURN p , ID(p) , r , r.start_hour , r.end_hour , r.date ,... | 5,349,735 |
def read_vectors(filename):
"""Reads measurement vectors from a space or comma delimited file.
:param filename: path of the file
:type filename: str
:return: array of vectors
:rtype: numpy.ndarray
:raises: ValueError
"""
vectors = []
data = read_csv(filename)
expected_size = le... | 5,349,736 |
def get_scoring_algorithm():
""" Base scoring algorithm for index and search """
return scoring.BM25F() | 5,349,737 |
def _make_augmentation_pipeline(augmentation_list):
"""Buids an sklearn pipeline of augmentations from a tuple of strings.
Parameters
----------
augmentation_list: list of strings, A list of strings that determine the
augmentations to apply, and in which order to apply them (the first
s... | 5,349,738 |
def ctg_path(event_name,sc_reform,path_cache,var_map,model,prev_events):
"""
Recursively computes the controllable and contigent events that influence
the schedule of a given event.
"""
if event_name in path_cache:#If solution has been already computed, use it
return path_cache[event_name]
... | 5,349,739 |
def _setup_mock_socket_file(mock_socket_create_conn, resp):
"""Sets up a mock socket file from the mock connection.
Args:
mock_socket_create_conn: The mock method for creating a socket connection.
resp: iterable, the side effect of the `readline` function of the mock
socket file.
Returns:
The ... | 5,349,740 |
def usage_info():
"""
usage info
"""
print("Input params is illegal...")
print("try it again:\n python matcaffe2pycaffe.py -h") | 5,349,741 |
def get_defense_type(action: int, game_config) -> int:
"""
Utility method for getting the defense type of action-id
:param action: action-id
:param game_config: game configuration
:return: action type
"""
defense_type = action % (game_config.num_attack_types+1) # +1 for detection
return... | 5,349,742 |
def color_box(
colors, border="#000000ff", border2=None, height=32, width=32,
border_size=1, check_size=4, max_colors=5, alpha=False, border_map=0xF
):
"""Color box."""
return colorbox.color_box(
colors, border, border2, height, width,
border_size, check_size, max_colors, alpha, border_... | 5,349,743 |
def get_performance_of_lstm_classifier(X, y, n_epochs, verbose=1, final_score=False):
"""
Reshapes feature matrix X, applies LSTM and returns the performance of the neural network
:param X: List of non-reshaped/original feature matrices (one per logfile)
:param y: labels
:param n_epochs: Number of ... | 5,349,744 |
def worker(data):
"""Thread function."""
width, column = data
queen = Queen(width)
queen.run(column)
return queen.solutions | 5,349,745 |
def eitem(self, key, value):
"""Translate included eitems."""
_eitem = self.get("_eitem", {})
urls = []
for v in force_list(value):
urls.append(
{
"description": "E-book by EbookCentral",
"value": clean_val("u", v, str),
}
)
_e... | 5,349,746 |
def annotate_group(groups, ax=None, label=None, labeloffset=30):
"""Annotates the categories with their parent group and add x-axis label"""
def annotate(ax, name, left, right, y, pad):
"""Draw the group annotation"""
arrow = ax.annotate(name, xy=(left, y), xycoords="data",
... | 5,349,747 |
def background_schwarzfischer(fluor_chan, bin_chan, div_horiz=7, div_vert=5, mem_lim=None, memmap_dir=None):
"""Perform background correction according to Schwarzfischer et al.
Arguments:
fluor_chan -- (frames x height x width) numpy array; the fluorescence channel to be corrected
bin_chan -- b... | 5,349,748 |
def _get_eula_date(extract_path: str) -> Optional[str]:
"""Get any EULA accept date in the install script, if any.
:param extract_path: The path to the extracted archive.
:return: The EULA date, if any.
"""
install_script = os.path.join(extract_path, "houdini.install")
if not os.path.exists(i... | 5,349,749 |
def get_output_data_path(extension, suffix=None):
"""Return full path for data file with extension, generated by a test script"""
name = get_default_test_name(suffix)
return osp.join(TST_PATH[0], f"{name}.{extension}") | 5,349,750 |
def _plot(self, **kwargs) -> tp.BaseFigure: # pragma: no cover
"""Plot `close` and overlay it with the heatmap of `labels`."""
if self.wrapper.ndim > 1:
raise TypeError("Select a column first. Use indexing.")
return self.close.rename('close').vbt.overlay_with_heatmap(self.labels.rename('labels'), ... | 5,349,751 |
def _set_global_vars(metadata):
"""Identify files used multiple times in metadata and replace with global variables
"""
fnames = collections.defaultdict(list)
for sample in metadata.keys():
for k, v in metadata[sample].items():
print k, v
if os.path.isfile(v):
... | 5,349,752 |
def user_get(context, id):
"""Get user by id."""
return IMPL.user_get(context, id) | 5,349,753 |
def animation_template(world):
"""Shows how to animate a robot."""
#first, build a trajectory with 10 random configurations
robot = world.robot(0)
times = list(range(10))
milestones = []
for t in times:
robot.randomizeConfig()
milestones.append(robot.getConfig())
traj = traje... | 5,349,754 |
def unpack_singleton(x):
"""
>>> unpack_singleton([[[[1]]]])
1
>>> unpack_singleton(np.array(np.datetime64('2000-01-01')))
array('2000-01-01', dtype='datetime64[D]')
"""
while isinstance(x, (list, tuple)):
try:
x = x[0]
except (IndexError, TypeError, KeyError):
... | 5,349,755 |
def run_bincapture(args: List[str]) -> bytes:
"""run is like "subprocess.run(args, capture_out=True, text=False)",
but with helpful settings and obeys "with capture_output(out)".
"""
if _capturing:
try:
return subprocess.run(args, check=True, capture_output=True).stdout
excep... | 5,349,756 |
def _EnumValFromText(fdesc, enum_text_val, log):
"""Convert text version of enum to integer value.
Args:
fdesc: field descriptor containing the text -> int mapping.
enum_text_val: text to convert.
log: logger obj
Returns:
integer value of enum text.
"""
log.debug("converting enum val:" + enum... | 5,349,757 |
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
# print('correct shape:', corre... | 5,349,758 |
def yyyydoy2jd(year,doy,hh=0,mm=0,ss=0.0):
"""
yyyydoy2jd Take a year, day-of-year, etc and convert it into a julian day
Usage: jd = yyyydoy2jd(year,doy,hh,mm,ss)
Input: year - 4 digit integer
doy - 3 digit, or less integer, (1 <= doy <= 366)
hh - 2 digit, or less int, (0 ... | 5,349,759 |
def lon2index(lon, coords, corr=True):
"""convert longitude to index for OpenDAP request"""
if corr:
if lon < 0:
lon += 360
lons = coords.lon.values
return np.argmin(np.abs(lons - lon)) | 5,349,760 |
def get_dynamic_call_address(ea):
"""Find all dynamic calls e.g call eax"""
dism_addr_list = list(FuncItems(ea))
return [addr for addr in dism_addr_list if print_insn_mnem(addr) == 'call' and get_operand_type(addr, 0)==1] | 5,349,761 |
def update_pfc_context_to_original(operation: DataOperation) -> None:
"""
Revert the change to pyfileconf currently running context
made by :func:`update_pfc_context_to_pipeline_section_path`
:param operation: The operation which was just executed
:return: None
"""
context.stack.pop_frame() | 5,349,762 |
def iwbo_nats(model, x, k, kbs=None):
"""Compute the IWBO in nats."""
if kbs: return - iwbo_batched(model, x, k, kbs).mean()
else: return - iwbo(model, x, k).mean() | 5,349,763 |
def ko_json(queryset, field_names=None, name=None, safe=False):
"""
Given a QuerySet, return just the serialized representation
based on the knockout_fields. Useful for middleware/APIs.
Convenience method around ko_data.
"""
return ko_data(queryset, field_names, name, safe, return_json=True) | 5,349,764 |
def map(video_features_path, audio_hypothesis, file_uri, ier=False):
"""Maps outputs of pyannote.audio and pyannote.video models
Parameters:
-----------
video_features_path: str
Path to the video features (.npy) file as defined in pyannote.video
audio_hypothesis: Annotation
hypothes... | 5,349,765 |
def delete_demo(guid):
"""
Delete a demo object and all its children.
:param guid: The demo's guid
:return:
"""
web_utils.check_null_input((guid, 'demo to delete'))
demo_service.delete_demo_by_guid(guid)
return '', 204 | 5,349,766 |
def return_json():
"""
Sample function that has been given a different name
"""
print("Tooler should render out the JSON value returned")
return {"one": 1, "deep": {"structure": ["example"]}} | 5,349,767 |
def get(url) -> str:
"""Send an http GET request.
:param str url:
The URL to perform the GET request for.
:rtype: str
:returns:
UTF-8 encoded string of response
"""
return _execute_request(url).read().decode("utf-8") | 5,349,768 |
def strip_filenames(path, ext='', allowed_chars=None):
"""
Strips the filenames from whitespaces and other 'problematic' chars.
In other words converts the filenames to alpharethmetic chars.
:param path: (String) Base path for the filenames.
:param ext: (String, optional) If provided, the glo... | 5,349,769 |
def brute_force(durs, labels, labelset, train_dur, val_dur, test_dur, max_iter=5000):
"""finds indices that split (labels, durations) tuples into training,
test, and validation sets of specified durations, with the set of unique labels
in each dataset equal to the specified labelset.
The durations of t... | 5,349,770 |
def test_operator__remove_all__2(evaluate):
"""remove-all() does nothing on `None`."""
assert None is evaluate(None, 'remove-all', 'a') | 5,349,771 |
def VOLUME(env: Optional[Dict] = None) -> Dict:
"""Get specification for the volume that is associated with the worker that
is used to execute the main algorithm step.
Parameters
----------
env: dict, default=None
Optional environment variables that override the system-wide
settings... | 5,349,772 |
def test_reaction_oneliner():
"""
7
2
xx
2
3
"""
m1 = MyObject4(bar=2)
m2 = MyObject4(bar=lambda: m1.bar)
loop.iter()
print(m2.bar)
loop.iter()
print(m2.bar)
print('xx')
m1.set_bar(3)
loop.iter()
print(m2.bar)
loop.iter()
print(m2.bar) | 5,349,773 |
def compress(body, compress_level):
"""Compress 'body' at the given compress_level."""
import zlib
yield '\037\213' # magic header
yield '\010' # compression method
yield '\0'
yield struct.pack("<L", long(time.time()))
yield '\002'
yield '\377'
crc = zlib.crc32... | 5,349,774 |
def train_step(model_optimizer, game_board_log, predicted_action_log,
action_result_log):
"""Run one training step."""
def loss_fn(model_params):
logits = PolicyGradient().apply({'params': model_params}, game_board_log)
loss = compute_loss(logits, predicted_action_log, action_result_log)
... | 5,349,775 |
def make_static_rnn_with_control_flow_v2_tests(options):
"""Make a set of tests to do basic Lstm cell."""
test_parameters = [
{
"dtype": [tf.float32],
"num_batches": [4],
"time_step_size": [4],
"input_vec_size": [3],
"num_cells": [4],
"use_sequence_... | 5,349,776 |
def jaccard(structured_phrases, phrases_to_score, partial=False, status_callback=None, status_increment=None, pmd_class=PartialMatchDict):
""" calculate jaccard similarity between phrases_to_score, using
structured_phrases to determine cooccurrences. For phrases `a' and `b', let
A be the set of documents `a... | 5,349,777 |
def print_python(node: AST) -> str:
"""Takes an AST and produces a string containing a human-readable
Python expression that builds the AST node."""
return black.format_str(ast.dump(node), mode=black.FileMode()) | 5,349,778 |
def reg2deg(reg):
"""
Converts phase register values into degrees.
:param cycles: Re-formatted number of degrees
:type cycles: int
:return: Number of degrees
:rtype: float
"""
return reg*360/2**32 | 5,349,779 |
def weakify_voxelwise_label_one_sub(pos_path_path, masks_path):
""" This function converts the voxelwise mask of a positive patch into a weak mask: it creates a sphere around the aneurysm center
Args:
pos_path_path (str): path to the positive patch to be converted
masks_path (str): path to the f... | 5,349,780 |
def load_config(config_file=None):
"""Load the configuration file.
Configuration options will be available in dict sjkscan.conf.config.
When configuration options are added, modified or removed in future
releases, `config_template` in this function must be updated.
:param config_file: file to read... | 5,349,781 |
def plotit(depth, a, n, res1, res2, res3, title):
"""Call `comp_appres` and plot result."""
# Compute the three different models
rho1, AB2 = comp_appres(depth, res1, a, n)
rho2, _ = comp_appres(depth, res2, a, n)
rho3, _ = comp_appres(depth, res3, a, n)
# Create figure
plt.figure()
# ... | 5,349,782 |
def plot_accuracy(scores: dict, filename: str) -> None:
"""
Plots the distribution of validation accuracy of the neural network
for all hyperparameter combination experiments.
"""
bins = 250
(hist, _) = np.histogram(scores, bins=bins, range=(0, 1))
x = np.linspace(0, 1, bins)
... | 5,349,783 |
def update_channel_metadata_cache():
"""
After a channel is imported, or when the devserver is started,
scan through the settings.CONTENT_DATABASE_DIR folder for all channel content databases,
and pull the data from each database's ChannelMetadata object to update the ChannelMetadataCache
object in ... | 5,349,784 |
def flag_element(uid: int, reason: Union[key_duplicate, key_optimization, ReviewDeleteReasons], db_user: User,
is_argument: bool, ui_locales: str, extra_uid=None) -> dict:
"""
Flags an given argument based on the reason which was sent by the author. This argument will be enqueued
for a revi... | 5,349,785 |
def export_bioimageio_model(checkpoint, export_folder, input_data=None,
dependencies=None, name=None,
description=None, authors=None,
tags=None, license=None,
documentation=None, covers=None,
... | 5,349,786 |
def main(args=None):
"""Entry point for CLI."""
if len(sys.argv) > 1:
if sys.argv[1] in {"-h", "--h", "help", "-help", "--help", "-H"}:
help_text()
sys.exit()
BatchMandelbrot(**dict(arg.split("=") for arg in sys.argv[1:])) | 5,349,787 |
def load_config_at_path(path: Pathy) -> Dynaconf:
"""Load config at exact path
Args:
path: path to config file
Returns:
dict: config dict
"""
path = pathlib.Path(path)
if path.exists() and path.is_file():
options = DYNACONF_OPTIONS.copy()
options.update({
... | 5,349,788 |
def _build_target(action, original_target, plugin, context):
"""Augment dictionary of target attributes for policy engine.
This routine adds to the dictionary attributes belonging to the
"parent" resource of the targeted one.
"""
target = original_target.copy()
resource, _w = _get_resource_and_... | 5,349,789 |
def test_constructor_raises_value_error_for_invalid_url():
"""Test that ocnstructor raises TypeError for invalid url."""
with pytest.raises(ValueError):
ms.MangaSource('test', 'bad test', '-') | 5,349,790 |
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
"""Configure Gammu state machine."""
device = entry.data[CONF_DEVICE]
config = {"Device": device, "Connection": "at"}
gateway = await create_sms_gateway(config, opp)
if not gateway:
return False
opp.data[DOMAIN][SMS_GA... | 5,349,791 |
def grep_response_body(regex_name, regex, owtf_transaction):
"""Grep response body
:param regex_name: Regex name
:type regex_name: `str`
:param regex: Regex
:type regex:
:param owtf_transaction: OWTF transaction
:type owtf_transaction:
:return: Output
:rtype: `dict`
"""
retu... | 5,349,792 |
def link(f, search_range, pos_columns=None, t_column='frame', verbose=True, **kwargs):
"""
link(f, search_range, pos_columns=None, t_column='frame', memory=0,
predictor=None, adaptive_stop=None, adaptive_step=0.95,
neighbor_strategy=None, link_strategy=None, dist_func=None,
to_eucl=None)... | 5,349,793 |
def get_classifier(opt, input_dim):
"""
Return a tuple with the ML classifier to be used and its hyperparameter
options (in dict format)."""
if opt == 'RF':
ml_algo = RandomForestClassifier
hyperparams = {
'n_estimators': [100],
'max_depth': [None, 10, 30, 50, 100... | 5,349,794 |
def list_spiders_endpoint():
"""It returns a list of spiders available in the SPIDER_SETTINGS dict
.. version 0.4.0:
endpoint returns the spidername and endpoint to run the spider from
"""
spiders = {}
for item in app.config['SPIDER_SETTINGS']:
spiders[item['endpoint']] = 'URL: ' + ... | 5,349,795 |
def plot3dOnFigure(ax, pixels, colors_rgb,axis_labels=list("RGB"), axis_limits=((0, 255), (0, 255), (0, 255))):
"""Plot pixels in 3D."""
# Set axis limits
ax.set_xlim(*axis_limits[0])
ax.set_ylim(*axis_limits[1])
ax.set_zlim(*axis_limits[2])
# Set axis labels and sizes
ax.tick_params(axis=... | 5,349,796 |
def _get_slice_predictions(
model: ModelBridge,
param_name: str,
metric_name: str,
generator_runs_dict: TNullableGeneratorRunsDict = None,
relative: bool = False,
density: int = 50,
slice_values: Optional[Dict[str, Any]] = None,
fixed_features: Optional[ObservationFeatures] = None,
t... | 5,349,797 |
def ellipse(a, b, center=(0.0, 0.0), num=50):
"""Return the coordinates of an ellipse.
Parameters
----------
a : float
The semi-major axis of the ellipse.
b : float
The semi-minor axis of the ellipse.
center : 2-tuple of floats, optional
The position of the center of the... | 5,349,798 |
def _copy_inputs(test_inputs: List[str], project_path: str) -> bool:
"""Copies all the test files into the test project directory."""
# The files are assumed to reside in the repo's 'data' directory.
print(f'# Copying inputs (from "${{PWD}}/{_DATA_DIRECTORY}")...')
expected_prefix: str = f"{_DATA_DIRE... | 5,349,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.