id int64 11 59.9k | original stringlengths 33 150k | modified stringlengths 37 150k |
|---|---|---|
4,425 | def _temp_proj(ref_2, ref_1, raw_data, n_proj=6):
"""Remove common signal subspace of ref_2 and ref_1 from raw_data.
Parameters
----------
ref_2 : np.ndarray of float, shape (n_sensors_2, n_times)
The magnetometer data for CSS. Can use either all magnetometer data or
a few selected sens... | def _temp_proj(ref_2, ref_1, raw_data, n_proj=6):
"""Remove common signal subspace of ref_2 and ref_1 from raw_data.
Parameters
----------
ref_2 : np.ndarray of float, shape (n_sensors_2, n_times)
The magnetometer data for CSS. Can use either all magnetometer data or
a few selected sens... |
7,542 | def get_pkg_data_path(*path, package=None):
"""Make path from source-included data directories.
Parameters
----------
*path : str
Name/location of the desired data file/directory.
May be a tuple of strings -- for ``os.path`` intelligent path joining.
package : str, optional, keywor... | def get_pkg_data_path(*path, package=None):
"""Get path from source-included data directories.
Parameters
----------
*path : str
Name/location of the desired data file/directory.
May be a tuple of strings -- for ``os.path`` intelligent path joining.
package : str, optional, keyword... |
40,170 | def _compute_library_size(
data: Union[sp_sparse.spmatrix, np.ndarray]
) -> Tuple[np.ndarray, np.ndarray]:
sum_counts = data.sum(axis=1)
masked_log_sum = np.ma.log(sum_counts)
if np.ma.is_masked(masked_log_sum):
logger.warning(
"This dataset has some empty cells, this might fail scVI... | def _compute_library_size(
data: Union[sp_sparse.spmatrix, np.ndarray]
) -> Tuple[np.ndarray, np.ndarray]:
sum_counts = data.sum(axis=1)
masked_log_sum = np.ma.log(sum_counts)
if np.ma.is_masked(masked_log_sum):
logger.warning(
"This dataset has some empty cells, this might fail infe... |
33,041 | def qemu_check_kvm_support() -> bool:
kvm = Path("/dev/kvm")
if not kvm.exists():
return False
# some CI runners may present a non-working KVM device
try:
with kvm.open():
return True
except OSError:
return False
| def qemu_check_kvm_support() -> bool:
kvm = Path("/dev/kvm")
if not kvm.is_char_device():
return False
# some CI runners may present a non-working KVM device
try:
with kvm.open():
return True
except OSError:
return False
|
32,487 | def validate_and_parse_detection_start_end_time(args: Dict[str, Any]) -> Tuple[Optional[datetime], Optional[datetime]]:
"""
Validate and return detection_start_time and detection_end_time as per Chronicle Backstory or \
raise a ValueError if the given inputs are invalid.
:type args: dict
:param arg... | def validate_and_parse_detection_start_end_time(args: Dict[str, Any]) -> Tuple[Optional[datetime], Optional[datetime]]:
"""
Validate and return detection_start_time and detection_end_time as per Chronicle Backstory or \
raise a ValueError if the given inputs are invalid.
:type args: dict
:param arg... |
13,913 | def _find_excluded_ranges(
lines: List[Tuple[int, str]],
*,
warnings: _ExclusionRangeWarnings,
exclude_lines_by_pattern: Optional[str] = None,
exclude_branches_by_pattern: Optional[str] = None,
exclude_pattern_prefix: str,
) -> Callable[[int], bool]:
"""
Scan through all lines to find li... | def _find_excluded_ranges(
lines: List[Tuple[int, str]],
*,
warnings: _ExclusionRangeWarnings,
exclude_lines_by_pattern: Optional[str] = None,
exclude_branches_by_pattern: Optional[str] = None,
exclude_pattern_prefix: str,
) -> Callable[[int], bool]:
"""
Scan through all lines to find li... |
34,409 | def get_entity_extractors(interpreter: Interpreter) -> Set[Text]:
"""Finds the names of entity extractors used by the interpreter.
Processors are removed since they do not detect the boundaries themselves.
"""
from rasa.nlu.extractors.extractor import EntityExtractor
extractors = set()
for c i... | def get_entity_extractors(interpreter: Interpreter) -> Set[Text]:
"""Finds the names of entity extractors used by the interpreter.
Processors are removed since they do not detect the boundaries themselves.
"""
from rasa.nlu.extractors.extractor import EntityExtractor
extractors = set()
for c i... |
37,946 | def test_project_generate():
"""
Run project by passing in a pandas.DataFrame as input.
"""
output = project(center=[0, -1], endpoint=[0, 1], flat_earth=True, generate=0.5)
assert isinstance(output, pd.DataFrame)
assert output.shape == (5, 3)
npt.assert_allclose(output.iloc[1], [3.061617e-17... | def test_project_generate():
"""
Run project by passing in center and endpoint as input.
"""
output = project(center=[0, -1], endpoint=[0, 1], flat_earth=True, generate=0.5)
assert isinstance(output, pd.DataFrame)
assert output.shape == (5, 3)
npt.assert_allclose(output.iloc[1], [3.061617e-1... |
27,950 | def generate_ast(triple_arch, action, source, config, env):
""" Generates ASTs for the current compilation command. """
ast_joined_path = os.path.join(config.ctu_dir, triple_arch, 'ast',
os.path.realpath(source)[1:] + '.ast')
ast_path = os.path.abspath(ast_joined_path)
... | def generate_ast(triple_arch, action, source, config, env):
""" Generates ASTs for the current compilation command. """
ast_joined_path = os.path.join(config.ctu_dir, triple_arch, 'ast',
os.path.realpath(source)[1:] + '.ast')
ast_path = os.path.abspath(ast_joined_path)
... |
44,364 | def test_vmc_functions():
ha, sx, ma, sampler, driver = _setup_vmc()
driver.advance(500)
assert driver.energy.mean == approx(ma.expect(ha).mean, abs=1e-5)
state = ma.to_array()
n_samples = 16000
ma.n_samples = n_samples
ma.n_discard_per_chain = 100
# Check zero gradieent
_, grad... | def test_vmc_functions():
ha, sx, ma, sampler, driver = _setup_vmc()
driver.advance(500)
assert driver.energy.mean == approx(ma.expect(ha).mean, abs=1e-5)
state = ma.to_array()
n_samples = 16000
ma.n_samples = n_samples
ma.n_discard_per_chain = 100
# Check zero gradient
_, grads... |
59,386 | def test_redact():
redacted = wandb_settings._redact_dict({"this": 2, "that": 9, "api_key": "secret"})
assert redacted == {"this": 2, "that": 9, "api_key": "***REDACTED***"}
redacted = wandb_settings._redact_dict(
{"ok": "keep", "unsafe": 9, "bad": "secret"},
unsafe_keys={"unsafe", "bad"},
... | def test_redact():
redacted = wandb_settings._redact_dict({"this": 2, "that": 9, "api_key": "secret"})
assert redacted == {"this": 2, "that": 9, "api_key": "***REDACTED***"}
redacted = wandb_settings._redact_dict({"this": 2, "that": 9})
assert redacted == {"this": 2, "that": 9}
redacted = wandb_sett... |
32,183 | def extract_trigger_kv(trigger_events: list):
"""
The main information about the alert is more convenient to have as key/value pairs
instead of using field weights as it makes writing mapping for individual values easier.
"""
trigger_event = None
for event in trigger_events:
if event.get... | def extract_trigger_kv(trigger_events: list):
"""
The main information about the alert is more convenient to have as key/value pairs
instead of using field weights as it makes writing mapping for individual values easier.
"""
trigger_event = None
for event in trigger_events:
if event.get... |
10,866 | def ini_check ():
"""set environmental variable and change directory"""
# Note:
# hal_gremlin gets INI file from os.environ (only)
# hal_gremlin expects cwd to be same as INI file
ini_filename = get_linuxcnc_ini_file()
if ini_filename is not None:
os.putenv('INI_FILE_NAME',ini_filena... | def ini_check ():
"""set environmental variable and change directory"""
# Note:
# hal_gremlin gets INI file from os.environ (only)
# hal_gremlin expects cwd to be same as INI file
ini_filename = get_linuxcnc_ini_file()
if ini_filename is not None:
os.putenv('INI_FILE_NAME',ini_filena... |
27,314 | def compute_authenticator(raw_payload: Union[bytes, bytearray],
dbmsg: Message,
authenticator_fn: Callable[[Message,
bytearray,
int],
... | def compute_authenticator(raw_payload: Union[bytes, bytearray],
dbmsg: Message,
authenticator_fn: Callable[[Message,
bytearray,
int],
... |
59,851 | def fake_random_ds(
ndims,
peak_value=1.0,
fields=None,
units=None,
particle_fields=None,
particle_field_units=None,
negative=False,
nprocs=1,
particles=0,
length_unit=1.0,
unit_system="cgs",
bbox=None,
):
from yt.loaders import load_uniform_grid
if fields is not... | def fake_random_ds(
ndims,
peak_value=1.0,
fields=None,
units=None,
particle_fields=None,
particle_field_units=None,
negative=False,
nprocs=1,
particles=0,
length_unit=1.0,
unit_system="cgs",
bbox=None,
):
from yt.loaders import load_uniform_grid
if (fields, unit... |
38,454 | def merge_grids_of_equal_dim(gb):
"""Merges all grids that have the same dimension in the GridBucket. Thus
the returned GridBucket only has one grid per dimension. See also
pp.utils.grid_utils.merge_grids(grids).
Parameters:
gb (pp.GridBucket): A Grid bucket with possible many grids per dimension
... | def merge_grids_of_equal_dim(gb: pp.GridBucket) -> pp.GridBucket:
"""Merges all grids that have the same dimension in the GridBucket. Thus
the returned GridBucket only has one grid per dimension. See also
pp.utils.grid_utils.merge_grids(grids).
Parameters:
gb (pp.GridBucket): A Grid bucket with pos... |
30,119 | def distance_to_identity(dist, d_low=None, d_high=None):
"""
ANI = 1-distance
"""
if not 0 <= dist <= 1:
raise ValueError(f"Error: distance value {dist} is not between 0 and 1!")
ident = 1 - dist
result = ident
id_low, id_high = None, None
if any([d_low is not None, d_high is not... | def distance_to_identity(dist, *, d_low=None, d_high=None):
"""
ANI = 1-distance
"""
if not 0 <= dist <= 1:
raise ValueError(f"Error: distance value {dist} is not between 0 and 1!")
ident = 1 - dist
result = ident
id_low, id_high = None, None
if any([d_low is not None, d_high is ... |
28,839 | def as_chunks(max_size: int, iterator: _Iter[T]) -> _Iter[List[T]]:
"""A helper function that collects an iterator into chunks of a given size.
.. versionadded:: 2.0
Parameters
----------
max_size: :class:`int`
The maximum chunk size.
iterator: Union[:class:`Iterator`, :class:`... | def as_chunks(max_size: int, iterator: _Iter[T]) -> _Iter[List[T]]:
"""A helper function that collects an iterator into chunks of a given size.
.. versionadded:: 2.0
Parameters
----------
max_size: :class:`int`
The maximum chunk size.
iterator: Union[:class:`collections.abc.Ite... |
32,012 | def parse_incident_from_item(item):
"""
Parses an incident from an item
:param item: item to parse
:return: Parsed item
"""
incident = {}
labels = []
try:
incident["details"] = item.text_body or item.body
except AttributeError:
incident["details"] = item.body
inc... | def parse_incident_from_item(item):
"""
Parses an incident from an item
:param item: item to parse
:return: Parsed item
"""
incident = {}
labels = []
try:
incident["details"] = item.text_body or item.body
except AttributeError:
incident["details"] = item.body
inc... |
54,721 | def _flag_missing_timestamps(
df: pd.DataFrame,
frequency: str,
column_name: str,
first_time_stamp: pd.Timestamp,
last_time_stamp: pd.Timestamp,
) -> namedtuple:
"""
Utility function to test if input data frame is missing any timestamps relative to expected timestamps
generated based on ... | def _flag_missing_timestamps(
df: pd.DataFrame,
frequency: str,
column_name: str,
first_time_stamp: pd.Timestamp,
last_time_stamp: pd.Timestamp,
) -> namedtuple:
"""
Utility function to test if input data frame is missing any timestamps relative to expected timestamps
generated based on ... |
57,681 | def map_scim(clientData):
try:
clientData = json.loads(clientData)
except Exception:
pass
if type(clientData) != dict:
raise Exception('Provided client data is not JSON compatible')
scim_extension = INPUT_SCIM_EXTENSION_KEY.replace('.', '\.')
mapping = {
"active": "a... | def map_scim(client_data):
try:
client_data = json.loads(client_data)
except Exception:
pass
if type(client_data) != dict:
raise Exception('Provided client data is not JSON compatible')
scim_extension = INPUT_SCIM_EXTENSION_KEY.replace('.', '\.')
mapping = {
"active"... |
33,134 | def rk4(f, x, t, dt, stages=4, s=0):
"""Runge-Kutta (explicit, non-adaptive) numerical (S)ODE solvers.
The rule has strong / weak convergence order 1.0 for generic SDEs and order 4.0
convergence for ODEs when stages=4. For stages=1, this becomes the Euler-Maruyama
schemefor SDEs (s > 0.0) with strong ... | def rk4(f, x, t, dt, stages=4, s=0):
"""Runge-Kutta (explicit, non-adaptive) numerical (S)ODE solvers.
The rule has strong / weak convergence order 1.0 for generic SDEs and order 4.0
convergence for ODEs when stages=4. For stages=1, this becomes the Euler-Maruyama
schemefor SDEs (s > 0.0) with strong ... |
15,725 | def gather_new_integration(determine_auth: bool) -> Info:
"""Gather info about new integration from user."""
fields = {
"name": {
"prompt": "What is the name of your integration?",
"validators": [CHECK_EMPTY],
},
"codeowner": {
"prompt": "What is your ... | def gather_new_integration(determine_auth: bool) -> Info:
"""Gather info about new integration from user."""
fields = {
"name": {
"prompt": "What is the name of your integration?",
"validators": [CHECK_EMPTY],
},
"codeowner": {
"prompt": "What is your ... |
30,953 | def create_user_iam(default_base_dn, default_page_size, args):
assert conn is not None
user_profile = args.get("user-profile")
user_profile_delta = args.get('user-profile-delta')
iam_user_profile = IAMUserProfile(user_profile=user_profile, user_profile_delta=user_profile_delta)
ad_user = iam_user_... | def create_user_iam(default_base_dn, default_page_size, args):
assert conn is not None
user_profile = args.get("user-profile")
user_profile_delta = args.get('user-profile-delta')
iam_user_profile = IAMUserProfile(user_profile=user_profile, user_profile_delta=user_profile_delta)
ad_user = iam_user_... |
45,736 | def _linda_forecast(
precip,
precip_lagr_diff,
timesteps,
fct_gen,
precip_pert_gen,
vel_pert_gen,
n_ensemble_members,
seed,
measure_time,
print_info,
return_output,
callback,
):
"""Compute LINDA nowcast."""
# compute convolved difference fields
precip_lagr_dif... | def _linda_forecast(
precip,
precip_lagr_diff,
timesteps,
forecast_gen,
precip_pert_gen,
vel_pert_gen,
n_ensemble_members,
seed,
measure_time,
print_info,
return_output,
callback,
):
"""Compute LINDA nowcast."""
# compute convolved difference fields
precip_lag... |
56,815 | def group_dataset_datavalues(
dataset,
datavalues_list
) -> list:
"""
This function evaluates a few cases regarding the 'period' and 'orgUnit':
Considerations:
The 'period' and 'orgUnit' must be on specified on the same level as the 'completeDate',
thus ... | def group_dataset_datavalues(
dataset,
datavalues_list
) -> list:
"""
This function evaluates a few cases regarding the 'period' and 'orgUnit':
Considerations:
The 'period' and 'orgUnit' must be on specified on the same level as the 'completeDate',
thus ... |
4,165 | def combine_evoked(all_evoked, weights):
"""Merge evoked data by weighted addition or subtraction.
Data should have the same channels and the same time instants.
Subtraction can be performed by calling
``combine_evoked([evoked1, -evoked2], 'equal')``
.. warning:: If you pass negative weights, it
... | def combine_evoked(all_evoked, weights):
"""Merge evoked data by weighted addition or subtraction.
Data should have the same channels and the same time instants.
Subtraction can be performed by calling
``combine_evoked([evoked1, -evoked2], 'equal')``
.. warning:: If you pass negative weights, it
... |
30,715 | def list_accounts(client, args):
title = f'{INTEGRATION_NAME} - List of the Accounts'
raws = []
cyberark_ec = []
raw_response = client.get_accounts(offset=args['offset'], limit=args['limit'])['value']
if raw_response:
for item in raw_response:
raws.append(item)
cyber... | def list_accounts(client, args):
title = f'{INTEGRATION_NAME} - List of the Accounts'
raws = []
cyberark_ec = []
raw_response = client.get_accounts(offset=args['offset'], limit=args['limit'])['value']
if raw_response:
for item in raw_response:
raws.append(item)
cyber... |
13,590 | def rand_QB(A, target_rank=None, distribution='normal', oversampling=0, powerIterations=0):
"""
randomisierte QB-Zerlegung
See Algorithm 3.1 in [EMKB19]_.
Parameters
----------
A :
The |VectorArray| for which the randomized QB Decomposition is to be computed.
target_rank : int
... | def rand_QB(A, target_rank=None, distribution='normal', oversampling=0, powerIterations=0):
"""
randomisierte QB-Zerlegung
See Algorithm 3.1 in [EMKB19]_.
Parameters
----------
A :
The |VectorArray| for which the randomized QB Decomposition is to be computed.
target_rank : int
... |
40,145 | def create_data_graph_nodes_and_groups(data, parent_uid, root_uid, whitelist):
data_graph = {
'nodes': [],
'edges': [],
'groups': []
}
groups = []
for file in data:
mime = file['processed_analysis']['file_type']['mime']
if mime not in whitelist or root_uid not i... | def create_data_graph_nodes_and_groups(data, parent_uid, root_uid, whitelist):
data_graph = {
'nodes': [],
'edges': [],
'groups': []
}
groups = []
for file in data:
mime = file['processed_analysis']['file_type']['mime']
if mime not in whitelist or root_uid not i... |
30,854 | def format_sort(sort_str: str) -> list:
"""
Format a sort string from "field1:asc,field2:desc" to a list accepted by pymongo.sort()
"field1:asc,field2:desc" => [("field1",1),("field2",-1)]
Args:
sort_str: a sort detailed as a string
Returns:
list accepted by pymongo.sort()
"""
... | def format_sort(sort_str: str) -> list:
"""
Format a sort string from "field1:asc,field2:desc" to a list accepted by pymongo.sort()
"field1:asc,field2:desc" => [("field1",1),("field2",-1)]
Args:
sort_str: a sort detailed as a string
Returns:
list accepted by pymongo.sort()
"""
... |
28,012 | def convert_reports(reports: Report, repo_dirs: List[str]) -> Dict:
"""Convert the given reports to codeclimate format.
This function will convert the given report to Code Climate format.
reports - list of reports type Report
repo_dir - Root directory of the sources, i.e. the directory where the
... | def convert_reports(reports: List[Report], repo_dirs: List[str]) -> Dict:
"""Convert the given reports to codeclimate format.
This function will convert the given report to Code Climate format.
reports - list of reports type Report
repo_dir - Root directory of the sources, i.e. the directory where the
... |
32,270 | def fetch_incidents(client: Client) -> list:
query_params = {}
incidents = []
last_run = demisto.getLastRun()
date_format = '%Y-%m-%d %H:%M:%S'
start_snow_time, _ = get_fetch_run_time_range(
last_run=last_run, first_fetch=client.fetch_time, look_back=client.look_back, date_format=date_form... | def fetch_incidents(client: Client) -> list:
query_params = {}
incidents = []
last_run = demisto.getLastRun()
date_format = '%Y-%m-%d %H:%M:%S'
start_snow_time, _ = get_fetch_run_time_range(
last_run=last_run, first_fetch=client.fetch_time, look_back=client.look_back, date_format=date_form... |
11,310 | def _get_secret_key(response):
# type: (PipelineResponse) -> str
# expecting header containing path to secret key file
header = response.http_response.headers.get("Www-Authenticate")
if header is None:
raise CredentialUnavailableError(message="Did not receive a value from Www-Authenticate header... | def _get_secret_key(response):
# type: (PipelineResponse) -> str
# expecting header containing path to secret key file
header = response.http_response.headers.get("Www-Authenticate")
if header is None:
raise CredentialUnavailableError(message="Did not receive a value from Www-Authenticate header... |
1,361 | def plot_dendrogram(model, **kwargs):
# Create linkage matrix and then plot the dendrogram
# create the counts of samples in each node
counts = np.zeros(model.children_.shape[0])
n_samples = len(model.labels_)
for i, merge in enumerate(model.children_):
current_count = 0
for j in [0... | def plot_dendrogram(model, **kwargs):
# Create linkage matrix and then plot the dendrogram
# create the counts of samples in each node
counts = np.zeros(model.children_.shape[0])
n_samples = len(model.labels_)
for i, merge in enumerate(model.children_):
current_count = 0
for j in [0... |
39,712 | def _is_resolved(what):
return (what is None or isinstance(what, (dict, list)))
| def _is_resolved(what):
return isinstance(what, (dict, list, NoneType))
|
12,995 | def set_total_prices(apps, schema_editor):
OrderLine = apps.get_model("order", "OrderLine")
lines = []
for line in OrderLine.objects.filter(total_price_gross_amount__isnull=True):
line.total_price_gross_amount = line.unit_price_gross_amount * line.quantity
line.total_price_net_amount = line.... | def set_total_prices(apps, schema_editor):
OrderLine = apps.get_model("order", "OrderLine")
lines = []
for line in OrderLine.objects.filter(total_price_gross_amount__isnull=True).iterator():
line.total_price_gross_amount = line.unit_price_gross_amount * line.quantity
line.total_price_net_amo... |
46,184 | def check_layout_layers(layout, layers):
"""
Check the layer widget order matches the layers order in the layout
Parameters
----------
layout : QLayout
Layout to test
layers : napar.components.LayersList
LayersList to compare to
Returns
----------
match : bool
... | def check_layout_layers(layout, layers):
"""
Check the layer widget order matches the layers order in the layout
Parameters
----------
layout : QLayout
Layout to test
layers : napari.components.LayersList
LayersList to compare to
Returns
----------
match : bool
... |
39,160 | def _get_packages():
exclude = [
"build*",
"test*",
"torchaudio.csrc*",
"third_party*",
"build_tools*",
]
exclude_prototype = False
branch_name = _run_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
is_on_tag = _run_cmd(['git', 'describe', '--tags', '--exact... | def _get_packages():
exclude = [
"build*",
"test*",
"torchaudio.csrc*",
"third_party*",
"tools*",
]
exclude_prototype = False
branch_name = _run_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
is_on_tag = _run_cmd(['git', 'describe', '--tags', '--exact-match... |
58,296 | def log_umount_blockers(mount: Path) -> None:
blockers: List[Tuple[str, Path]] = []
for d in Path("/proc").iterdir():
if not d.is_dir():
continue
try:
int(d.name)
except ValueError:
continue
if not d.joinpath("fd").exists():
cont... | def log_umount_blockers(mount: Path) -> None:
blockers: List[Tuple[str, Path]] = []
for d in Path("/proc").iterdir():
if not d.is_dir():
continue
if not d.name.isdigit():
continue
if not d.joinpath("fd").exists():
continue
comm = d.joinpath... |
3,548 | def _get_doc_content(project, version, doc):
storage_path = project.get_storage_path(
'json',
version_slug=version.slug,
include_file=False,
version_type=version.type,
)
file_path = build_media_storage.join(storage_path, f'{doc}.fjson')
try:
with build_media_stora... | def _get_doc_content(project, version, doc):
storage_path = project.get_storage_path(
'json',
version_slug=version.slug,
include_file=False,
version_type=version.type,
)
file_path = build_media_storage.join(storage_path, f'{doc}.fjson')
try:
with build_media_stora... |
31,397 | def main():
"""
PARSE AND VALIDATE INTEGRATION PARAMS
"""
params = demisto.params()
username = params.get('credentials').get('identifier')
password = params.get('credentials').get('password')
# get the service API url
base_url = params.get('server_url')
verify_certificate = not... | def main():
"""
PARSE AND VALIDATE INTEGRATION PARAMS
"""
params = demisto.params()
username = params.get('credentials').get('identifier')
password = params.get('credentials').get('password')
# get the service API url
base_url = params.get('server_url')
verify_certificate = not... |
31,839 | def checkpoint_delete_objects_batch_command(client: Client, object_type: str, name):
printable_result = {}
readable_output = ''
name = argToList(name)
del_list = []
for n in name:
tmp_dict = {'name': n}
del_list.append(tmp_dict)
result = current_result = client.delete_objects_b... | def checkpoint_delete_objects_batch_command(client: Client, object_type: str, name):
printable_result = {}
readable_output = ''
name = argToList(name)
objects_to_delete = [{'name':object_name} for object_name in object_names]
result = current_result = client.delete_objects_batch(object_type, del_l... |
53,832 | def handle_exception(ex): # pylint: disable=too-many-return-statements
# For error code, follow guidelines at https://docs.python.org/2/library/sys.html#sys.exit,
from jmespath.exceptions import JMESPathTypeError
from msrestazure.azure_exceptions import CloudError
from msrest.exceptions import HttpOper... | def handle_exception(ex): # pylint: disable=too-many-return-statements
# For error code, follow guidelines at https://docs.python.org/2/library/sys.html#sys.exit,
from jmespath.exceptions import JMESPathTypeError
from msrestazure.azure_exceptions import CloudError
from msrest.exceptions import HttpOper... |
23,667 | def parse_psm3(fbuf, map_variables):
"""
Parse an NSRDB PSM3 weather file (formatted as SAM CSV). The NSRDB
is described in [1]_ and the SAM CSV format is described in [2]_.
.. versionchanged:: 0.9.0
The function now returns a tuple where the first element is a dataframe
and the second el... | def parse_psm3(fbuf, map_variables=None):
"""
Parse an NSRDB PSM3 weather file (formatted as SAM CSV). The NSRDB
is described in [1]_ and the SAM CSV format is described in [2]_.
.. versionchanged:: 0.9.0
The function now returns a tuple where the first element is a dataframe
and the seco... |
2,625 | def power_transform(X, method="yeo-johnson", *, standardize=True, copy=True):
"""
Family of parametric, monotonic transformations to make data more Gaussian-like.
Power transforms are a family of parametric, monotonic transformations
that are applied to make data more Gaussian-like. This is useful ... | def power_transform(X, method="yeo-johnson", *, standardize=True, copy=True):
"""Parametric, monotonic transformation to make data more Gaussian-like.
Power transforms are a family of parametric, monotonic transformations
that are applied to make data more Gaussian-like. This is useful for
modeling... |
724 | def _get_handler(settings):
""" Return a log handler object according to settings """
filename = settings.get('LOG_FILE')
if filename:
encoding = settings.get('LOG_ENCODING')
if settings.get("LOG_ROTATING") is True:
max_bytes = settings.get('LOG_MAX_BYTES', 0)
log_bac... | def _get_handler(settings):
""" Return a log handler object according to settings """
filename = settings.get('LOG_FILE')
if filename:
encoding = settings.get('LOG_ENCODING')
if settings.getbool("LOG_ROTATING") is True:
max_bytes = settings.get('LOG_MAX_BYTES', 0)
log... |
22,718 | def _prepare_environ(workspace):
new_environ = os.environ.copy()
new_environ['TMPDIR'] = workspace
# So, pytest is nice, and a little to for our usage.
# In order to help user to call seamlessly any piece of python code without requiring to
# install it as a full-fledged setuptools distribution for... | def _prepare_environ(workspace):
new_environ = os.environ.copy()
new_environ['TMPDIR'] = workspace
# So, pytest is nice, and a little too nice for our usage.
# In order to help user to call seamlessly any piece of python code without requiring to
# install it as a full-fledged setuptools distributi... |
569 | def get_user_id(form_id):
key = f'xform-{form_id}-user_id'
user_id = cache.get(key)
if not user_id:
try:
user_id = FormAccessorSQL.get_form(form_id).metadata.userID
except XFormNotFound:
return None
cache.set(key, user_id, 12 * 60 * 60)
return user_id
| def get_user_id(form_id):
key = f'xform-{form_id}-user_id'
user_id = cache.get(key)
if not user_id:
try:
user_id = FormAccessorSQL.get_form(form_id).user_id
except XFormNotFound:
return None
cache.set(key, user_id, 12 * 60 * 60)
return user_id
|
38,816 | def main(args):
"""
function for the initial repositories fetch and manual repositories updates
"""
if not args:
_show_usage()
sys.exit(0)
logdir = os.path.dirname(CONFIG["path.log.fetch"])
if not os.path.exists(logdir):
os.makedirs()
logging.basicConfig(
f... | def main(args):
"""
function for the initial repositories fetch and manual repositories updates
"""
if not args:
_show_usage()
sys.exit(0)
logdir = os.path.dirname(CONFIG["path.log.fetch"])
if not os.path.exists(logdir):
os.makedirs(logdir)
logging.basicConfig(
... |
43,811 | def _inner_out_flow_constraint_hamiltonian(
graph: nx.DiGraph, node: int
) -> Tuple[List[float], List[qml.operation.Observable]]:
r"""Calculates the expanded inner portion of the Hamiltonian in :func:`out_flow_constraint`.
For a given :math:`i`, this function returns:
.. math::
d_{i}^{out}(d_... | def _inner_out_flow_constraint_hamiltonian(
graph: nx.DiGraph, node: int
) -> Tuple[List[float], List[qml.operation.Observable]]:
r"""Calculates the inner portion of the Hamiltonian in :func:`out_flow_constraint`.
For a given :math:`i`, this function returns:
.. math::
d_{i}^{out}(d_{i}^{out}... |
9,071 | def _receive_cap_nak(bot: SopelWrapper, trigger: Trigger) -> None:
was_completed = bot.cap_requests.is_complete
cap_ack = bot.capabilities.handle_nak(bot, trigger)
try:
result: Optional[
List[Tuple[bool, Optional[plugin.CapabilityNegotiation]]]
] = bot.cap_requests.deny(bot, cap... | def _receive_cap_nak(bot: SopelWrapper, trigger: Trigger) -> None:
was_completed = bot.cap_requests.is_complete
cap_ack = bot.capabilities.handle_nak(bot, trigger)
try:
result: Optional[
List[Tuple[bool, Optional[plugin.CapabilityNegotiation]]]
] = bot.cap_requests.deny(bot, cap... |
32,770 | def _api_template_string(wrapped, instance, args, kwargs):
tracer = _get_tracer(instance)
with tracer.trace("responder.render_template"):
return wrapped(*args, **kwargs)
| def _api_template_string(wrapped, instance, args, kwargs):
tracer = _get_tracer(instance)
with tracer.trace("responder.render_template", span_type=SpanTypes.TEMPLATE):
return wrapped(*args, **kwargs)
|
3,050 | def test_type_error_complex_index_non_scalar_return():
# GH 31605
def fct(group):
return group[1].values.flatten()
df = pd.DataFrame([("A", 1), ("A", 2), ("A", 3), ("B", 4), ("B", 5), ("C", np.nan)])
result = df.groupby(0).apply(fct)
expected = pd.Series(
[[1.0, 2.0, 3.0], [4.0, 5.0... | def test_apply_function_returns_numpy_array():
# GH 31605
def fct(group):
return group[1].values.flatten()
df = pd.DataFrame([("A", 1), ("A", 2), ("A", 3), ("B", 4), ("B", 5), ("C", np.nan)])
result = df.groupby(0).apply(fct)
expected = pd.Series(
[[1.0, 2.0, 3.0], [4.0, 5.0], [np.n... |
30,555 | def fetch_incidents(service):
last_run = demisto.getLastRun() and demisto.getLastRun()['time']
search_offset = demisto.getLastRun().get('offset', 0)
incidents = []
current_time_for_fetch = datetime.utcnow()
if demisto.get(demisto.params(), 'timezone'):
timezone = demisto.params()['timezone'... | def fetch_incidents(service):
last_run = demisto.getLastRun() and demisto.getLastRun()['time']
search_offset = demisto.getLastRun().get('offset', 0)
incidents = []
current_time_for_fetch = datetime.utcnow()
if demisto.get(demisto.params(), 'timezone'):
timezone = demisto.params()['timezone'... |
31,973 | def convert_to_unicode(s, is_msg_header=True):
global ENCODINGS_TYPES
try:
res = '' # utf encoded result
if is_msg_header: # Mime encoded words used on message headers only
try:
word_mime_encoded = s and MIME_ENCODED_WORD.search(s)
if word_mime_encod... | def convert_to_unicode(s, is_msg_header=True):
global ENCODINGS_TYPES
try:
res = '' # utf encoded result
if is_msg_header: # Mime encoded words used on message headers only
try:
word_mime_encoded = s and MIME_ENCODED_WORD.search(s)
if word_mime_encod... |
20,560 | def main(argv=None):
parser = get_parser()
arguments = parser.parse_args(argv)
verbose = arguments.v
set_loglevel(verbose=verbose)
# See if there's a configuration file and import those options
if arguments.config is not None:
print('configuring')
with open(arguments.config, 'r'... | def main(argv=None):
parser = get_parser()
arguments = parser.parse_args(argv)
verbose = arguments.v
set_loglevel(verbose=verbose)
# See if there's a configuration file and import those options
if arguments.config is not None:
print('configuring')
with open(arguments.config, 'r'... |
55,418 | def run(
uri,
entry_point="main",
version=None,
parameters=None,
docker_args=None,
experiment_name=None,
experiment_id=None,
backend="local",
backend_config=None,
use_conda=None,
storage_dir=None,
synchronous=True,
run_id=None,
run_name=None,
env_manager=None,... | def run(
uri,
entry_point="main",
version=None,
parameters=None,
docker_args=None,
experiment_name=None,
experiment_id=None,
backend="local",
backend_config=None,
use_conda=None,
storage_dir=None,
synchronous=True,
run_id=None,
run_name=None,
env_manager=None,... |
43,229 | def test_batch():
assert list(Batch()) == []
assert Batch().is_empty()
assert not Batch(b={'c': {}}).is_empty()
assert Batch(b={'c': {}}).is_empty(recurse=True)
assert not Batch(a=Batch(), b=Batch(c=Batch())).is_empty()
assert Batch(a=Batch(), b=Batch(c=Batch())).is_empty(recurse=True)
asser... | def test_batch():
assert list(Batch()) == []
assert Batch().is_empty()
assert not Batch(b={'c': {}}).is_empty()
assert Batch(b={'c': {}}).is_empty(recurse=True)
assert not Batch(a=Batch(), b=Batch(c=Batch())).is_empty()
assert Batch(a=Batch(), b=Batch(c=Batch())).is_empty(recurse=True)
asser... |
4,549 | def create_fake_bids_dataset(base_dir='', n_sub=10, n_ses=2,
tasks=['localizer', 'main'],
n_runs=[1, 3], with_derivatives=True,
with_confounds=True,
confounds_tag="desc-confounds_timeseries",
... | def create_fake_bids_dataset(base_dir='', n_sub=10, n_ses=2,
tasks=['localizer', 'main'],
n_runs=[1, 3], with_derivatives=True,
with_confounds=True,
confounds_tag="desc-confounds_timeseries",
... |
45,203 | def file_open(file_path, mode="rb", kwargs=None):
if isinstance(file_path, str):
match = S3_ADDRESS_REGEX.search(file_path)
if match:
import s3fs as S3FS
from botocore.exceptions import NoCredentialsError
s3fs = S3FS.S3FileSystem(anon=False)
try:
... | def file_open(file_path, mode="rb", kwargs=None):
if isinstance(file_path, str):
match = S3_ADDRESS_REGEX.search(file_path)
if match:
import s3fs as S3FS
from botocore.exceptions import NoCredentialsError
s3fs = S3FS.S3FileSystem(anon=False)
try:
... |
56,415 | def get_other_source_component_file_query(session):
""" Get filter query for the auto-generated Others component.
If there are no user defined source components in the database this
function will return with None.
The returned query will look like this:
(Files NOT IN Component_1) AND (Files NOT... | def get_other_source_component_file_query(session):
""" Get filter query for the auto-generated Others component.
If there are no user defined source components in the database this
function will return with None.
The returned query will look like this:
(Files NOT LIKE Component_1) AND (Files N... |
31,656 | def main():
params = demisto.params()
args = demisto.args()
url = params.get('url')
verify_certificate = not params.get('insecure', False)
proxy = params.get('proxy', False)
headers = {}
mock_data = str(args.get('mock-data', ''))
if mock_data.lower() == "true":
headers['Mock-Data... | def main():
params = demisto.params()
args = demisto.args()
url = params.get('url')
verify_certificate = not params.get('insecure', False)
proxy = params.get('proxy', False)
headers = {}
mock_data = str(args.get('mock-data', ''))
if mock_data.lower() == "true":
headers['Mock-Data... |
21,206 | def test_prex_builder_script_from_pex_path(tmpdir):
# type: (Any) -> None
pex_with_script = os.path.join(str(tmpdir), "script.pex")
with built_wheel(
name="my_project",
entry_points={"console_scripts": ["my_app = my_project.my_module:do_something"]},
) as my_whl:
pb = PEXBuilder... | def test_pex_builder_script_from_pex_path(tmpdir):
# type: (Any) -> None
pex_with_script = os.path.join(str(tmpdir), "script.pex")
with built_wheel(
name="my_project",
entry_points={"console_scripts": ["my_app = my_project.my_module:do_something"]},
) as my_whl:
pb = PEXBuilder(... |
12,232 | def s3_server(xprocess):
"""
Mock a local S3 server using `minio`
This requires:
- pytest-xprocess: runs the background process
- minio: the executable must be in PATH
Note it will be given EMPTY! The test function needs
to populate it. You can use
`conda.testing.helpers.populate_s3_se... | def s3_server(xprocess):
"""
Mock a local S3 server using `minio`
This requires:
- pytest-xprocess: runs the background process
- minio: the executable must be in PATH
Note it will be given EMPTY! The test function needs
to populate it. You can use
`conda.testing.helpers.populate_s3_se... |
1,617 | def clone(estimator, safe=True):
"""Constructs a new estimator with the same parameters.
Clone does a deep copy of the model in an estimator
without actually copying attached data. It yields a new estimator
with the same parameters that has not been fit on any data.
Parameters
----------
e... | def clone(estimator, safe=True):
"""Constructs a new estimator with the same parameters.
Clone does a deep copy of the model in an estimator
without actually copying attached data. It yields a new estimator
with the same parameters that has not been fit on any data.
Parameters
----------
e... |
31,831 | def get_used_dockers_images() -> CommandResults:
md = None
active_docker_list_integration = {}
active_docker_list_automation = {}
result_dict: Dict[str, List[str]] = {}
active_integration_instances = demisto.internalHttpRequest(POST_COMMAND, "%s" % SETTING_INTEGRATION_SEARCH,
... | def get_used_dockers_images() -> CommandResults:
md = None
active_docker_list_integration = {}
active_docker_list_automation = {}
result_dict: Dict[str, List[str]] = {}
active_integration_instances = demisto.internalHttpRequest(POST_COMMAND, "%s" % SETTING_INTEGRATION_SEARCH,
... |
8,660 | def main(argv=None):
try:
# Step One: Parse The Command Line
parser = build_parser()
opts = parser.parse_args(argv or None)
# Step Two: "Do not run as root" checks
try:
check_not_root()
except RuntimeError as err:
stderr('%s' % err)
... | def main(argv=None):
try:
# Step One: Parse The Command Line
parser = build_parser()
opts = parser.parse_args(argv or None)
# Step Two: "Do not run as root" checks
try:
check_not_root()
except RuntimeError as err:
stderr('%s' % err)
... |
8,427 | def test_create_with_spectral_coord():
spectral_coord = SpectralCoord(np.arange(5100, 5150)*u.AA, radial_velocity = u.Quantity(1000.0, "km/s"))
flux = np.random.randn(50)*u.Jy
spec = Spectrum1D(spectral_axis = spectral_coord, flux = flux)
assert spec.radial_velocity == u.Quantity(1000.0, "km/s")
a... | def test_create_with_spectral_coord():
spectral_coord = SpectralCoord(np.arange(5100, 5150)*u.AA, radial_velocity = u.Quantity(1000.0, "km/s"))
flux = np.random.randn(50)*u.Jy
spec = Spectrum1D(spectral_axis = spectral_coord, flux=flux)
assert spec.radial_velocity == u.Quantity(1000.0, "km/s")
ass... |
31,990 | def cve_to_context(cve) -> Dict[str, str]:
"""Returning a cve structure with the following fields:
* ID: The cve ID.
* CVSS: The cve score scale/
* Published: The date the cve was published.
* Modified: The date the cve was modified.
* Description: the cve's description
Args:
... | def cve_to_context(cve) -> Dict[str, str]:
"""Returning a cve structure with the following fields:
* ID: The cve ID.
* CVSS: The cve score scale/
* Published: The date the cve was published.
* Modified: The date the cve was modified.
* Description: the cve's description
Args:
... |
31,814 | def item_purchase_command(client: Client, args: Dict[str, Any]) -> Union[CommandResults, None]:
try:
item_id = str(args.get('item_id'))
bot_id = ''
room_id = ''
# Get mentions list:
mentions_list_res = client.get_mention_list()
if isinstance(mentions_list_res, dict) ... | def item_purchase_command(client: Client, args: Dict[str, Any]) -> Union[CommandResults, None]:
try:
item_id = str(args.get('item_id'))
bot_id = ''
room_id = ''
# Get mentions list:
mentions_list_res = client.get_mention_list()
if isinstance(mentions_list_res, dict) ... |
44,113 | def compare_measurements(meas1, meas2):
"""
Helper function to compare measurements
"""
assert meas1.return_type.name == meas2.return_type.name
obs1 = meas1.obs
obs2 = meas2.obs
assert np.array(obs1.name == obs2.name).all()
assert set(obs1.wires.tolist()) == set(obs2.wires.tolist())
| def compare_measurements(meas1, meas2):
"""
Helper function to compare measurements
"""
assert meas1.return_type.name == meas2.return_type.name
obs1 = meas1.obs
obs2 = meas2.obs
assert np.array(obs1.name == obs2.name).all()
assert set(obs1.wires) == set(obs2.wires)
|
29,894 | def cluster_pool_from_config(
app_config: config.RawConfig, prefix: str = "rediscluster.", **kwargs: Any
) -> rediscluster.ClusterConnectionPool:
"""Make a ClusterConnectionPool from a configuration dictionary.
The keys useful to :py:func:`clusterpool_from_config` should be prefixed, e.g.
``rediscluste... | def cluster_pool_from_config(
app_config: config.RawConfig, prefix: str = "rediscluster.", **kwargs: Any
) -> rediscluster.ClusterConnectionPool:
"""Make a ClusterConnectionPool from a configuration dictionary.
The keys useful to :py:func:`clusterpool_from_config` should be prefixed, e.g.
``rediscluste... |
10,833 | def remove_unnecessary_nrt_usage(function, context, fndesc):
"""
Remove unnecessary NRT incref/decref in the given LLVM function.
It uses highlevel type info to determine if the function does not need NRT.
Such a function does not:
- return array object;
- take arguments that need refcount exce... | def remove_unnecessary_nrt_usage(function, context, fndesc):
"""
Remove unnecessary NRT incref/decref in the given LLVM function.
It uses highlevel type info to determine if the function does not need NRT.
Such a function does not:
- return array object;
- take arguments that need refcount exce... |
43,138 | def traverse_dir(
directory,
topdown=True,
ignore=None,
only=None,
recursive=True,
include_subdir=True,
):
"""
Recursively traverse all files and sub directories in a directory and
get a list of relative paths.
:param directory: Path to a directory that will be traversed.
:t... | def traverse_dir(
directory,
topdown=True,
ignore=None,
only=None,
recursive=True,
include_subdir=True,
):
"""
Recursively traverse all files and sub directories in a directory and
get a list of relative paths.
:param directory: Path to a directory that will be traversed.
:t... |
12,775 | def test_raid(verbosity):
"""checks all MD arrays on local machine, returns status code"""
raid_devices = find_arrays(verbosity)
status = OK
message = ""
arrays_not_ok = 0
number_arrays = len(raid_devices)
for array in raid_devices:
if verbosity >= 2:
print('Now testing... | def test_raid(verbosity):
"""checks all MD arrays on local machine, returns status code"""
raid_devices = find_arrays(verbosity)
status = OK
message = ""
arrays_not_ok = 0
number_arrays = len(raid_devices)
for array in raid_devices:
if verbosity >= 2:
print('Now testing... |
34,047 | def test_no_eager_gc_in_equal_splitting_lazy_dataset(ray_start_regular_shared):
ds = (
ray.data.range(100, parallelism=10).map_batches(lambda x: x).experimental_lazy()
)
for batch in ds.iter_batches():
pass
assert ds._lazy
assert not ds._used_from_dataset_pipeline
# Splitting 10 ... | def test_no_eager_gc_in_equal_splitting_lazy_dataset(ray_start_regular_shared):
ds = (
ray.data.range(100, parallelism=10).map_batches(lambda x: x).experimental_lazy()
)
for batch in ds.iter_batches():
pass
assert ds._lazy
assert not ds._used_from_dataset_pipeline
# Splitting 10 ... |
41,038 | def _get_parser():
"""
Parses command line inputs for tedana
Returns
-------
parser.parse_args() : argparse dict
"""
parser = argparse.ArgumentParser()
# Argument parser follow templtate provided by RalphyZ
# https://stackoverflow.com/a/43456577
optional = parser._action_groups.... | def _get_parser():
"""
Parses command line inputs for tedana
Returns
-------
parser.parse_args() : argparse dict
"""
parser = argparse.ArgumentParser()
# Argument parser follow templtate provided by RalphyZ
# https://stackoverflow.com/a/43456577
optional = parser._action_groups.... |
27,453 | def lintify(meta, recipe_dir=None, conda_forge=False):
lints = []
hints = []
major_sections = list(meta.keys())
# If the recipe_dir exists (no guarantee within this function) , we can
# find the meta.yaml within it.
meta_fname = os.path.join(recipe_dir or "", "meta.yaml")
sources_section =... | def lintify(meta, recipe_dir=None, conda_forge=False):
lints = []
hints = []
major_sections = list(meta.keys())
# If the recipe_dir exists (no guarantee within this function) , we can
# find the meta.yaml within it.
meta_fname = os.path.join(recipe_dir or "", "meta.yaml")
sources_section =... |
30,616 | def test_module():
"""
Performs basic get request to get item samples
"""
request_api_token()
r = requests.get(url=ARC_URL + '/watchlists', headers=CLIENT_HEADERS, verify=VERIFY_CERT)
try:
_ = r.json() if r.text else {}
if not r.ok:
demisto.results('Cannot connect to ... | def test_module():
"""
Performs basic get request to get item samples
"""
request_api_token()
r = requests.get(url=ARC_URL + '/watchlists', headers=CLIENT_HEADERS, verify=VERIFY_CERT)
try:
_ = r.json() if r.text else {}
if not r.ok:
demisto.results('Cannot connect to ... |
17,885 | def test_all_attribute():
"""Verify all trait types are added to to `traitlets.__all__`"""
names = dir(traitlets)
for name in names:
value = getattr(traitlets, name)
if not name.startswith("_") and isinstance(value, type) and issubclass(value, TraitType):
if name not in traitlets... | def test_all_attribute():
"""Verify all trait types are added to `traitlets.__all__`"""
names = dir(traitlets)
for name in names:
value = getattr(traitlets, name)
if not name.startswith("_") and isinstance(value, type) and issubclass(value, TraitType):
if name not in traitlets.__... |
34,608 | def validate_component_keys(pipeline: List["Component"]) -> None:
"""Validates that all keys for a component are valid.
Raises:
InvalidConfigError: If any component has a key specified that is not used
by the component class, it is likely a mistake in the pipeline
Args:
pipelin... | def validate_component_keys(pipeline: List["Component"]) -> None:
"""Validates that all keys for a component are valid.
Raises:
InvalidConfigError: If any component has a key specified that is not used
by the component class, it is likely a mistake in the pipeline
Args:
pipelin... |
28,041 | def __reload_config(args):
"""
Sends the CodeChecker server process a SIGHUP signal, causing it to
reread it's configuration files.
"""
for i in instance_manager.get_instances():
if i['hostname'] != socket.gethostname():
continue
# A RELOAD only reloads the server associ... | def __reload_config(args):
"""
Sends the CodeChecker server process a SIGHUP signal, causing it to
reread it's configuration files.
"""
for i in instance_manager.get_instances():
if i['hostname'] != socket.gethostname():
continue
# A RELOAD only reloads the server associ... |
21,214 | def get_app(git_url, branch=None, bench_path='.', skip_assets=False, verbose=False, postprocess=True, overwrite=False):
if not os.path.exists(git_url):
if git_url.startswith('git@'):
pass
elif not check_url(git_url, raise_err=False):
orgs = ['frappe', 'erpnext']
for org in orgs:
url = 'https://api.git... | def get_app(git_url, branch=None, bench_path='.', skip_assets=False, verbose=False, postprocess=True, overwrite=False):
if not os.path.exists(git_url):
if not git_url.startswith('git@') and not check_url(git_url, raise_err=False):
orgs = ['frappe', 'erpnext']
for org in orgs:
url = 'https://api.github.com/... |
55,747 | def test_default_properties_assignment():
"""Test that the default properties value can be assigned to properties
see https://github.com/napari/napari/issues/2477
"""
np.random.seed(0)
data = np.random.randint(20, size=(10, 15))
layer = Labels(data)
layer.properties = layer.properties
| def test_default_properties_assignment():
"""Test that the default properties value can be assigned to properties
see https://github.com/napari/napari/issues/2477
"""
np.random.seed(0)
data = np.random.randint(20, size=(10, 15))
layer = Labels(data)
layer.properties = {}
assert layer.pr... |
22,734 | def main():
parser = argparse.ArgumentParser(
description='CLI tool to start a local instance of Pebble or Boulder CA server.')
parser.add_argument('--server-type', '-s',
choices=['pebble', 'boulder-v1', 'boulder-v2'], default='pebble',
help='type of CA se... | def main():
parser = argparse.ArgumentParser(
description='CLI tool to start a local instance of Pebble or Boulder CA server.')
parser.add_argument('--server-type', '-s',
choices=['pebble', 'boulder-v1', 'boulder-v2'], default='pebble',
help='type of CA se... |
12,034 | def format_array(arr):
"""
Returns the given array as a string, using the python builtin str
function on a piecewise basis.
Useful for xml representation of arrays.
For customisations, use the :mod:`numpy.core.arrayprint` directly.
"""
summary_threshold = 85
summary_insert = "..." if... | def format_array(arr):
"""
Returns the given array as a string, using the python builtin str
function on a piecewise basis.
Useful for xml representation of arrays.
For customisations, use the :mod:`numpy.core.arrayprint` directly.
"""
summary_threshold = 85
summary_insert = "..." if... |
13,635 | def load_module(path):
"""Creates model from configuration file.
Args:
path (string): Path to the configuration file relative to pymor_source.
Returns:
model: model as loaded from the file.
"""
with open(path, "r") as stream:
try:
load_dict = yaml.safe_load(stre... | def load_module(path):
"""Creates model from configuration file.
Args:
path (string): Path to the configuration file relative to pymor_source.
Returns:
model: |Model| as loaded from the file.
"""
with open(path, "r") as stream:
try:
load_dict = yaml.safe_load(st... |
17,399 | def _get_engine_from_magic_number(filename_or_obj):
# check byte header to determine file type
if isinstance(filename_or_obj, bytes):
magic_number = filename_or_obj[:8]
else:
if filename_or_obj.tell() != 0:
raise ValueError(
"file-like object read/write pointer no... | def _get_engine_from_magic_number(filename_or_obj):
# check byte header to determine file type
if isinstance(filename_or_obj, bytes):
magic_number = filename_or_obj[:8]
else:
if filename_or_obj.tell() != 0:
raise ValueError(
"file-like object read/write pointer no... |
50,135 | def common_verify(client, expected_keys):
for user, filename, keys in expected_keys:
# Ensure key is in the key file
contents = client.read_from_file(filename)
if user in ['ubuntu', 'root']:
# Our personal public key gets added by pycloudlib
lines = contents.split('\n... | def common_verify(client, expected_keys):
for user, filename, keys in expected_keys:
# Ensure key is in the key file
contents = client.read_from_file(filename)
if user in ['ubuntu', 'root']:
# Our personal public key gets added by pycloudlib
lines = contents.split('\n... |
32,481 | def slack_send():
"""
Sends a message to slack
"""
args = demisto.args()
message = args.get('message', '')
to = args.get('to')
original_channel = args.get('channel')
channel_id = demisto.args().get('channel_id', '')
group = args.get('group')
message_type = args.get('messageType'... | def slack_send():
"""
Sends a message to slack
"""
args = demisto.args()
message = args.get('message', '')
to = args.get('to')
original_channel = args.get('channel')
channel_id = demisto.args().get('channel_id', '')
group = args.get('group')
message_type = args.get('messageType'... |
24,312 | def update_link_metadata(checks, core_workflow=True):
root = get_root()
ensure_dir_exists(path_join(root, LINK_DIR))
# Sign only what affects each wheel
products = []
for check in checks:
products.append(path_join(check, 'datadog_checks'))
products.append(path_join(check, 'setup.py'... | def update_link_metadata(checks, core_workflow=True):
root = get_root()
ensure_dir_exists(path_join(root, LINK_DIR))
# Sign only what affects each wheel
products = []
for check in checks:
products.append(path_join(check, 'datadog_checks'))
products.append(path_join(check, 'setup.py'... |
45,513 | def test_get_channels_data_repsonse_structure():
# Given
api_token = "test_token"
response_data = {
"ok": True,
"channels": [
{
"id": "id1",
"name": "channel1",
"is_channel": True,
"num_members": 3,
},
... | def test_get_channels_data_response_structure():
# Given
api_token = "test_token"
response_data = {
"ok": True,
"channels": [
{
"id": "id1",
"name": "channel1",
"is_channel": True,
"num_members": 3,
},
... |
43,440 | def CRoty(theta):
r"""Two-qubit controlled rotation about the y axis.
Args:
theta (float): rotation angle
Returns:
array: unitary 4x4 rotation matrix `
"""
return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, np.cos(theta/2), -1*np.sin(theta/2)], [0, 0, np.sin(theta/2), np.cos(theta/... | def CRoty(theta):
r"""Two-qubit controlled rotation about the y axis.
Args:
theta (float): rotation angle
Returns:
array: unitary 4x4 rotation matrix
"""
return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, np.cos(theta/2), -1*np.sin(theta/2)], [0, 0, np.sin(theta/2), np.cos(theta/2)... |
31,983 | def wildfire_get_verdict_command():
file_hashes = hash_args_handler(demisto.args().get('hash', ''))
urls = argToList(demisto.args().get('url', ''))
if not urls and not file_hashes:
raise Exception('Specify exactly 1 of the following arguments: url, hash.')
if file_hashes:
for file_hash i... | def wildfire_get_verdict_command():
file_hashes = hash_args_handler(demisto.args().get('hash', ''))
urls = argToList(demisto.args().get('url', ''))
if not urls and not file_hashes:
raise Exception('Either hash or url must be provided.')
if file_hashes:
for file_hash in file_hashes:
... |
18,964 | def add(name, url, scope, args={}):
"""Add a named mirror in the given scope"""
mirrors = spack.config.get('mirrors', scope=scope)
if not mirrors:
mirrors = syaml_dict()
if name in mirrors:
tty.die("Mirror with name %s already exists." % name)
items = [(n, u) for n, u in mirrors.it... | def add(name, url, scope, args={}):
"""Add a named mirror in the given scope"""
mirrors = spack.config.get('mirrors', scope=scope)
if not mirrors:
mirrors = syaml_dict()
if name in mirrors:
tty.die("Mirror with name %s already exists." % name)
items = [(n, u) for n, u in mirrors.it... |
17,411 | def _mapping_repr(mapping, title, summarizer, col_width=None, max_rows=None):
if col_width is None:
col_width = _calculate_col_width(mapping)
if max_rows is None:
max_rows = OPTIONS["display_max_rows"]
summary = [f"{title}:"]
if mapping:
if len(mapping) > max_rows:
fi... | def _mapping_repr(mapping, title, summarizer, col_width=None, max_rows=None):
if col_width is None:
col_width = _calculate_col_width(mapping)
if max_rows is None:
max_rows = OPTIONS["display_max_rows"]
summary = [f"{title}:"]
if mapping:
if len(mapping) > max_rows:
fi... |
56,836 | def test_should_hide_feature_notifs_for_non_pro_with_groups():
with case_sharing_groups_patch(['agroupid']), active_service_type_patch("not_IMPLEMENTATION_or_SANDBOX"):
hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", None)
assert not hide, "notifications should not be hidden f... | def test_should_hide_feature_notifs_for_non_pro_with_groups():
with case_sharing_groups_patch([]), active_service_type_patch("not_IMPLEMENTATION_or_SANDBOX"):
hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", None)
assert not hide, "notifications should not be hidden for non pro... |
55,831 | def finalize_on_12(spec, state, epoch, sufficient_support, messed_up_target):
assert epoch > 2
state.slot = (spec.SLOTS_PER_EPOCH * epoch) - 1 # skip ahead to just before epoch
# 43210 -- epochs ago
# 210xx -- justification bitfield indices (pre shift)
# 3210x -- justification bitfield indices (p... | def finalize_on_12(spec, state, epoch, sufficient_support, messed_up_target):
assert epoch > 2
state.slot = (spec.SLOTS_PER_EPOCH * epoch) - 1 # skip ahead to just before epoch
# 43210 -- epochs ago
# 210xx -- justification bitfield indices (pre shift)
# 3210x -- justification bitfield indices (p... |
25,613 | def _mix_latent_gp(W, g_mu, g_var, full_cov, full_output_cov):
r"""
Takes the mean and variance of a uncorrelated L-dimensional latent GP
and returns the mean and the variance of the mixed GP, `f = W \times g`,
where both f and g are GPs.
:param W: [P, L]
:param g_mu: [..., N, L]
:param g_v... | def _mix_latent_gp(W, g_mu, g_var, full_cov, full_output_cov):
r"""
Takes the mean and variance of an uncorrelated L-dimensional latent GP
and returns the mean and the variance of the mixed GP, `f = W \times g`,
where both f and g are GPs.
:param W: [P, L]
:param g_mu: [..., N, L]
:param g_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.