content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_list_my_asi_observations_command_when_invalid_args_are_provided(args, err_msg, client):
"""
To test pt-list-my-attack-surface-observations command when invalid arguments are provided.
"""
from PassiveTotal_v2 import list_my_asi_observations_command
with pytest.raises(ValueError) as de:
... | 5,311,600 |
def write_cache(d, filepath):
"""Writes dict to a cache file on disk."""
f = h5py.File(filepath, "w")
for k, v in d.items():
try:
f.create_dataset(k, data=v)
except Exception:
pass
f.close() | 5,311,601 |
def create_pie_chart(data, rngs, colors=['#244268', '#426084', '#67809F', '#95A9C1', '#C6D2E0'],
unit_scale=1.0, measure_quantity='m^3', figsize=(33, 15),
legend_loc=(0.383, -0.25), zebra_color=(False, 3),
legend_fontsize=50, chart_fontsize=60, dpi=72, n... | 5,311,602 |
def entrypoint():
"""The entry that the CLI is executed from"""
try:
dispatch_cli()
except DispatchException as e:
click.secho(f"ERROR: {e}", bold=True, fg="red") | 5,311,603 |
def read_xr_and_concat(fname: pathlib.Path):
"""Reads the given filename and concatenates it into a single file.
Assumes that the filename is an xarray file which was made by parsing
many calcium analysis results.
"""
data = xr.open_dataset(fname).dff
return np.vstack(data) | 5,311,604 |
def ee_dask_deploy(config, pb_id, image, n_workers=1, buffers=[]):
"""Deploy Dask execution engine.
:param config: configuration DB handle
:param pb_id: processing block ID
:param image: Docker image to deploy
:param n_workers: number of Dask workers
:param buffers: list of buffers to mount on ... | 5,311,605 |
def _filterProviders(providers, item, cfgData, dataCache):
"""
Take a list of providers and filter/reorder according to the
environment variables
"""
eligible = []
preferred_versions = {}
sortpkg_pn = {}
# The order of providers depends on the order of the files on the disk
# up to ... | 5,311,606 |
def is_win(record):
"""
Test for specific domains
:param record: line to analyse
:return: True if is specific for Windows, False otherwise
"""
return win_reg1.search(record) or win_reg2.search(record) or win_reg3.search(record) \
or win_reg4.search(record) or win_reg5.search(record) o... | 5,311,607 |
def initialize_nose_logger() -> logging.Logger:
"""Configures the logger to be used by the "nose" package.
"""
print("initialize_nose_logger()")
logger_config = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"level": log... | 5,311,608 |
def addGroups(raw_entries):
"""Add implicitely given groups to raw_entries."""
# Collect known names.
names = set()
for e in raw_entries:
name = e.name.text
if '#' not in name and '::' not in name:
names.add(name)
# Collect unknown names.
unknown = set()
for e in ... | 5,311,609 |
def warn(message: str):
"""Log the warning to stdout"""
print(_apply_color("yellow", f"[!] {message}")) | 5,311,610 |
def sq_sums(a_gpu, b_gpu, GSZ=GSZ):
"""
Compute squared summations of rows from GPUArrays and then their pairwise summations.
Parameters
----------
A : GPUArray
B : GPUArray
GSZ : int, optional
Grid size for CUDA kernel invocation
Returns
-------
out : GPUArray
... | 5,311,611 |
def timealize_img(experiment, image, label):
"""
Transforms an image to an image with timesteps to be fed into a SNN.
Copies the image timesteps times and stacks them together.
Equivalent of feeding the SNN a raw input current, not feeding it spikes.
:param experiment:
:param image:
:param l... | 5,311,612 |
def swift_names(path: list, schema: dict):
""" Generates Swift names for each object type from Plotly JSON schema. """
for name, item in schema.items():
if not isinstance(item, dict):
Primitive.camel_cased(name)
continue
if 'valType' in item:
if item['valType... | 5,311,613 |
def simpleClosedPath(listPts):
"""Returns the closed path of the given points"""
points = listPts[:] # making a compy of the listPts
y_min_index = getBottomRight(listPts)
y_min_point = points.pop(y_min_index)
closed_path = [(y_min_point, 0)]
for point in points:
angle = the... | 5,311,614 |
def home():
"""
Route for displaying the homepage.
"""
return render_template("home.html", home=True) | 5,311,615 |
def timefunc(func, msg, *args, **kwargs):
"""Benchmark *func* and print out its runtime.
Args:
msg (str):
func:
*args:
**kwargs:
Returns:
object:
"""
# Make sure the function is compiled before we start the benchmark
res = func(*args, **kwargs)
# T... | 5,311,616 |
def learn(repo_path, app_name, app_cmd_file, app_init_cwd, memsize, strace, pristine_sysroot_name,
post_sim_sysroot_path,
copy_spawn):
"""
Analyze an app for how to create SimEnv.
"""
manifest_db_path = get_manifests_dir(repo_path)
sysroots_archive_path = get_sysroots_dir(repo_pa... | 5,311,617 |
def test_link_order():
"""Test ordering of links."""
rg = RasterModelGrid(3, 4)
assert_array_equal(rg.node_at_link_tail, [0, 1, 2, 0, 1, 2, 3, 4, 5, 6,
4, 5, 6, 7, 8, 9, 10])
assert_array_equal(rg.node_at_link_head, [1, 2, 3, 4, 5, 6, 7, 5, 6, 7,
... | 5,311,618 |
def button(where=None, x=0, y=0, label="", width=0, height=30, idle=None, over=None, down=None, color=(50,50,50)):
"""Display a button whose graphics are images (np.ndarray). The button accepts three images to describe its states, which are idle (no mouse interaction), over (mouse is over the button) and down (mouse c... | 5,311,619 |
def execute_clean_call(
clean_call = None,
reset = False,
):
"""
Execute a clean call object, optionally deleting previous versions
of the imaging first.
Set reset to wipe any existing output data.
"""
if not isinstance(clean_call, CleanCall):
logger.error("Please input a v... | 5,311,620 |
def action_checker(target_name):
"""
Checks in on targets.json and determines what actions are available for the requesting target.
Parameters
----------
target_name: str
Returns
-------
A list of available actions for the target.
"""
target_json = get_target_data(target_name)
... | 5,311,621 |
def print_header():
"""Prints out header information."""
# Always let the user know a help file is available.
print("\nFor help, use: python dimorphite_dl.py --help")
# And always report citation information.
print("\nIf you use Dimorphite-DL in your research, please cite:")
print("Ropp PJ, Kam... | 5,311,622 |
def get_licence(html):
"""
Searches the HTML content for a mention of a CC licence.
"""
if "creative-commons" in html or "Creative Commons" in html:
licence = "CC"
else:
licence = "N/A"
return licence | 5,311,623 |
def test_sha384ValidatorValidator_incorrect_types(value):
"""Check if improper values (with wrong type) are validated."""
# exception is expected
with pytest.raises(Invalid) as excinfo:
sha384Validator(value) | 5,311,624 |
def delete(share_directory, force=False):
"""
Deletes a share. The directory representing the share should exist.
For more information on input variables run nfs4_share delete --help
"""
share = unlock(share_directory)
htaccess.remove_from(share, absent_ok=True)
share.self_d... | 5,311,625 |
def get_selected_ctrl():
"""
the joints from current selection.
:return: <tuple> array of joints from selection.
"""
selected_obj = object_utils.get_selected_node()
if selected_obj and object_utils.is_shape_curve(selected_obj):
return selected_obj | 5,311,626 |
def sum_temp(s, n):
"""
:param s: int, sum of total value of temperature
:param n: int, latest information to add up
:return: s + n
"""
s += n
return s | 5,311,627 |
def foreground_rainbow(ncolors=20, background_color=BLACK):
"""
A rainbow gradient of `ncolors` ColorPairs with a given background color.
"""
return [
ColorPair(*foreground_color, *background_color)
for foreground_color in _rainbow_gradient(ncolors)
] | 5,311,628 |
def get_method_parameter_values(code, line, full_sig):
""" Returns a List of parameter values for the method at a given line """
param_list = []
offset = int((get_offset(code, line, "catch(") - 3))
line += (1 + int(offset / 2))
for i in range(int(offset / 2)):
param_pattern = re.compile(rf"... | 5,311,629 |
def mrc_to_dask(fname: Pathlike, chunks: tuple):
"""
Generate a dask array backed by a memory-mapped .mrc file
"""
with access_mrc(fname, mode="r") as mem:
shape, dtype = mrc_shape_dtype_inference(mem)
chunks_ = normalize_chunks(chunks, shape)
def chunk_loader(fname, block_info=None):
... | 5,311,630 |
def start_box():
""" Create Vagrant file and up virtual machine """
# render templates for vagrant up
render_template('Vagrantfile.j2', 'Vagrantfile')
render_template('Makefile.j2', 'Makefile')
run('chmod +x Makefile')
# make provisioning folder
mkdir('provision')
render_template('provis... | 5,311,631 |
def get_local_path_kind(pathname):
"""Determine if there is a path in the filesystem and if the path
is a directory or non-directory."""
try:
os.stat(pathname)
if os.path.isdir(pathname):
status = LOCAL_PATH_DIR
else:
status = LOCAL_PATH_NON_DIR
except OS... | 5,311,632 |
def _get_bindings_for_assert(node):
"""
..code:: python
Assert(expr test, expr? msg)
"""
yield from get_bindings(node.test)
if node.msg is not None:
yield from get_bindings(node.msg) | 5,311,633 |
def do_cleanup(catalog):
"""Cleanup catalog after importing all data."""
task_str = catalog.get_current_task_str()
# Set preferred names, calculate some columns based on imported data,
# sanitize some fields
keys = list(catalog.entries.keys())
cleanupcnt = 0
for oname in pbar(keys, task_st... | 5,311,634 |
def mock_random_choice(seq):
"""Always returns first element from the sequence."""
# We could try to mock a particular |seq| to be a list with a single element,
# but it does not work well, as random_choice returns a 'mock.mock.MagicMock'
# object that behaves differently from the actual type of |seq[0]|.
ret... | 5,311,635 |
def apply_hists(d):
"""
Apply histogram values to dict d
:param d: Dictionary
:return:
"""
d.update(hists) | 5,311,636 |
def mount_remote_volumes(
runner: Runner, remote_info: RemoteInfo, ssh: SSH, allow_all_users: bool
) -> Tuple[str, Callable]:
"""
sshfs is used to mount the remote system locally.
Allowing all users may require root, so we use sudo in that case.
Returns (path to mounted directory, callable that wi... | 5,311,637 |
def find_entries_without_field(path_or_db, field):
"""Return entries without field."""
_, db = _load_or_use(path_or_db)
lacking_entries = []
for entry in db.entries:
if field not in entry:
lacking_entries += [entry]
return lacking_entries | 5,311,638 |
def generate_application_history_records(app_id, when = None):
"""
After application/package list has been updated store the current state in the DB.
@app_id - Application.id
@when - datetime - optional
TODO: fix slow queries!!!
TODO: when importing refactor to just save the text of the im... | 5,311,639 |
def valley_width_transform(valleys):
"""Calculate the approximate distributed valley width
`from bluegeo.water import valley_width_transform;test = valley_width_transform('/Users/devin/Desktop/valley.tif')`
Arguments:
valleys {[type]} -- [description]
"""
valleys = Raster(valleys)
mask... | 5,311,640 |
def add_contents_entry(section, page_variable, feature, parent):
"""
Adds a new row to the table of contents table.
<p>
The table should be called 'report_contents' and be
structured with a 'section' and a 'page' column. No
detailed checks are made to confirm this structure is
in place.
</p><p>... | 5,311,641 |
def clean_count(dataset):
"""
remove stop words
remove numbers - ints and floats
remove numbers with $
save as a shortened df
"""
file_dst = str(dataset + '_untargeted_count')
path_dst = os.path.join(retrieve_path(file_dst), dataset + '.csv')
df = pd.read_csv(path_dst)
... | 5,311,642 |
def V_6_3_3(b, h0, ft):
"""
不配置箍筋和弯起钢筋的一般板类受弯构件斜截面承载力
"""
if h0<800:
beta_h = 1
elif h0<2000:
beta_h = (800/h0)**0.25
else:
beta_h = (800/2000)**0.25
return 0.7*beta_h*ft*b*h0 | 5,311,643 |
def make_cond_block():
"""
if flor.skip_stack.peek().should_execute(not flor.SKIP):
pass
TODO: Extend to accept predicate
"""
previous_arg = ast.UnaryOp(
op=ast.Not(),
operand=ast.Attribute(
value=ast.Name('flor', ast.Load()),
... | 5,311,644 |
def reverse_rel(wn, source, target, change_list=None):
"""Reverse the direction of relations"""
rel_type = find_type(source, target)
delete_rel(source, target, change_list)
if rel_type in inverse_synset_rels:
delete_rel(target, source, change_list)
insert_rel(target, rel_type, source, change... | 5,311,645 |
def copy_description_to_catalog_details(apps, schema_editor):
"""
Copy the existing page description to the new `catalog_details`
field.
"""
CoursePage = apps.get_model("cms", "CoursePage")
ProgramPage = apps.get_model("cms", "ProgramPage")
CoursePage.objects.update(catalog_details=models.F... | 5,311,646 |
def removeInteger(string):
"""
Remove an integer from a string.
Args:
string: write your description
"""
_checkSequenceError(string=string, start=bytesHexB, expected="02")
length, lengthLen = _readLength(string[1:])
numberBytes = string[1 + lengthLen:1 + lengthLen + length]
res... | 5,311,647 |
def get_urls():
"""The get_urls function fetches 16 urls from the database that need to be scraped by the bee.
The Url which are set with a priority in the database will be retrieved first.
"""
return select(u for u in Url if u.date_scraped is None).order_by(desc(Url.priority_scrape))[:8] | 5,311,648 |
def convert_input_to_userid(input_id):
"""
Take user input from app (Steam user ID or vanity URL) and output Steam user ID for further API calls ]
"""
req = Request('http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=%s&vanityurl=%s'%(api_key, input_id))
try:
data_raw = urlopen(req).read()
exc... | 5,311,649 |
def create_citydist(create_environment, create_building):
"""
Pytest fixture function to generate city district with three
res. buildings (with demands) on positions (0, 0), (0, 10), (10, 10)
Parameters
----------
create_environment : object
Environment object (as fixture of pytest)
... | 5,311,650 |
def create_db_cluster_snapshot(DBClusterSnapshotIdentifier=None, DBClusterIdentifier=None, Tags=None):
"""
Creates a snapshot of a DB cluster.
See also: AWS API Documentation
Exceptions
:example: response = client.create_db_cluster_snapshot(
DBClusterSnapshotIdentifier='string',
... | 5,311,651 |
def plot_abs(dataset,absMIN,absMAX):
"""Function to plot absorbance at all times
Args:
dataset representing the Dataset object
absMIN representing the minimum absorbance to plot
absMAX representing the maximum absorbance to plot
Returns:
none
"""
temp = dataset.abs_data
temp = te... | 5,311,652 |
def read_log(log_file, skip_log_rows=None, skip_log_conditions=None):
"""Reads the behavioral log file with information about each EEG trial."""
# Check if data are already in a DataFrame
if isinstance(log_file, pd.DataFrame):
log = log_file
else:
# Detect file encoding
with op... | 5,311,653 |
def sha1_base32(buf: bytes, n: int = None):
"""
Return a base32 representation of the first n bytes of SHA1(buf).
If n = None, the entire buffer will be encoded.
"""
return base32(hashlib.sha1(buf).digest()[slice(0, n)]) | 5,311,654 |
def inserir():
"""
Função para inserir um produto
"""
conn = conectar()
cursor = conn.cursor()
nome = str(input('Insira o Nome para o Cadastro: ')).strip().title()
sobrenome = str(input('Insira o Sobrenome para Cadastro: ')).strip().title()
sexo = str(input('Inser o Sexo [M/F]: '... | 5,311,655 |
def get_lsf_grid_name(fibre_number):
"""
Return the appropriate LSF name (a, b, c, or d) to use, given a mean fiber number.
:param fiber_number:
The mean fiber number of observations.
:returns:
A one-length string describing which LSF grid to use ('a', 'b', 'c', or 'd').
"""
... | 5,311,656 |
def get_named_layers_and_params_by_regex(
module: Module,
param_names: List[str],
params_strict: bool = False,
) -> List[NamedLayerParam]:
"""
:param module: the module to get the matching layers and params from
:param param_names: a list of names or regex patterns to match with full parameter
... | 5,311,657 |
def draw_box(to_draw, xmin, xmax, ymin, ymax, cname, cindex, class_colors, conf=None, extratext=""):
""" Draws a box on top of an image. The image is then returned.
Arguments:
to_draw -- image to draw on
xmin, xmax, ymin, ymax -- coordinates of the box
cname ... | 5,311,658 |
def _get_node(pending_set, pre_sel=[], opts={}):
""" Next node preferably in pre-selected nodes
"""
shuffle(pre_sel)
for node in pre_sel:
if node in pending_set:
pending_set.remove(node)
return node
# Random if not
return pending_set.pop() | 5,311,659 |
def callCounter(func):
"""function call counter"""
@functools.wraps(func)
def helper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
return helper | 5,311,660 |
def deprecated(func):
"""Print a deprecation warning once on first use of the function.
>>> @deprecated # doctest: +SKIP
... def f():
... pass
>>> f() # doctest: +SKIP
f is deprecated
"""
count = [0]
def wrapper(*args, **kwargs)... | 5,311,661 |
def eigsh(a, k=6, *, which='LM', ncv=None, maxiter=None, tol=0,
return_eigenvectors=True):
"""Finds ``k`` eigenvalues and eigenvectors of the real symmetric matrix.
Solves ``Ax = wx``, the standard eigenvalue problem for ``w`` eigenvalues
with corresponding eigenvectors ``x``.
Args:
... | 5,311,662 |
def calc_t_frame(n_col, n_row, n_amp, ins):
"""Calculates the frame time for a given ins/readmode/subarray.
Parameters
----------
n_col : int
Number of columns.
n_row : int
Number of rows.
n_amp : int
Amplifiers reading data.
ins : str
The instrument key.
... | 5,311,663 |
def verify_bytesio(enc_message, verify_key_hex, signature):
""" Verify asymmetrically signed bytesreams.
:param bytes enc_message: encrypted data
:param bytes verify_key_hex: serialized verification key
:param bytes signature: signature
"""
verify_key = nacl.signing.VerifyKey(verify_key_hex, en... | 5,311,664 |
def rest_error_message(error, jid):
"""Returns exception error message as valid JSON string to caller
:param error: Exception, error message
:param jid: string, job ID
:return: JSON string
"""
logging.exception(error)
e = str(error)
return json.dumps({'user_id': 'admin', 'result': {'erro... | 5,311,665 |
def typedefn_from_root_element(el: UxsdElement) -> str:
"""Generate a C++ class declaration of a root element,
which inherits its content type and adds load and write functions.
"""
out = ""
out += "/** Generated from:\n"
out += utils.to_comment_body(el.source)
out += "\n*/\n"
out += "class %s : public %s {\n" ... | 5,311,666 |
def test_url_request_timing():
"""test that the timing is right and we do not cause DoS. No cache
used."""
double_request() | 5,311,667 |
def store(url, date, content):
"""Store article in database."""
if type(date) is str: date = iso2ts(date)
return crawldb.add(url, content, version=date) | 5,311,668 |
def Dict(val):
"""
Build a dict for key/value pairs.
"""
return dict(val) | 5,311,669 |
def get_distracting_answer_by_visual7w_generation(qa_id, correct_answer, candidate_dict, res_cnt=3):
"""
Args:
qa_id: int
correct_answer: str
candidate_dict: dict of (id, candidate), generated by visual7w baseline model
"""
res = []
if qa_id not in candidate_dict:
pri... | 5,311,670 |
def sys_exit(res: int) -> None:
"""
Call the ``_exit()`` system call. This exits the calling thread, but does not terminate other
threads in the same process.
"""
libc.syscall(_SYS_EXIT, res)
assert False, "If we got here, something is very wrong" | 5,311,671 |
def diag(req, resp):
""" Data about the state of the database """
return {
'driver': engine.driver,
'tables': engine.table_names()
} | 5,311,672 |
def local_backup():
"""Local backups.
Move all existing <DB name>.N files one number up,
deleting the largest if maximum depth is reached
Then copy the current database to <DB name>.1,
encrypting if encryption is enabled
"""
conf = config.scripts.python.local_backup
number_name = lambd... | 5,311,673 |
def as_path(path: PathLike) -> ReadWritePath:
"""Create a generic `pathlib.Path`-like abstraction.
This function
Args:
path: Pathlike object.
Returns:
path: The `pathlib.Path`-like abstraction.
"""
if isinstance(path, str):
if os.name == 'nt' and not path.startswith('gs://'):
# On windo... | 5,311,674 |
def dc_loss(embedding, label):
"""
Deep clustering loss function.
Args:
embedding: (T,D)-shaped activation values
label: (T,C)-shaped labels
return:
(1,)-shaped squared flobenius norm of the difference
between embedding and label affinity matrices
"""
xp = cuda.get_array... | 5,311,675 |
def ScrapeAdMetadataByKeyword(CurrentSession, Seed, NumAds = 2000):
"""
Returns a list of dictionaries that includes metadata of the Ad and
also includes it's performance details. Our program crawls 5000
ads in the first iteration and then 500 ads in the subsequent
iterations. This is done to opti... | 5,311,676 |
def get_all_slots_metadata(player_id: str, page_size: int, consistent_read: bool, start_key: Optional[str]):
"""Get metadata for all save slots, or an empty list if no metadata is found."""
gamesaves_table = ddb.get_table(table_name=os.environ.get('GAMESAVES_TABLE_NAME'))
query_params = ddb.query_request_pa... | 5,311,677 |
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities):
"""Set up the platform from config_entry."""
# We should scan options for alert configs and then if at least 1 listener is enabled subscribe for the stream
hik_client = hass.data[const.DOMAIN][config_entry.entry... | 5,311,678 |
def image_pil2cv(img):
"""Convert a PIL image to an opencv image.
Args:
img (PIL image): A PIL image of uint8 between 0 and 255 using RGB channels.
Returns:
np.array: A numpy image loaded with opencv of uint8 between 0 and 255 using BGR channels.
Examples:
>>> img ... | 5,311,679 |
def _ww3_ounf_contents(run_date, run_type):
"""
:param run_date: :py:class:`arrow.Arrow`
:param str run_type:
:return: ww3_ounf.inp file contents
:rtype: str
"""
start_date = (
run_date.format("YYYYMMDD")
if run_type == "nowcast"
else run_date.shift(days=+1).format("... | 5,311,680 |
def _search(matrix: np.ndarray, tour: np.ndarray, x: int, y: int, z: int) -> Tuple[int, float]:
""" Поиск лучшей замены, среди всех возможных замен
matrix: Матрица весов
tour: Список городов
x, y, z: Города, для которых пробуем найти изменение тура
return: Тип переворота, выигрыш
"""
s = len... | 5,311,681 |
def test_more_edge_colors_than_num_edges_directed():
"""Test that extra edge colors are ignored when there are more specified
colors than edges."""
G = nx.path_graph(4, create_using=nx.DiGraph) # 3 edges
pos = nx.random_layout(barbell)
edgecolors = ("r", "g", "b", "c") # 4 edge colors
drawn_ed... | 5,311,682 |
def __build_transfer_paths(
requests_with_sources: "Iterable[RequestWithSources]",
multihop_rses: "List[str]",
schemes: "List[str]",
failover_schemes: "List[str]",
logger: "Callable" = logging.log,
session: "Optional[Session]" = None,
):
"""
For each request, find... | 5,311,683 |
def new_min_max(_builtin_func, *args, **kwargs):
"""
To support the argument "default" introduced in python 3.4 for min and max
:param _builtin_func: builtin min or builtin max
:param args:
:param kwargs:
:return: returns the min or max based on the arguments passed
"""
for key, _ in kw... | 5,311,684 |
def GewekeDiagPlot(M, dset, ax):
""" Get pvalues from geweke diagnostic from the dataset """
from statsmodels.sandbox.stats.multicomp import multipletests
from ..StoneHelper import geweke_chains
_, pvalues = geweke_chains(dset)
ptable = pd.DataFrame(pvalues, columns=FcgRlistL + texRenameList(M.pNa... | 5,311,685 |
def get_database_config(parsed: ConfigParser, manager: ConfigManager) -> dict:
"""
Generate a populated
configuration dictionary.
TODO: This should be shared
with dbManager.py.
:param parsed: ConfigParser
:param manager: ConfigManager
:return: Dictionary
"""
config: dict = {}
... | 5,311,686 |
def eigenvector_centrality(
G, max_iter=100, tol=1.0e-6, normalized=True
):
"""
Compute the eigenvector centrality for a graph G.
Eigenvector centrality computes the centrality for a node based on the
centrality of its neighbors. The eigenvector centrality for node i is the
i-th element of the ... | 5,311,687 |
def test_compare_newton_optimization_no_split_with_linear_gpu(num_iters=50):
"""Check if parallel linear layer without splitting behaves the same
as HBPLinear during optimization with Newton-style optimizer on GPU."""
if torch.cuda.is_available():
device = torch.device("cuda:0")
compare_newt... | 5,311,688 |
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT):
""" Returns the indefinite (ein) or definite (der/die/das/die) article for the given word.
"""
return function == DEFINITE \
and definite_article(word, gender, role) \
or indefinite_article(word, gender, role) | 5,311,689 |
def get_workbooks(server, auth_token, user_id, site_id):
"""
Queries all existing workbooks on the current site.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
'user_id' ID of user with access to workbooks
'si... | 5,311,690 |
async def faq(ctx):
"""
Send out the FAQ panel
:param ctx:
:return:
"""
await embeddirectory.send_faq_embed(ctx) | 5,311,691 |
def spawn_new_population_members(population, spawn_count, puzzle,
random_state):
"""
Create new population members using 50% crossover_and_mutate() and
50% copy_and_mutate(). New population members are written to the last
`spawn_count` rows of `population`.
:param ... | 5,311,692 |
def createEntries(sigs):
"""Gets a list of [filename, lineNumber, signature, namespaces] tupels.
Analyse signature and adds entries in FUNCS and CLASSES.
"""
completefile_lines = defaultdict(list)
noncompletefile_lines = defaultdict(list)
#print FILES_COMPLETELY_IORELATED
#print FUNCT... | 5,311,693 |
def dirty_image_generate(dirty_image_uv, mask = None, baseline_threshold = 0, normalization = None,
resize = None, width_smooth = None, degpix = None, not_real = False,
image_filter_fn = 'filter_uv_uniform', pad_uv_image = None, filter = None,
v... | 5,311,694 |
def includeme(config: Configurator) -> None:
"""Pyramid knob."""
from pyramid_mixpanel.consumer import MockedConsumer
from pyramid_mixpanel.track import mixpanel_flush
from pyramid_mixpanel.track import mixpanel_init
from pyramid_mixpanel.track import MixpanelTrack
mixpanel = MixpanelTrack(sett... | 5,311,695 |
def get_significant_states_with_session(
hass: HomeAssistant,
session: Session,
start_time: datetime,
end_time: datetime | None = None,
entity_ids: list[str] | None = None,
filters: Filters | None = None,
include_start_time_state: bool = True,
significant_changes_only: bool = True,
m... | 5,311,696 |
def vc_to_oct(solution):
"""Convert a VertexCover solution into an OCT solution.
This is done by undoing the graph doubling done to reduce
OCT to VC. The certificate is recovered as the vertes
whose counterparts are both in the VC certificate.
Parameters
----------
solution : Solution
... | 5,311,697 |
def class_of ( object ):
""" Returns a string containing the class name of an object with the
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
if isinstance( object, py3compat.string_types ):
return add_article( object )
return add_article( ob... | 5,311,698 |
async def test_filters(hass: HomeAssistant, client: MagicMock) -> None:
"""Test spa filters."""
config_entry = await init_integration(hass)
for filter_mode in range(4):
for spa_filter in range(1, 3):
state = await _patch_filter(
hass, config_entry, filter_mode, spa_filt... | 5,311,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.