id int64 11 59.9k | original stringlengths 33 150k | modified stringlengths 37 150k |
|---|---|---|
17,417 | def _plot1d(plotfunc):
"""
Decorator for common 2d plotting logic
Also adds the 2d plot method to class _PlotMethods
"""
commondoc = """
Parameters
----------
darray : DataArray
Must be 2 dimensional, unless creating faceted plots
x : string, optional
Coordinate for ... | def _plot1d(plotfunc):
"""
Decorator for common 1d plotting logic.
Also adds the 2d plot method to class _PlotMethods
"""
commondoc = """
Parameters
----------
darray : DataArray
Must be 2 dimensional, unless creating faceted plots
x : string, optional
Coordinate for... |
54,288 | def _qmu_like(mu, data, pdf, init_pars, par_bounds):
"""
Clipped version of _tmu where _qmu = 0 if muhat > 0 else _tmu
If the lower bound of the POI is 0 this automatically implments
qmu_tilde. Otherwise this is qmu (no tilde).
"""
tensorlib, optimizer = get_backend()
tmu_stat, (mubhathat, ... | def _qmu_like(mu, data, pdf, init_pars, par_bounds):
"""
Clipped version of _tmu where _qmu = 0 if muhat > 0 else _tmu
If the lower bound of the POI is 0 this automatically implments
qmu_tilde. Otherwise this is qmu (no tilde).
"""
tensorlib, optimizer = get_backend()
tmu_stat, (mubhathat, ... |
32,689 | def test_pandas_dtypes(conn_cnx):
with conn_cnx(
session_parameters={
PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "arrow_force"
}
) as cnx:
with cnx.cursor() as cur:
cur.execute(
"select 1::integer, 2.3::double, 'foo'::string, current_timestamp... | def test_pandas_dtypes(conn_cnx):
with conn_cnx(
session_parameters={
PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "arrow_force"
}
) as cnx:
with cnx.cursor() as cur:
cur.execute(
"select 1::integer, 2.3::double, 'foo'::string, current_timestamp... |
35,262 | def emd(a, b, M, numItermax=100000, log=False, center_dual=True):
r"""Solves the Earth Movers distance problem and returns the OT matrix
.. math:: \gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matr... | def emd(a, b, M, numItermax=100000, log=False, center_dual=True):
r"""Solves the Earth Movers distance problem and returns the OT matrix
.. math:: \gamma = arg\min_\gamma <\gamma,M>_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matr... |
40,597 | def mock_snakemake(rulename, **wildcards):
"""
This function is expected to be executed from the 'scripts'-directory of '
the snakemake project. It returns a snakemake.script.Snakemake object,
based on the Snakefile.
If a rule has wildcards, you have to specify them in **wildcards.
Parameters
... | def mock_snakemake(rulename, **wildcards):
"""
This function is expected to be executed from the 'scripts'-directory of '
the snakemake project. It returns a snakemake.script.Snakemake object,
based on the Snakefile.
If a rule has wildcards, you have to specify them in **wildcards.
Parameters
... |
53,635 | def _subprocess_transform():
communicate = (bytes("string", "ascii"), bytes("string", "ascii"))
communicate_signature = "def communicate(self, input=None, timeout=None)"
args = """\
self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True... | def _subprocess_transform():
communicate = (bytes("string", "ascii"), bytes("string", "ascii"))
communicate_signature = "def communicate(self, input=None, timeout=None)"
args = """\
self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True... |
212 | def check_if_updates_and_builds_set(ctx, param, value):
"""
Print an error to stderr if the user has set both the --updates and --builds flags.
Args:
ctx (click.core.Context): The Click context, used to find out if the other flags are set.
param (click.core.Option): The option being handled... | def check_if_updates_and_builds_set(ctx, param, value):
"""
Print an error to stderr if the user has set both the --updates and --builds flags.
Args:
ctx (click.core.Context): The Click context, used to find out if the other flags are set.
param (click.core.Option): The option being handled... |
34,346 | def add_subparser(
subparsers: argparse._SubParsersAction, parents: List[argparse.ArgumentParser]
):
scaffold_parser = subparsers.add_parser(
"init",
parents=parents,
help="Creates a new project, with example training data, actions, and config files.",
formatter_class=argparse.Ar... | def add_subparser(
subparsers: argparse._SubParsersAction, parents: List[argparse.ArgumentParser]
):
scaffold_parser = subparsers.add_parser(
"init",
parents=parents,
help="Creates a new project, with example training data, actions, and config files.",
formatter_class=argparse.Ar... |
31,670 | def fetch_incidents(last_run, first_run_time_range):
target_orgs = []
if BROKER:
orgs = list_org()
for org in orgs:
target_orgs.append(org['org_name'])
else:
target_orgs.append(None)
next_run = {}
incidents = []
for target_org in target_orgs:
if targe... | def fetch_incidents(last_run, first_run_time_range):
target_orgs = []
if BROKER:
orgs = list_org()
for org in orgs:
target_orgs.append(org['org_name'])
else:
target_orgs.append(None)
next_run = {}
incidents = []
for target_org in target_orgs:
if targe... |
43,704 | def observable(me_tables, init_term=0, mapping="jordan_wigner", wires=None):
r"""Builds the many-body observable whose expectation value can be
measured in PennyLane.
This function can be used to build second-quantized operators in the basis
of single-particle states (e.g., HF states) and to transform... | def observable(me_tables, init_term=0, mapping="jordan_wigner", wires=None):
r"""Builds the many-body observable whose expectation value can be
measured in PennyLane.
This function can be used to build second-quantized operators in the basis
of single-particle states (e.g., HF states) and to transform... |
50,147 | def _is_applicable(
module_details: ModuleDetails, cfg: dict, schema: Optional[dict] = None
) -> bool:
if not module_details.module.meta.get("skippable", False):
return True
normalized_name = f"cc_{module_details.name}".replace("-", "_")
config_keys = get_config_keys(normalized_name, schema=sche... | def _is_applicable(
module_details: ModuleDetails, cfg: dict, schema: Optional[dict] = None
) -> bool:
if not module_details.module.meta.get("skip_on_inapplicable_schema", False):
return True
normalized_name = f"cc_{module_details.name}".replace("-", "_")
config_keys = get_config_keys(normalized... |
17,896 | def get_variation_from_env(envvar_value):
"""Return a tuple with variation data from the specific environment
variable key.
Raise an exception if the passed in envvar doesn't look something
like: '0 100'
"""
try:
# We want to create a tuple of integers from a string containing
#... | def get_variation_from_env(envvar_value):
"""Return a tuple with variation data from the specific environment
variable key.
Raise an exception if the passed in envvar doesn't look something
like: '0 100'
"""
try:
# We want to create a tuple of integers from a string containing
#... |
28,090 | def journal_entry(cmdr, is_beta, system, station, entry, state):
# Always update, even if we're not the *current* system or station provider.
this.system_address = entry.get('SystemAddress') or this.system_address
this.system = entry.get('StarSystem') or this.system
# We need pop == 0 to set the value ... | def journal_entry(cmdr, is_beta, system, station, entry, state):
# Always update, even if we're not the *current* system or station provider.
this.system_address = entry.get('SystemAddress') or this.system_address
this.system = entry.get('StarSystem') or this.system
# We need pop == 0 to set the value ... |
2,251 | def test_multilabel_binarizer_unknown_class():
mlb = MultiLabelBinarizer()
y = [[1, 2]]
Y = np.array([[1, 0], [0, 1]])
warning_message = 'will be ignored'
with pytest.warns(UserWarning, match=warning_message):
matrix = mlb.fit(y).transform([[4, 1], [2, 0]])
Y = np.array([[1, 0, 0], [0, ... | def test_multilabel_binarizer_unknown_class():
mlb = MultiLabelBinarizer()
y = [[1, 2]]
Y = np.array([[1, 0], [0, 1]])
warning_message = 'unknown class.* will be ignored'
with pytest.warns(UserWarning, match=warning_message):
matrix = mlb.fit(y).transform([[4, 1], [2, 0]])
Y = np.array(... |
24,744 | def _has_different_parameter_names_only(original, overridden):
"""Check if the original and the overridden parameters have different names
but the same type.If they do, raise arguments-renamed. In any other case
return False.
Args:
original (astroid.FunctionDef): original function's definition... | def _has_different_parameter_names_only(original: astroid.FunctionDef, overridden: astroid.FunctionDef) -> bool:
"""Check if the original and the overridden parameters have different names
but the same type.If they do, raise arguments-renamed. In any other case
return False.
Args:
original (as... |
49,660 | def get_terminal_width() -> int:
"""Get number of columns of the terminal."""
return shutil.get_terminal_size().columns - 1
| def get_terminal_width() -> int:
"""Return the width of the terminal window.
The width of the terminal connected to sys.__stdout__ is obtained via
os.get_terminal_size. If the terminal size cannot be determined, the
environment variable COLUMNS is used if defined. Otherwise, fallback value
is retur... |
22,840 | def _modify_relative_data(relative_data, replace_spaces=False):
modified_relative_data = OrderedDict()
for key, value in relative_data.items():
for i, string in enumerate(value):
string = RELATIVE_PATTERN.sub(r'(\\d+)', string)
if replace_spaces:
string = re.sub(r... | def _modify_relative_data(relative_data, replace_spaces=False):
modified_relative_data = OrderedDict()
for key, value in relative_data.items():
for i, string in enumerate(value):
string = RELATIVE_PATTERN.sub(r'(\\d+)', string)
if replace_spaces:
string = re.sub(r... |
56,644 | def sortable_lcc_to_short_lcc(lcc):
"""
As close to the inverse of make_sortable_lcc as possible
:param basestring lcc:
:rtype: basestring
"""
m = LCC_PARTS_RE.match(lcc)
parts = m.groupdict()
parts['letters'] = parts['letters'].strip('-')
parts['number'] = parts['number'].strip('0')... | def sortable_lcc_to_short_lcc(lcc):
"""
As close to the inverse of make_sortable_lcc as possible
:param basestring lcc:
:rtype: basestring
"""
m = LCC_PARTS_RE.match(lcc)
parts = m.groupdict()
parts['letters'] = parts['letters'].strip('-')
parts['number'] = parts['number'].strip('0')... |
4,812 | def _get_config_or_cache_dir(xdg_base):
configdir = os.environ.get('MPLCONFIGDIR')
if configdir:
configdir = Path(configdir).resolve()
elif sys.platform.startswith(('linux', 'freebsd')) and xdg_base:
configdir = Path(xdg_base, "matplotlib")
else:
configdir = Path.home() / ".matpl... | def _get_config_or_cache_dir(xdg_base):
configdir = os.environ.get('MPLCONFIGDIR')
if configdir:
configdir = Path(configdir).resolve()
elif sys.platform.startswith(('linux', 'freebsd')) and xdg_base:
configdir = Path(xdg_base, "matplotlib")
else:
configdir = Path.home() / ".matpl... |
53,472 | def iterator_suffix(iterator, stop: int):
for i, item in enumerate(iterator):
if i < stop: # [no-else-continue]
continue
else:
yield item
| def even_number_under(n: int):
for i in range(n):
if i%2 == 1: # [no-else-continue]
continue
else:
yield i
|
27,984 | def check(check_data):
"""
Invoke clang with an action which called by processes.
Different analyzer object belongs to for each build action.
skiplist handler is None if no skip file was configured.
"""
actions_map, action, context, analyzer_config, \
output_dir, skip_handler, quiet_out... | def check(check_data):
"""
Invoke clang with an action which called by processes.
Different analyzer object belongs to for each build action.
skiplist handler is None if no skip file was configured.
"""
actions_map, action, context, analyzer_config, \
output_dir, skip_handler, quiet_out... |
11,794 | def export_regions(objs):
"""
Convenience function to convert a sequence of Ginga canvas objects
to a ds9 file containing regions and
return a list of matching .
Parameters
----------
objs : seq of subclasses of `~ginga.canvas.CanvasObject.CanvasObjectBase`
Sequence of Ginga canvas ... | def export_regions(objs):
"""
Convenience function to convert a sequence of Ginga canvas objects
to a ds9 file containing regions and
return a list of matching regions.
Parameters
----------
objs : seq of subclasses of `~ginga.canvas.CanvasObject.CanvasObjectBase`
Sequence of Ginga ... |
40,128 | def log_current_packages(packages: Tuple[str], install: bool = True):
'''
Log which packages are installed or removed.
:param packages: List of packages that are affected.
:param install: Identifier to distinguish installation from removal.
'''
action = 'Installing' if install else 'Removing'
... | def log_current_packages(packages: Tuple[str], install: bool = True):
'''
Log which packages are installed or removed.
:param packages: List of packages that are affected.
:param install: Identifier to distinguish installation from removal.
'''
logging.info(f'{action} {" ".join(packages)}')
... |
53,863 | def process_alias(io, data, name, print_name=False):
return process_rr(io, data, 'ALIAS', 'target-resource-id', name, print_name) | def process_alias(io, data, name, print_name=False):
return process_rr(io, data, 'ALIAS', 'target-resource-id', name, print_name)
|
12,493 | def is_definitely_not_enum_member(name: str, typ: Optional[Type]) -> bool:
"""
Return `True` if we are certain that an object inside an enum class statement
will not be converted to become a member of the enum.
The following things are not converted:
1. Assignments with private names like in `__pro... | def is_definitely_not_enum_member(name: str, typ: Type | None) -> bool:
"""
Return `True` if we are certain that an object inside an enum class statement
will not be converted to become a member of the enum.
The following things are not converted:
1. Assignments with private names like in `__prop =... |
45,870 | def tiltProjection(taux: torch.Tensor, tauy: torch.Tensor, inv: bool = False) -> torch.Tensor:
r"""Estimate the tilt projection matrix or the inverse tilt projection matrix
Args:
taux (torch.Tensor): Rotation angle in radians around the :math:`x`-axis with shape :math:`(*, 1)`.
tauy (torch.Tens... | def tiltProjection(taux: torch.Tensor, tauy: torch.Tensor, inv: bool = False) -> torch.Tensor:
r"""Estimate the tilt projection matrix or the inverse tilt projection matrix
Args:
taux (torch.Tensor): Rotation angle in radians around the :math:`x`-axis with shape :math:`(*, 1)`.
tauy (torch.Tens... |
31,092 | def check_if_incident_was_modified_in_xdr(incident_id):
demisto_incident = demisto.get_incidents()[0]
last_mirrored_in_time = demisto_incident.get('CustomFields', {}).get('lastmirroredintime')
last_mirrored_in_time_timestamp = arg_to_timestamp(last_mirrored_in_time, 'last_mirrored_in_time')
last_modifi... | def check_if_incident_was_modified_in_xdr(incident_id):
demisto_incident = demisto.get_incidents()[0]
last_mirrored_in_time = demisto_incident.get('CustomFields', {}).get('lastmirroredintime')
last_mirrored_in_time_timestamp = arg_to_timestamp(last_mirrored_in_time, 'last_mirrored_in_time')
last_modifi... |
58,207 | def patched_api_call(original_func, instance, args, kwargs):
pin = Pin.get_from(instance)
if not pin or not pin.enabled():
return original_func(*args, **kwargs)
endpoint_name = deep_getattr(instance, '_endpoint._endpoint_prefix')
with pin.tracer.trace('{}.command'.format(endpoint_name),
... | def patched_api_call(original_func, instance, args, kwargs):
pin = Pin.get_from(instance)
if not pin or not pin.enabled():
return original_func(*args, **kwargs)
endpoint_name = deep_getattr(instance, '_endpoint._endpoint_prefix')
with pin.tracer.trace('{}.command'.format(endpoint_name),
... |
48,018 | def get_model_class(name):
for cls in get_all_subclasses(Model):
if cls.__name__.lower() == name:
return cls
raise ValueError("There is not model class with this name: {}".format(name))
| def get_model_class(name):
for cls in get_all_subclasses(Model):
if cls.__name__.lower() == name:
return cls
raise ValueError("There is no model class with this name: {}".format(name))
|
47,392 | def dice_loss(inputs: Tensor, targets: Tensor, num_masks: float) -> Tensor:
r"""
Compute the DICE loss, similar to generalized IOU for masks as follow
.. math::
\mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x \cap y }{x \cup y + 1}}
In practice, since `targets` is a binary mask, (only 0s and ... | def dice_loss(inputs: Tensor, targets: Tensor, num_masks: float) -> Tensor:
r"""
Compute the DICE loss, similar to generalized IOU for masks as follow
.. math::
\mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x \cap y }{x \cup y + 1}}
In practice, since `targets` is a binary mask, (only 0s and ... |
42,821 | def move_git_repo(source_path, new_path):
"""
Moves git folder and .gitignore to the new backup directory.
"""
if os.path.exists(os.path.join(new_path, '.git')) or os.path.exists(os.path.join(new_path, '.gitignore')):
print_red_bold("Git repository already exists new path ({})".format(new_path))
print_red_bold(... | def move_git_repo(source_path, new_path):
"""
Moves git folder and .gitignore to the new backup directory.
"""
if os.path.exists(os.path.join(new_path, '.git')) or os.path.exists(os.path.join(new_path, '.gitignore')):
print_red_bold("A git repo already exists here: {}".format(new_path))
print_red_bold("Please c... |
59,192 | def _run_pip(args, additional_paths=None):
# Add our bundled software to the sys.path so we can import it
if additional_paths is not None:
sys.path = additional_paths + sys.path
# Invoke pip as if it's the main module, and catch the exit.
backup_argv = sys.argv[:]
sys.argv[1:] = args
tr... | def _run_pip(args, additional_paths=None):
# Add our bundled software to the sys.path so we can import it
if additional_paths is not None:
sys.path = additional_paths + sys.path
# Invoke pip as if it's the main module, and catch the exit.
backup_argv = sys.argv[:]
sys.argv[1:] = args
tr... |
41,205 | def decompose_clifford_tableau_to_operations(
qubits: List['cirq.Qid'], clifford_tableau: qis.CliffordTableau
) -> List[ops.Operation]:
"""Decompose an n-qubit Clifford Tableau into a list of one/two qubit operations.
Args:
qubits: The list of qubits being operated on.
clifford_tableau: The... | def decompose_clifford_tableau_to_operations(
qubits: List['cirq.Qid'], clifford_tableau: qis.CliffordTableau
) -> List[ops.Operation]:
"""Decompose an n-qubit Clifford Tableau into a list of one/two qubit operations.
Args:
qubits: The list of qubits being operated on.
clifford_tableau: The... |
44,601 | def urisfy_regex_or_tree(
unit: Any, is_ascii: bool, is_wide: bool, is_nocase: bool,
) -> Optional[UrsaExpression]:
or_strings = flatten_regex_or_tree(unit)
if or_strings and all(s is not None for s in or_strings):
or_ursa_strings: List[UrsaExpression] = []
for s in or_strings:
u... | def urisfy_regex_or_tree(
unit: Any, is_ascii: bool, is_wide: bool, is_nocase: bool,
) -> Optional[UrsaExpression]:
or_strings = flatten_regex_or_tree(unit)
if or_strings and all(or_strings):
or_ursa_strings: List[UrsaExpression] = []
for s in or_strings:
ursified_s = ursify_rege... |
57,898 | def main() -> None:
params = {k: v for k, v in demisto.params().items() if v is not None}
params['indicator_type'] = FeedIndicatorType.File
params['feed_name_to_config'] = {
'File': {
'url': params.get("url") + "/api/v1/",
'extractor': "data",
'indicator': 'sha256... | def main() -> None:
params = {k: v for k, v in demisto.params().items() if v is not None}
params['indicator_type'] = FeedIndicatorType.File
params['feed_name_to_config'] = {
'File': {
'url': params.get("url") + "/api/v1/",
'extractor': "data",
'indicator': 'sha256... |
1,103 | def test_output_version():
class InputSpec(nib.TraitedSpec):
foo = nib.traits.Int(desc='a random int')
class OutputSpec(nib.TraitedSpec):
foo = nib.traits.Int(desc='a random int', min_ver='0.9')
class DerivedInterface1(nib.BaseInterface):
input_spec = InputSpec
output_spec ... | def test_output_version():
class InputSpec(nib.TraitedSpec):
foo = nib.traits.Int(desc='a random int')
class OutputSpec(nib.TraitedSpec):
foo = nib.traits.Int(desc='a random int', min_ver='0.9')
class DerivedInterface1(nib.BaseInterface):
input_spec = InputSpec
output_spec ... |
12,385 | def remove_default_ca_certs(distro_name):
"""
Removes all default trusted CA certificates from the system. To actually
apply the change you must also call L{update_ca_certs}.
"""
distro_cfg = _distro_ca_certs_configs(distro_name)
util.delete_dir_contents(distro_cfg['ca_cert_path'])
util.dele... | def remove_default_ca_certs(distro_name):
"""
Removes all default trusted CA certificates from the system. To actually
apply the change you must also call L{update_ca_certs}.
"""
distro_cfg = _distro_ca_certs_configs(distro_name)
util.delete_dir_contents(distro_cfg['ca_cert_path'])
util.dele... |
8,506 | def user_dictize(
user, context, include_password_hash=False,
include_plugin_extras=False):
if context.get('with_capacity'):
user, capacity = user
result_dict = d.table_dictize(user, context, capacity=capacity)
else:
result_dict = d.table_dictize(user, context)
pass... | def user_dictize(
user, context, include_password_hash=False,
include_plugin_extras=False):
if context.get('with_capacity'):
user, capacity = user
result_dict = d.table_dictize(user, context, capacity=capacity)
else:
result_dict = d.table_dictize(user, context)
pass... |
56,340 | def _compute_dt_correlations(catalog, master, min_link, event_id_mapper,
stream_dict, min_cc, extract_len, pre_pick,
shift_len, interpolate, max_workers=1):
""" Compute cross-correlation delay times. """
max_workers = max_workers or 1
Logger.info(
... | def _compute_dt_correlations(catalog, master, min_link, event_id_mapper,
stream_dict, min_cc, extract_len, pre_pick,
shift_len, interpolate, max_workers=1):
""" Compute cross-correlation delay times. """
max_workers = max_workers or 1
Logger.info(
... |
10,891 | def install_pip():
print('')
print('Install pip')
print('')
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tmp = tempfile.mkdtemp(prefix='buildout-dev-')
try:
get_pip = os.path.join(tmp, 'get-pip.py')
with open(get_pip... | def install_pip():
print('')
print('Install pip')
print('')
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tmp = tempfile.mkdtemp(prefix='buildout-dev-')
try:
get_pip = os.path.join(tmp, 'get-pip.py')
with open(get_pip... |
7,099 | def filter_ids(
pools: 'List[Pool]',
ids: 'Iterable[str]',
*,
warn: 'bool' = True,
out: 'IDTokens' = IDTokens.Task,
pattern_match: 'bool' = True,
# ) -> _RET:
):
"""Filter IDs against a pool of tasks.
Args:
pool:
The pool to match against.
ids:
... | def filter_ids(
pools: 'List[Pool]',
ids: 'Iterable[str]',
*,
warn: 'bool' = True,
out: 'IDTokens' = IDTokens.Task,
pattern_match: 'bool' = True,
# ) -> _RET:
):
"""Filter IDs against a pool of tasks.
Args:
pool:
The pool to match against.
ids:
... |
4,739 | def _parse_char_metrics(fh):
"""
Parse the given filehandle for character metrics information and return
the information as dicts.
It is assumed that the file cursor is on the line behind
'StartCharMetrics'.
Returns
-------
ascii_d : dict
A mapping "ASCII num of the character"... | def _parse_char_metrics(fh):
"""
Parse the given filehandle for character metrics information and return
the information as dicts.
It is assumed that the file cursor is on the line behind
'StartCharMetrics'.
Returns
-------
ascii_d : dict
A mapping "ASCII num of the character"... |
37,295 | def _parse_pulse_args(backend, qubit_lo_freq, meas_lo_freq, qubit_lo_range,
meas_lo_range, schedule_los, meas_level,
meas_return, meas_map,
memory_slot_size,
rep_time, rep_delay,
parametric_pulses,
... | def _parse_pulse_args(backend, qubit_lo_freq, meas_lo_freq, qubit_lo_range,
meas_lo_range, schedule_los, meas_level,
meas_return, meas_map,
memory_slot_size,
rep_time, rep_delay,
parametric_pulses,
... |
11,878 | def _toqclass_helper(im):
data = None
colortable = None
# handle filename, if given instead of image name
if hasattr(im, "toUtf8"):
# FIXME - is this really the best way to do this?
im = str(im.toUtf8(), "utf-8")
if isPath(im):
im = Image.open(im)
if im.mode == "1":
... | def _toqclass_helper(im):
data = None
colortable = None
# handle filename, if given instead of image name
if hasattr(im, "toUtf8"):
# FIXME - is this really the best way to do this?
im = str(im.toUtf8(), "utf-8")
if isPath(im):
im = Image.open(im)
if im.mode == "1":
... |
33,112 | def get_time_as_str(t, timezone=None):
if timezone is None:
timezone = config.get("TIMEZONE")
s = (t - datetime.utcnow()).total_seconds()
(m, s) = divmod(s, 60)
(h, m) = divmod(m, 60)
d = timedelta(hours=h, minutes=m, seconds=s)
if timezone is not None:
disappear_time = datetime.... | def get_time_as_str(t, timezone=None):
if timezone is None:
timezone = config.get("TIMEZONE")
s = (t - datetime.utcnow()).total_seconds()
(m, s) = divmod(s, 60)
(h, m) = divmod(m, 60)
d = timedelta(hours=h, minutes=m, seconds=s)
if timezone is not None:
disappear_time = datetime.... |
20,542 | def main(argv=None):
parser = get_parser()
arguments = parser.parse_args(argv)
verbose = arguments.v
set_loglevel(verbose=verbose)
# Default params
param = Param()
# Get parser info
fname_data = arguments.i
fname_mask = arguments.m
fname_mask_noise = arguments.m_noise
m... | def main(argv=None):
parser = get_parser()
arguments = parser.parse_args(argv)
verbose = arguments.v
set_loglevel(verbose=verbose)
# Default params
param = Param()
# Get parser info
fname_data = arguments.i
fname_mask = arguments.m
fname_mask_noise = arguments.m_noise
m... |
24,112 | def config_proxy_skip(proxies, uri, skip_proxy=False):
"""
Returns an amended copy of the proxies dictionary - used by `requests`,
it will disable the proxy if the uri provided is to be reached directly.
:param proxies dict with existing proxies: 'https', 'http', 'no' as pontential keys
:param uri u... | def config_proxy_skip(proxies, uri, skip_proxy=False):
"""
Returns an amended copy of the proxies dictionary - used by `requests`,
it will disable the proxy if the uri provided is to be reached directly.
:param proxies dict with existing proxies: 'https', 'http', 'no' as pontential keys
:param uri U... |
7,893 | def _vectfit_xs(energy, ce_xs, mts, rtol=1e-3, atol=1e-5, orders=None,
n_vf_iter=30, log=False, path_out=None, **kwargs):
r"""Convert point-wise cross section to multipole data via Vector Fitting.
Parameters
----------
energy : np.ndarray
Energy array
ce_xs : np.ndarray
... | def _vectfit_xs(energy, ce_xs, mts, rtol=1e-3, atol=1e-5, orders=None,
n_vf_iter=30, log=False, path_out=None, **kwargs):
r"""Convert point-wise cross section to multipole data via Vector Fitting.
Parameters
----------
energy : np.ndarray
Energy array
ce_xs : np.ndarray
... |
8,654 | def get_pid_filename(options, pid_dir):
"""Get the pid filename in ``pid_dir`` from the given ``options``.
:param options: command line options
:param str pid_dir: path to the pid directory
:return: absolute filename of the pid file
By default, it's ``sopel.pid``, but if a configuration filename i... | def get_pid_filename(options, pid_dir):
"""Get the pid file name in ``pid_dir`` from the given ``options``.
:param options: command line options
:param str pid_dir: path to the pid directory
:return: absolute filename of the pid file
By default, it's ``sopel.pid``, but if a configuration filename ... |
5,661 | def ks_2samp(data1, data2, alternative='two-sided', mode='auto'):
"""
Compute the Kolmogorov-Smirnov statistic on 2 samples.
This is a two-sided test for the null hypothesis that 2 independent samples
are drawn from the same continuous distribution. The alternative hypothesis
can be either 'two-si... | def ks_2samp(data1, data2, alternative='two-sided', mode='auto'):
"""
Compute the Kolmogorov-Smirnov statistic on 2 samples.
This is a two-sided test for the null hypothesis that 2 independent samples
are drawn from the same continuous distribution. The alternative hypothesis
can be either 'two-si... |
19,614 | def getgccversion(chost=None):
"""
rtype: C{str}
return: the current in-use gcc version
"""
gcc_ver_command = ["gcc", "-dumpversion"]
gcc_ver_prefix = "gcc-"
# accept clang as system compiler too
clang_ver_command = ["clang", "--version"]
clang_ver_prefix = "clang-"
ubinpath ... | def getgccversion(chost=None):
"""
rtype: C{str}
return: the current in-use gcc version
"""
gcc_ver_command = ["gcc", "-dumpversion"]
gcc_ver_prefix = "gcc-"
# accept clang as system compiler too
clang_ver_command = ["clang", "--version"]
clang_ver_prefix = "clang-"
ubinpath ... |
51,444 | def _plot1d(plotfunc):
"""
Decorator for common 2d plotting logic
Also adds the 2d plot method to class _PlotMethods
"""
commondoc = """
Parameters
----------
darray : DataArray
Must be 2 dimensional, unless creating faceted plots
x : string, optional
Coordinate for ... | def _plot1d(plotfunc):
"""
Decorator for common 2d plotting logic
Also adds the 2d plot method to class _PlotMethods
"""
commondoc = """
Parameters
----------
darray : DataArray
Must be 2 dimensional, unless creating faceted plots
x : string, optional
Coordinate for ... |
17,352 | def dot(*arrays, dims=None, **kwargs):
"""Generalized dot product for xarray objects. Like np.einsum, but
provides a simpler interface based on array dimensions.
Parameters
----------
arrays: DataArray (or Variable) objects
Arrays to compute.
dims: xarray.ALL_DIMS, str or tuple of strin... | def dot(*arrays, dims=None, **kwargs):
"""Generalized dot product for xarray objects. Like np.einsum, but
provides a simpler interface based on array dimensions.
Parameters
----------
arrays: DataArray (or Variable) objects
Arrays to compute.
dims: '...', str or tuple of strings, option... |
5,707 | def _van_es_entropy(X, m):
"""Compute the van Es estimator as described in [6]"""
# No equation number, but referred to as HVE_mn.
# Typo: there should be a log within the summation.
n = X.shape[-1]
term1 = 1/(n-m) * np.sum(np.log((n+1)/m * (X[..., m:] - X[..., :-m])),
a... | def _van_es_entropy(X, m):
"""Compute the van Es estimator as described in [6]."""
# No equation number, but referred to as HVE_mn.
# Typo: there should be a log within the summation.
n = X.shape[-1]
term1 = 1/(n-m) * np.sum(np.log((n+1)/m * (X[..., m:] - X[..., :-m])),
... |
15,349 | def library_payload(roon_server, zone_id, media_content_id):
"""Create response payload for the library."""
opts = {
"hierarchy": "browse",
"zone_or_output_id": zone_id,
"count": ITEM_LIMIT,
}
# Roon starts browsing for a zone where it left off - so start from the top unless ot... | def library_payload(roon_server, zone_id, media_content_id):
"""Create response payload for the library."""
opts = {
"hierarchy": "browse",
"zone_or_output_id": zone_id,
"count": ITEM_LIMIT,
}
# Roon starts browsing for a zone where it left off - so start from the top unless ot... |
24,479 | def initialize_instance(values, **kwargs):
# TODO: remove when deprecation is finalized https://github.com/DataDog/integrations-core/pull/9340
if 'username' not in values and 'user' in values:
values['username'] = values['user']
_validate_authenticator_option(values)
if 'private_key_password' ... | def initialize_instance(values, **kwargs):
# TODO: remove when deprecation is finalized https://github.com/DataDog/integrations-core/pull/9340
if 'username' not in values and 'user' in values:
values['username'] = values['user']
_validate_authenticator_option(values)
if 'private_key_password' ... |
15,817 | def _first_ip_nexthop_from_route(routes: Iterable) -> None | str:
"""Find the first RTA_PREFSRC in the routes."""
_LOGGER.debug("Routes: %s", routes)
for route in routes:
for key, value in route["attrs"]:
if key == "RTA_PREFSRC":
return cast(str, value)
return None
| def _first_ip_nexthop_from_route(routes: Iterable) -> str | None:
"""Find the first RTA_PREFSRC in the routes."""
_LOGGER.debug("Routes: %s", routes)
for route in routes:
for key, value in route["attrs"]:
if key == "RTA_PREFSRC":
return cast(str, value)
return None
|
41,225 | def state_vector_to_probabilities(state_vector: 'cirq.STATE_VECTOR_LIKE') -> np.ndarray:
normalized_vector = format(state_vector)
return np.abs(normalized_vector) ** 2
| def state_vector_to_probabilities(state_vector: 'cirq.STATE_VECTOR_LIKE') -> np.ndarray:
normalized_vector = format(state_vector)
return np.abs(valid_state_vector) ** 2
|
3,167 | def var(
values: np.ndarray,
mask: npt.NDArray[np.bool_],
*,
skipna: bool = True,
axis: int | None = None,
ddof: int = 1,
):
if not values.size or mask.all():
return libmissing.NA
return _reductions(
np.var, values=values, mask=mask, skipna=skipna, axis=axis, **{"ddof": ... | def var(
values: np.ndarray,
mask: npt.NDArray[np.bool_],
*,
skipna: bool = True,
axis: int | None = None,
ddof: int = 1,
):
if not values.size or mask.all():
return libmissing.NA
return _reductions(
np.var, values=values, mask=mask, skipna=skipna, axis=axis, ddof=ddof
... |
56,696 | def get_language_name(code):
lang = web.ctx.site.get('/languages/' + code)
return lang.name if lang else "'%s' unknown" % code
| def read_author_facet(author_facet: str) -> tuple[str, str]:
key, name = author_facet.split(' ', 1)
return key, name
"""
>>> read_author_facet("OL26783A Leo Tolstoy")
('OL26783A', 'Leo Tolstoy')
"""
key, name = author_facet.strip().split(' ', 1)
lang = web.ctx.site.get('/languages/' + ... |
56,435 | def main(): # noqa: C901, CCR001
"""Run the main code of the program."""
try:
# arg parsing
parser = argparse.ArgumentParser(
prog=appcmdname,
description='Prints the current system and station (if docked) to stdout and optionally writes player '
... | def main(): # noqa: C901, CCR001
"""Run the main code of the program."""
try:
# arg parsing
parser = argparse.ArgumentParser(
prog=appcmdname,
description='Prints the current system and station (if docked) to stdout and optionally writes player '
... |
14,628 | def compute_evaluation_metrics(metrics,
labels,
predictions,
model_type,
label_dict=None,
grid_objective=None,
probability=False,
... | def compute_evaluation_metrics(metrics,
labels,
predictions,
model_type,
label_dict=None,
grid_objective=None,
probability=False,
... |
23,224 | def import_ivar_by_name(name: str, prefixes: List[str] = [None], last_errors = None) -> Tuple[str, Any, Any, str]:
"""Import an instance variable that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
try:
name, attr = name.rsplit(".", 1)
real_... | def import_ivar_by_name(name: str, prefixes: List[str] = [None], last_errors = None) -> Tuple[str, Any, Any, str]:
"""Import an instance variable that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
try:
name, attr = name.rsplit(".", 1)
real_... |
35,646 | def resnet152(weights: Optional[ResNet152Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet:
if "pretrained" in kwargs:
warnings.warn("The argument pretrained is deprecated, please use weights instead.")
weights = ResNet152Weights.ImageNet1K_RefV1 if kwargs.pop("pretrained") else None
... | def resnet152(weights: Optional[ResNet152Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet:
if "pretrained" in kwargs:
warnings.warn("The argument pretrained is deprecated, please use weights instead.")
weights = ResNet152Weights.ImageNet1K_RefV1 if kwargs.pop("pretrained") else None
... |
23,676 | def gti_dirint(poa_global, aoi, solar_zenith, solar_azimuth, times,
surface_tilt, surface_azimuth, pressure=101325.,
use_delta_kt_prime=True, temp_dew=None, albedo=.25,
model='perez', model_perez='allsitescomposite1990',
calculate_gt_90=True, max_iterations=30... | def gti_dirint(poa_global, aoi, solar_zenith, solar_azimuth, times,
surface_tilt, surface_azimuth, pressure=101325.,
use_delta_kt_prime=True, temp_dew=None, albedo=.25,
model='perez', model_perez='allsitescomposite1990',
calculate_gt_90=True, max_iterations=30... |
22,323 | def clean_multiline_string(multiline_string, sep='\n'):
"""
Dedent, split, remove first and last empty lines, rejoin.
"""
multiline_string = textwrap.dedent(multiline_string)
string_list = multiline_string.split(sep)
if not string_list[0]:
string_list = string_list[1:]
if not string_... | def clean_multiline_string(multiline_string, sep='\n'):
"""
Dedent, split, remove first and last empty lines, rejoin.
"""
multiline_string = textwrap.dedent(multiline_string)
string_list = multiline_string.split(sep)
if not string_list[0]:
string_list = string_list[1:]
if not string_... |
46,697 | def create_new_key_pair(secret: bytes = None) -> KeyPair:
"""
Returns a new Secp256k1 keypair derived from the provided ``secret``,
a sequence of bytes corresponding to some integer between 0 and the group order.
A valid secret is created if ``None`` is passed.
"""
private_key = Secp256k1Privat... | def create_new_key_pair(secret: bytes = None) -> KeyPair:
"""
Returns a new Secp256k1 keypair derived from the provided ``secret``,
a sequence of bytes corresponding to some integer between 0 and the group order.
A valid secret is created if ``None`` is passed.
"""
private_key = Secp256k1Privat... |
54,863 | def laplacian_pe(g, k, padding=False, return_eigval=False):
r"""Laplacian Positional Encoding, as introduced in
`Benchmarking Graph Neural Networks
<https://arxiv.org/abs/2003.00982>`__
This function computes the laplacian positional encodings as the
k smallest non-trivial eigenvectors.
Parame... | def laplacian_pe(g, k, padding=False, return_eigval=False):
r"""Laplacian Positional Encoding, as introduced in
`Benchmarking Graph Neural Networks
<https://arxiv.org/abs/2003.00982>`__
This function computes the laplacian positional encodings as the
k smallest non-trivial eigenvectors.
Parame... |
52,356 | def maybe_base64(value: Optional[str]) -> Optional[str]:
if not value:
return None
elif set(value).issubset(_base64_alphabet):
return value
return base64.b64encode(value.encode()).decode()
| def decode_base64(value: Optional[str]) -> Optional[str]:
"""
Lazy decoding of base64-encoded data.
If the character set indicates a base64-encoded content, decoding is attempted and the result returned.
Otherwise, or if the decoding fails, the original string is returned.
"""
if not value:
... |
48,921 | def _array_repeat_op(translator, expr):
op = expr.op()
arr, times = op.args
arr_ = _parenthesize(translator, arr)
times_ = _parenthesize(translator, times)
repeat_fmt = '''
(select arrayFlatten(groupArray(arr)) from
(
select {} as arr
from system.numbers
... | def _array_repeat_op(translator, expr):
op = expr.op()
arr, times = op.args
arr_ = _parenthesize(translator, arr)
times_ = _parenthesize(translator, times)
repeat_fmt = '''
(select arrayFlatten(groupArray(arr)) from
(
select {arr_} as arr
from system.numbers... |
6,881 | def execute():
if frappe.db.exists("DocType", "Desk Page"):
if frappe.db.exists('DocType Workspace'):
# this patch was not added initially, so this page might still exist
frappe.delete_doc('DocType', 'Desk Page')
else:
rename_doc('DocType', 'Desk Page', 'Workspace')
rename_doc('DocType', 'Desk Chart', '... | def execute():
if frappe.db.exists("DocType", "Desk Page"):
if frappe.db.exists('DocType', 'Workspace'):
# this patch was not added initially, so this page might still exist
frappe.delete_doc('DocType', 'Desk Page')
else:
rename_doc('DocType', 'Desk Page', 'Workspace')
rename_doc('DocType', 'Desk Chart'... |
4,242 | def combine_evoked(all_evoked, weights):
"""Merge evoked data by weighted addition or subtraction.
Each `~mne.Evoked` in ``all_evoked`` should have the same channels and the
same time instants. Subtraction can be performed by passing
``weights=[1, -1]``.
.. Warning::
Other than cases like ... | def combine_evoked(all_evoked, weights):
"""Merge evoked data by weighted addition or subtraction.
Each `~mne.Evoked` in ``all_evoked`` should have the same channels and the
same time instants. Subtraction can be performed by passing
``weights=[1, -1]``.
.. Warning::
Other than cases like ... |
24,308 | def render_logs_progress():
valid_checks = sorted(get_valid_checks())
total_checks = len(valid_checks)
checks_with_logs = 0
lines = ['## Logs specs', '', None, '', '??? check "Completed"']
for check in valid_checks:
config_file = get_config_file(check)
status = ' '
tile_onl... | def render_logs_progress():
valid_checks = sorted(get_valid_checks())
total_checks = len(valid_checks)
checks_with_logs = 0
lines = ['## Logs specs', '', None, '', '??? check "Completed"']
for check in valid_checks:
config_file = get_config_file(check)
status = ' '
tile_onl... |
29,153 | def require_valid_meta_tag_content(meta_tag_content):
"""Generic meta tag content validation.
Args:
meta_tag_content: str. The meta tag content to validate.
Raises:
Exception. Meta tag content is not a string.
Exception. Meta tag content is long.
"""
... | def require_valid_meta_tag_content(meta_tag_content):
"""Generic meta tag content validation.
Args:
meta_tag_content: str. The meta tag content to validate.
Raises:
Exception. Meta tag content is not a string.
Exception. Meta tag content is longer than expected.... |
55,402 | def _check_spark_version_in_range(ver, min_ver, max_ver):
if Version(ver) > Version(min_ver):
ver = _reset_minor_version(ver)
return _check_version_in_range(ver, min_ver, max_ver)
| def _check_spark_version_in_range(ver, min_ver, max_ver):
parsed_ver = Version(ver)
if parsed_ver > Version(min_ver):
ver = f"{parsed_ver.major}.{parsed_ver.minor}"
return _check_version_in_range(ver, min_ver, max_ver)
|
14,338 | def buildCOLR(
colorGlyphs: _ColorGlyphsDict,
version: int = 0,
glyphMap: Optional[Mapping[str, int]] = None,
varStore: Optional[ot.VarStore] = None,
) -> C_O_L_R_.table_C_O_L_R_:
"""Build COLR table from color layers mapping.
Args:
colorGlyphs: If version == 0, a map of base glyph name... | def buildCOLR(
colorGlyphs: _ColorGlyphsDict,
version: int = 0,
glyphMap: Optional[Mapping[str, int]] = None,
varStore: Optional[ot.VarStore] = None,
) -> C_O_L_R_.table_C_O_L_R_:
"""Build COLR table from color layers mapping.
Args:
colorGlyphs: If version == 0, a map of base glyph name... |
54,446 | def _get_edf_plot(studies: List[Study]) -> "go.Figure":
if len(studies) == 0:
raise ValueError("No studies were given.")
layout = go.Layout(
title="EDF Plot",
xaxis={"title": "Objective Value"},
yaxis={"title": "Cumulative Probability"},
)
all_trials = list(
ite... | def _get_edf_plot(studies: List[Study]) -> "go.Figure":
if len(studies) == 0:
raise ValueError("No studies were given.")
layout = go.Layout(
title="EDF Plot",
xaxis={"title": "Objective Value"},
yaxis={"title": "Cumulative Probability"},
)
all_trials = list(
ite... |
31,320 | def get_domain_details(client: Client, **args) -> CommandResults:
domain = args.get("domain")
uri = f"/domain/{domain}"
response = client._http_request("GET", uri)
md = ""
current_dns = response["current_dns"]
del response["current_dns"]
md = tableToMarkdown(f"Details for {domain}", respons... | def get_domain_details(client: Client, **args) -> CommandResults:
domain = args.get("domain")
uri = f"/domain/{domain}"
response = client._http_request("GET", uri)
md = ""
current_dns = response["current_dns"]
del response["current_dns"]
md = tableToMarkdown(f"Details for {domain}", respons... |
23,398 | def process_search_results(results):
"""
Transform result representation from the output of the widget to the
test framework comparison representation.
"""
matches = {}
for result in results.values():
file, line, col, _ = result
filename = osp.basename(file)
if filename n... | def process_search_results(results):
"""
Transform result representation from the output of the widget to the
test framework comparison representation.
"""
matches = {}
for result in results.values():
file, line, col, __ = result
filename = osp.basename(file)
if filename ... |
56,968 | def get_plain_text(secret: Union[SecretStr, SecretBytes, None, str]) -> Optional[str]:
if secret:
return secret.get_secret_value()
else:
return secret
| def get_plain_text(secret: Union[SecretStr, SecretBytes, None, str]) -> Optional[str]:
try:
return secret.get_secret_value()
except AttributeError:
return secret
|
2,533 | def fetch_openml(
name: Optional[str] = None,
*,
version: Union[str, int] = "active",
data_id: Optional[int] = None,
data_home: Optional[str] = None,
target_column: Optional[Union[str, List]] = "default-target",
cache: bool = True,
return_X_y: bool = False,
as_frame: Union[str, bool]... | def fetch_openml(
name: Optional[str] = None,
*,
version: Union[str, int] = "active",
data_id: Optional[int] = None,
data_home: Optional[str] = None,
target_column: Optional[Union[str, List]] = "default-target",
cache: bool = True,
return_X_y: bool = False,
as_frame: Union[str, bool]... |
1,106 | def test_rebase_path_traits():
"""Check rebase_path_traits."""
spec = _test_spec()
a = rebase_path_traits(
spec.trait('a'), '/some/path/f1.txt', '/some/path')
assert '%s' % a == 'f1.txt'
b = rebase_path_traits(
spec.trait('b'), ('/some/path/f1.txt', '/some/path/f2.txt'), '/some/pat... | def test_rebase_path_traits():
"""Check rebase_path_traits."""
spec = _test_spec()
a = rebase_path_traits(
spec.trait('a'), '/some/path/f1.txt', '/some/path')
assert a == Path('f1.txt')
b = rebase_path_traits(
spec.trait('b'), ('/some/path/f1.txt', '/some/path/f2.txt'), '/some/path... |
30,534 | def get_request_args(params):
limit = request.args.get('n', None)
offset = request.args.get('s', None)
out_format = request.args.get('v', None)
query = request.args.get('q', None)
if limit is None:
limit = try_parse_integer(params.get('list_size'), CTX_LIMIT_ERR_MSG)
else:
limi... | def get_request_args(params):
limit = request.args.get('n', None)
offset = request.args.get('s', None)
out_format = request.args.get('v', params.get('format'))
query = request.args.get('q', None)
if limit is None:
limit = try_parse_integer(params.get('list_size'), CTX_LIMIT_ERR_MSG)
el... |
44,119 | def kahypar_cut(
num_fragments: int,
adjacent_nodes: List[int],
edge_splits: List[int],
imbalance: int = None,
edge_weights: List[Union[int, float]] = None,
node_weights: List[Union[int, float]] = None,
block_weights: List[Union[int, float]] = None,
edges: Iterable[Any] = None,
seed:... | def kahypar_cut(
num_fragments: int,
adjacent_nodes: List[int],
edge_splits: List[int],
imbalance: int = None,
edge_weights: List[Union[int, float]] = None,
node_weights: List[Union[int, float]] = None,
fragment_weights: List[Union[int, float]] = None,
edges: Iterable[Any] = None,
se... |
31,214 | def mantis_get_issue_by_id_command(client, args):
"""
Returns Hello {somename}
Args:
client (Client): Mantis client.
args (dict): all command arguments.
Returns:
Mantis
"""
_id = args.get('id')
resp = client.get_issue(_id).get('issues')[0]
issues = create_output... | def mantis_get_issue_by_id_command(client, args):
"""
Returns Hello {somename}
Args:
client (Client): Mantis client.
args (dict): all command arguments.
Returns:
Mantis
"""
_id = args.get('id')
resp = client.get_issue(_id).get('issues')[0]
issues = create_output... |
30,974 | def results_return(command, thingtoreturn):
for item in thingtoreturn:
description = ''
ip_reputation = {
'indicator': item['Address'],
}
try:
if item['Malicious']['Vendor']:
score = Common.DBotScore.BAD
description = ip_reputat... | def results_return(command, thingtoreturn):
for item in thingtoreturn:
description = ''
ip_reputation = {
'indicator': item['Address'],
}
try:
if item['Malicious']['Vendor']:
score = Common.DBotScore.BAD
description = ip_reputat... |
33,011 | def parse_arguments():
parser = argparse.ArgumentParser(
prog="spotdl",
description=help_notice,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"query", type=str, nargs="+", help="URL/String for a song/album/playlist/artist"
)
parser.add_... | def parse_arguments():
parser = argparse.ArgumentParser(
prog="spotdl",
description=help_notice,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"query", type=str, nargs="+", help="URL/String for a song/album/playlist/artist"
)
parser.add_... |
41,206 | def decompose_clifford_tableau_to_operations(
qubits: List['cirq.Qid'], clifford_tableau: qis.CliffordTableau
) -> List[ops.Operation]:
"""Decompose an n-qubit Clifford Tableau into a list of one/two qubit operations.
Args:
qubits: The list of qubits being operated on.
clifford_tableau: The... | def decompose_clifford_tableau_to_operations(
qubits: List['cirq.Qid'], clifford_tableau: qis.CliffordTableau
) -> List[ops.Operation]:
"""Decompose an n-qubit Clifford Tableau into a list of one/two qubit operations.
Args:
qubits: The list of qubits being operated on.
clifford_tableau: The... |
35,436 | def panda_state_function(q: Queue):
pm = messaging.PubMaster(['pandaState'])
while 1:
if not q.empty():
if q.get() == "quit":
break
dat = messaging.new_message('pandaState')
dat.valid = True
dat.pandaState = {
'ignitionLine': True,
'pandaType': "blackPanda",
'control... | def panda_state_function(q: Queue):
pm = messaging.PubMaster(['pandaState'])
while not exit_event.is_set():
dat = messaging.new_message('pandaState')
dat.valid = True
dat.pandaState = {
'ignitionLine': True,
'pandaType': "blackPanda",
'controlsAllowed': True,
'safetyModel': 'hon... |
14,632 | def _munge_featureset_name(featureset):
"""
Joins features in ``featureset`` by '+' if ``featureset`` is not a string.
Otherwise, returns ``featureset``.
Parameters
----------
featureset : SKLL.FeatureSet
A SKLL ``FeatureSet`` object.
Returns
-------
res : str
``fea... | def _munge_featureset_name(featureset):
"""
Joins features in ``featureset`` by '+' if ``featureset`` is not a string.
Otherwise, returns ``featureset``.
Parameters
----------
featureset : skll.data.FeatureSet
A SKLL ``FeatureSet`` object.
Returns
-------
res : str
... |
22,095 | def rec_iter(
filenames: List[str],
sensor: Optional[str],
ignore_rules: Dict[str, Dict[str, List[Tuple[int, int]]]],
) -> Generator[Record, None, None]:
ignorenets = ignore_rules.get("IGNORENETS", {})
neverignore = ignore_rules.get("NEVERIGNORE", {})
for fname in filenames:
with P0fFile... | def rec_iter(
filenames: List[str],
sensor: Optional[str],
ignore_rules: Dict[str, Dict[str, List[Tuple[int, int]]]],
) -> Generator[Record, None, None]:
ignorenets = ignore_rules.get("IGNORENETS", {})
neverignore = ignore_rules.get("NEVERIGNORE", {})
for fname in filenames:
with P0fFile... |
41,571 | def get_parameters():
parser = argparse.ArgumentParser(description='This script is curating dataset data_axondeepseg_tem to BIDS')
# Define input path
parser.add_argument("-d", "--data",
help="Path to folder containing the dataset to be curated",
required=True... | def get_parameters():
parser = argparse.ArgumentParser(description='This script is curating the demo dataset to BIDS')
# Define input path
parser.add_argument("-d", "--data",
help="Path to folder containing the dataset to be curated",
required=True)
# Defi... |
24,824 | def implements(obj: "Interface", interface: Tuple[type, type]) -> bool:
"""Return whether the give object (maybe an instance or class) implements
the interface.
"""
kimplements = getattr(obj, "__implements__", ())
if not isinstance(kimplements, (list, tuple)):
kimplements = (kimplements,)
... | def implements(obj: "Interface", interface: Tuple[type, type]) -> bool:
"""Return whether the give object (maybe an instance or class) implements
the interface.
"""
kimplements = getattr(obj, "__implements__", ())
if not isinstance(kimplements, (list, tuple)):
kimplements = (kimplements,)
... |
43,986 | def qnode_spectrum(qnode, encoding_args=None, argnum=None, decimals=8, validation_kwargs=None):
r"""Compute the frequency spectrum of the Fourier representation of quantum circuits,
including classical preprocessing.
The circuit must only use gates as input-encoding gates that can be decomposed
into si... | def qnode_spectrum(qnode, encoding_args=None, argnum=None, decimals=8, validation_kwargs=None):
r"""Compute the frequency spectrum of the Fourier representation of quantum circuits,
including classical preprocessing.
The circuit must only use gates as input-encoding gates that can be decomposed
into si... |
40,596 | def voronoi_partition_pts(points, outline, no_multipolygons=False):
"""
Compute the polygons of a voronoi partition of `points` within the
polygon `outline`. Taken from
https://github.com/FRESNA/vresutils/blob/master/vresutils/graph.py
Attributes
----------
points : Nx2 - ndarray[dtype=float... | def voronoi_partition_pts(points, outline, no_multipolygons=False):
"""
Compute the polygons of a voronoi partition of `points` within the
polygon `outline`. Taken from
https://github.com/FRESNA/vresutils/blob/master/vresutils/graph.py
Attributes
----------
points : Nx2 - ndarray[dtype=float... |
57,822 | def email_command(client, args, email_suspicious_score_threshold, email_malicious_score_threshold, reliability):
emails = argToList(args.get("email"), ",")
results = []
for email in emails:
result = client.get_email_reputation(email)
result['address'] = email
human_readable = tableT... | def email_command(client, args, email_suspicious_score_threshold, email_malicious_score_threshold, reliability):
emails = argToList(args.get("email"), ",")
results = []
for email in emails:
result = client.get_email_reputation(email)
result['address'] = email
human_readable = tableT... |
43,936 | def nuclear_attraction(la, lb, ra, rb, alpha, beta, r):
r"""Compute nuclear attraction integral between primitive Gaussian functions.
The nuclear attraction integral between two Gaussian functions denoted by :math:`a` and
:math:`b` can be computed as
[`Helgaker (1995) p820 <https://www.worldscientific.... | def nuclear_attraction(la, lb, ra, rb, alpha, beta, r):
r"""Compute nuclear attraction integral between primitive Gaussian functions.
The nuclear attraction integral between two Gaussian functions denoted by :math:`a` and
:math:`b` can be computed as
[`Helgaker (1995) p820 <https://www.worldscientific.... |
36,193 | def language_code_to_iso_3166(language):
"""Turn a language name (en-us) into an ISO 3166 format (en-US)."""
language, _, country = language.lower().partition('-')
if country:
return language + '-' + country.upper()
return language
| def language_code_to_iso_3166(language):
"""Turn a language name (en-us) into an ISO 3166 format (en-US)."""
language, _, country = language.lower().partition('-')
if country:
return f'{language}-{country.upper()}'
return language
|
27,779 | def pytest_collect_file(
fspath: Path, path: py.path.local, parent: Collector,
) -> Optional[Union["DoctestModule", "DoctestTextfile"]]:
config = parent.config
if fspath.suffix == ".py":
if config.option.doctestmodules and not _is_setup_py(fspath):
mod: DoctestModule = DoctestModule.from... | def pytest_collect_file(
fspath: Path, parent: Collector
) -> Optional[Union["DoctestModule", "DoctestTextfile"]]:
config = parent.config
if fspath.suffix == ".py":
if config.option.doctestmodules and not _is_setup_py(fspath):
mod: DoctestModule = DoctestModule.from_parent(parent, fspath... |
14,113 | def test_fsspec_url():
fsspec = pytest.importorskip("fsspec")
import fsspec.implementations.memory
class MyMemoryFileSystem(fsspec.implementations.memory.MemoryFileSystem):
# Simple fsspec filesystem that adds a required keyword.
# Attempting to use this filesystem without the keyword will ... | def test_fsspec_url():
fsspec = pytest.importorskip("fsspec")
import fsspec.implementations.memory
class MyMemoryFileSystem(fsspec.implementations.memory.MemoryFileSystem):
# Simple fsspec filesystem that adds a required keyword.
# Attempting to use this filesystem without the keyword will ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.