text
stringlengths 15
7.82k
| ids
sequencelengths 1
7
|
---|---|
def METHOD_NAME(vault_identity, use_system_assigned_msi, identity_id):
if (use_system_assigned_msi or identity_id) and vault_identity is None:
raise ArgumentUsageError("Please ensure that Selected MI is enabled for the vault")
if use_system_assigned_msi:
if vault_identity.type is None or "systemassigned" not in vault_identity.type.lower():
raise ArgumentUsageError("Please ensure that System MI is enabled for the vault")
if identity_id:
if vault_identity.type is not None and "userassigned" in vault_identity.type.lower():
if identity_id.lower() not in (id.lower() for id in vault_identity.user_assigned_identities.keys()):
raise ArgumentUsageError("""
Vault does not have the specified User MI.
Please ensure you've provided the correct --mi-user-assigned.
""")
else:
raise ArgumentUsageError("Please ensure that User MI is enabled for the vault") | [
187,
2353,
1304,
43,
1032,
3033
] |
def METHOD_NAME(self):
self.worldNP = render.attach_new_node('World')
# World
self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
self.debugNP.show()
self.debugNP.node().show_wireframe(True)
self.debugNP.node().show_constraints(True)
self.debugNP.node().show_bounding_boxes(False)
self.debugNP.node().show_normals(False)
self.world = BulletWorld()
self.world.set_gravity((0, 0, -9.81))
self.world.set_debug_node(self.debugNP.node())
# Ground
shape = BulletPlaneShape((0, 0, 1), 0)
body = BulletRigidBodyNode('Ground')
bodyNP = self.worldNP.attach_new_node(body)
bodyNP.node().add_shape(shape)
bodyNP.set_pos(0, 0, 0)
bodyNP.set_collide_mask(BitMask32.all_on())
self.world.attach(bodyNP.node())
# Bowl
visNP = loader.load_model('models/bowl.egg')
geom = (visNP.findAllMatches('**/+GeomNode')
.get_path(0).node().get_geom(0))
mesh = BulletTriangleMesh()
mesh.addGeom(geom)
shape = BulletTriangleMeshShape(mesh, dynamic=True)
body = BulletRigidBodyNode('Bowl')
bodyNP = self.worldNP.attach_new_node(body)
bodyNP.node().add_shape(shape)
bodyNP.node().set_mass(10.0)
bodyNP.set_pos(0, 0, 0)
bodyNP.set_collide_mask(BitMask32.all_on())
self.world.attach(bodyNP.node())
visNP.reparent_to(bodyNP)
self.bowlNP = bodyNP
self.bowlNP.set_scale(2)
# Eggs
self.eggNPs = []
for i in range(5):
x = random.gauss(0, 0.1)
y = random.gauss(0, 0.1)
z = random.gauss(0, 0.1) + 1
h = random.random() * 360
p = random.random() * 360
r = random.random() * 360
visNP = loader.load_model('models/egg.egg')
geom = (visNP.find_all_matches('**/+GeomNode')
.get_path(0).node().get_geom(0))
shape = BulletConvexHullShape()
shape.addGeom(geom)
body = BulletRigidBodyNode('Egg-%i' % i)
bodyNP = self.worldNP.attach_new_node(body)
bodyNP.node().set_mass(1.0)
bodyNP.node().add_shape(shape)
bodyNP.node().set_deactivation_enabled(False)
bodyNP.set_collide_mask(BitMask32.all_on())
bodyNP.set_pos_hpr(x, y, z, h, p, r)
#bodyNP.set_scale(1.5)
self.world.attach(bodyNP.node())
visNP.reparent_to(bodyNP)
self.eggNPs.append(bodyNP) | [
102
] |
def METHOD_NAME(self):
return torch.optim.SGD(self.layer.parameters(), lr=0.1) | [
111,
6915
] |
def METHOD_NAME(ref_filter=None):
"""Return all the existing refs in this repository, optionally filtering the refs."""
ref_output = check_output(['git', 'for-each-ref', '--format=%(refname)\t%(objecttype)\t%(*objecttype)'])
ref_split = [tuple(iter_extend(l.rsplit('\t'), 3)) for l in ref_output.splitlines()]
if ref_filter:
ref_split = (e for e in ref_split if ref_filter(*e))
refs = [r[0] for r in ref_split]
return refs | [
19,
75,
2925
] |
def METHOD_NAME():
return GetPoolInformationHelper("ju") | [
19,
1567,
1691
] |
def METHOD_NAME(a, b, c, alpha, beta, gamma):
alpha, beta, gamma = DEG2RAD*alpha, DEG2RAD*beta, DEG2RAD*gamma
return a*b*c*(1-cos(alpha)**2-cos(beta)**2-cos(gamma)**2+
2*cos(alpha)*cos(beta)*cos(gamma))**0.5 | [
805,
118,
2276
] |
def METHOD_NAME(self):
self.assertEqual("Diner, Kerstrecepten", self.harvester_class.category()) | [
9,
253
] |
def METHOD_NAME():
actions.key("left") | [
879
] |
def METHOD_NAME(self) -> Sequence[str]:
"""
List of string resources.
"""
return pulumi.get(self, "properties") | [
748
] |
def METHOD_NAME():
container = InstanceContainer(container_id="intent container")
container.setMetaDataEntry("type", "intent")
return container | [
9090,
224
] |
def METHOD_NAME():
result = render_root(part=live_edit_view(req('get'), part_based_view, args=(), kwargs={}).bind(request=req('get')))
assert 'class PartBasedViewPage' in result, result | [
9,
1824,
2004,
995
] |
def METHOD_NAME(self):
return f"{self.gpt3Agent.init_prompt}{self.gpt3Agent.turns}" | [
19,
351,
3
] |
def METHOD_NAME(Name, ConnectionCredential, Ensure):
arg_names = list(locals().keys())
retval = 0
(Name, ConnectionCredential, Ensure) = init_vars(Name, ConnectionCredential, Ensure)
(Name, ConnectionCredential, Ensure) = Get(Name, ConnectionCredential, Ensure)
Name = protocol.MI_String(Name)
ConnectionCredential = protocol.MI_String(ConnectionCredential)
Ensure = protocol.MI_String(Ensure)
retd = {}
ld = locals()
for k in arg_names:
retd[k] = ld[k]
return retval, retd | [
19,
9043
] |
def METHOD_NAME(workload, _):
"""Infer input/output shapes and layouts from a workload and cfg.
Parameters
----------
workload : tuple
conv2d workload
cfg : tuple
tvm.autotvm config
Returns
-------
Output : [tuple of tuple and str, tuple of tuple and str]
Input shapes and layouts, and output shapes and layouts
"""
_, data, kernel, strides, padding, _, _ = workload
batch_size, in_channel, in_height, in_width = data[1]
filter_channel, channel_multiplier, k_height, k_width = kernel[1]
out_channel = filter_channel * channel_multiplier
out_height = (in_height + 2 * padding[0] - k_height) // strides[0] + 1
out_width = (in_width + 2 * padding[1] - k_width) // strides[1] + 1
in_shape = (batch_size, in_channel, in_height, in_width)
out_shape = (batch_size, out_channel, out_height, out_width)
in_layout = out_layout = "NCHW"
return ((in_shape, in_layout),), ((out_shape, out_layout),) | [
4611,
3385,
1852,
571
] |
def METHOD_NAME(self, sites: Union[int, list]) -> Optional["Spin"]:
if isinstance(sites, int):
sites = [sites]
for site in sites:
if site < 0 or site >= self.size:
raise ValueError(
f"Site {site} not in this hilbert space of site {self.size}"
)
if self._total_sz is not None:
raise TypeError(
"Cannot take the partial trace with a total magnetization constraint."
)
Nsites = len(sites)
if self.size - Nsites == 0:
return None
else:
return Spin(s=self._s, N=self.size - Nsites) | [
15805
] |
def METHOD_NAME(self):
return os.path.join("lib", "cmake", f"conan-official-{self.name}-targets.cmake") | [
298,
171,
2071,
157
] |
def METHOD_NAME(self):
if not hasattr(self, "_collab") or not self._collab:
self._collab = _str_with_64_char(self.xml_with_pre.collab)
return self._collab | [
2079,
14531
] |
def METHOD_NAME(request, path):
obj = parse_path(request, path, (Project, Component, Translation))
if not request.user.has_perm("vcs.reset", obj):
raise PermissionDenied
return execute_locked(
request,
obj,
gettext("All repositories have been reset."),
obj.do_reset,
request,
) | [
656
] |
def METHOD_NAME(x, grad_output):
m = torch.ones_like(x) * ((x >= -3.) & (x <= 3.)) / 6.
return grad_output * m | [
388,
2709,
3821,
5299
] |
def METHOD_NAME(satosa_config):
"""
Creates SAML metadata strings for the configured front- and backends.
:param satosa_config: configuration of the proxy
:return: a tuple of the frontend metadata (containing IdP entities) and the backend metadata (containing SP
entities).
:type satosa_config: satosa.satosa_config.SATOSAConfig
:rtype: Tuple[str, str]
"""
frontend_modules = load_frontends(satosa_config, None, satosa_config["INTERNAL_ATTRIBUTES"])
backend_modules = load_backends(satosa_config, None, satosa_config["INTERNAL_ATTRIBUTES"])
logger.info("Loaded frontend plugins: {}".format([frontend.name for frontend in frontend_modules]))
logger.info("Loaded backend plugins: {}".format([backend.name for backend in backend_modules]))
backend_metadata = _create_backend_metadata(backend_modules)
frontend_metadata = _create_frontend_metadata(frontend_modules, backend_modules)
return frontend_metadata, backend_metadata | [
129,
2419,
3265
] |
def METHOD_NAME(s):
output_buffer.append(s.rstrip())
return len(s) | [
77
] |
async def METHOD_NAME(self) -> None:
"""
Start the process for receiving events.
"""
raise NotImplementedError("start_events_async must be implemented for {}".format(self.__class__.__name__)) | [
447,
239,
958
] |
def METHOD_NAME(self):
self.assertEqual(threading.Lock, threading._Lock)
self.assertEqual(threading.RLock, threading._RLock) | [
9,
949,
-1,
295
] |
def METHOD_NAME(self):
"""
Uncover all combinations
"""
self.total_covered_more_than_ones = 0
self.total_uncovered = 0
for _, value in self.hash_table.items():
value.completely_uncover()
self.total_uncovered += value.uncovered | [
18108
] |
def METHOD_NAME(self, secret_id: str) -> str:
return f"{self.prefix}{secret_id}" | [
19,
324,
444,
147
] |
def METHOD_NAME(tmp_path):
"""Test updating a file with Nimrod-format Radarnet data"""
kgo_dir = acc.kgo_root() / "standardise/radarnet"
kgo_path = kgo_dir / "kgo_coverage.nc"
input_path = kgo_dir / "input_coverage.nimrod"
output_path = tmp_path / "output.nc"
args = [input_path, "--output", output_path]
run_cli(args)
acc.compare(output_path, kgo_path) | [
9,
12544,
-1,
756
] |
def METHOD_NAME(self):
return {"pp": self.pp, "gp": self.gp, "ep": self.ep, "sp": self.sp, "cp": self.cp} | [
24,
553
] |
def METHOD_NAME(self,key):
return self.data_container.get(key) | [
19
] |
def METHOD_NAME(self):
printer = QPrinter()
dlg = QPrintDialog(printer, self)
dlg.setWindowTitle(app.caption(_("Print")))
options = (QAbstractPrintDialog.PrintToFile
| QAbstractPrintDialog.PrintShowPageSize
| QAbstractPrintDialog.PrintPageRange)
if self.browser.textCursor().hasSelection():
options |= QAbstractPrintDialog.PrintSelection
dlg.setOptions(options)
if dlg.exec_():
self.browser.METHOD_NAME(printer) | [
38
] |
def METHOD_NAME(kwargs):
"""Return kwargs or an empty dict.
We often pass named kwargs (like `sarimax_kwargs`) as None by default. This
is to avoid a mutable default, which can bite you in unexpected ways. This
will return a kwarg-compatible value.
"""
if kwargs:
return kwargs
return {} | [
250,
1475
] |
def METHOD_NAME(args):
if args.key is not None:
key = b64decode(args.key.encode("utf-8"))
elif args.password is not None:
key = kdf_gen_key(args.password, args.kdf_salt, args.kdf_iters)
else:
raise ValueError("Neither password nor key is provided")
tag = args.gcm_tag.encode("utf-8")
outputBuffer = io.BytesIO()
with Path(args.infile).open("rb") as in_:
decorated(key, in_, outputBuffer, tag)
with Path(args.outfile).open("wb") as out:
out.write(outputBuffer.getbuffer()) | [
291
] |
def METHOD_NAME(self, is_inside_record_or_union: bool) -> Self | None:
next_content = self._content.METHOD_NAME(is_inside_record_or_union)
if next_content is None:
return None
else:
return UnmaskedForm(
next_content,
parameters=self._parameters,
form_key=self._form_key,
) | [
3724,
1951
] |
def METHOD_NAME():
"""Test getting of fix."""
fix = Fix.get_fixes('CMIP6', 'FIO-ESM-2-0', 'Omon', 'tos')
assert fix == [OceanFixGrid(None), Omon(None)] | [
9,
19,
3181,
1112
] |
def METHOD_NAME():
print(""" | [
38,
40
] |
def METHOD_NAME():
@deprecated(sdk_version="2.66.6")
class SampleClass:
def __init__(self):
pass
with pytest.warns(DeprecationWarning) as w:
SampleClass()
msg = (
"SampleClass is a no-op in sagemaker>=2.66.6.\n"
"See: https://sagemaker.readthedocs.io/en/stable/v2.html for details."
)
assert str(w[-1].message) == msg | [
9,
2497,
43,
2
] |
def METHOD_NAME(y, x=None, dx=1.0, axis=-1):
"""
Integrate along the given axis using the composite trapezoidal rule.
Integrate `y` (`x`) along given axis.
Parameters
----------
y : array_like
Input tensor to integrate.
x : array_like, optional
The sample points corresponding to the `y` values. If `x` is None,
the sample points are assumed to be evenly spaced `dx` apart. The
default is None.
dx : scalar, optional
The spacing between sample points when `x` is None. The default is 1.
axis : int, optional
The axis along which to integrate.
Returns
-------
trapz : float
Definite integral as approximated by trapezoidal rule.
See Also
--------
sum, cumsum
Notes
-----
Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
will be taken from `y` tensor, by default x-axis distances between
points will be 1.0, alternatively they can be provided with `x` tensor
or with `dx` scalar. Return value will be equal to combined area under
the red lines.
References
----------
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
.. [2] Illustration image:
https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
Examples
--------
>>> import mars.tensor as mt
>>> mt.trapz([1,2,3]).execute()
4.0
>>> mt.trapz([1,2,3], x=[4,6,8]).execute()
8.0
>>> mt.trapz([1,2,3], dx=2).execute()
8.0
>>> a = mt.arange(6).reshape(2, 3)
>>> a.execute()
array([[0, 1, 2],
[3, 4, 5]])
>>> mt.trapz(a, axis=0).execute()
array([1.5, 2.5, 3.5])
>>> mt.trapz(a, axis=1).execute()
array([2., 8.])
"""
y = astensor(y)
axis = validate_axis(y.ndim, axis)
op = TensorTrapz(y=y, x=x, dx=dx, axis=axis)
return op(y, x=x) | [
-1
] |
def METHOD_NAME():
fname = os.path.join(resources, 'hms_lincs_extra.tsv')
with open(fname, 'r') as fh:
rows = [line.strip('\n').split('\t') for line in fh.readlines()]
return {r[0]: {'HMS LINCS ID': r[0],
'Name': r[1],
'ChEMBL ID': r[2] if r[2] else ''}
for r in rows[1:]} | [
557,
-1,
6735
] |
def METHOD_NAME(self) -> None:
transform_result = (
self.pipeline
| beam.Create(['item', 'item', 'item'])
| job_result_transforms.CountObjectsToJobRunResult('PREFIX')
)
self.assert_pcoll_equal(
transform_result,
[job_run_result.JobRunResult.as_stdout('PREFIX SUCCESS: 3')]
) | [
9,
2756,
635,
41,
426,
3705,
141
] |
def METHOD_NAME(diabetes_split_dataset_and_model):
_, test, clf = diabetes_split_dataset_and_model
check = RegressionErrorDistribution().add_condition_kurtosis_greater_than(threshold=1)
# Act
result = check.conditions_decision(check.run(test, clf))
assert_that(result, has_items(
equal_condition_result(is_pass=False,
name='Kurtosis value higher than 1',
details='Found kurtosis value of 0.02867',
category=ConditionCategory.WARN)
)) | [
9,
405,
4653,
15803,
130,
3657,
489
] |
def METHOD_NAME(self, fst) -> 'pynini.FstLike':
"""
Wraps class name around to given fst
Args:
fst: input fst
Returns:
Fst: fst
"""
return pynutil.insert(f"{self.name} {{ ") + fst + pynutil.insert(" }") | [
238,
1735
] |
def METHOD_NAME(self):
atom1 = Atom(name="atom1")
atom2 = Atom(name="atom2")
atom3 = Atom(name="atom3")
connect = Angle(connection_members=[atom1, atom2, atom3])
assert connect.angle_type is None | [
9,
3057,
-1
] |
METHOD_NAME(self): | [
9,
1412,
452,
194,
2592,
1717,
1597
] |
def METHOD_NAME(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
if o != 0:
return self._tab.VectorLen(o)
return 0 | [
288,
799
] |
f METHOD_NAME(self): | [
9,
0,
285,
641
] |
def METHOD_NAME(self, read_net):
with core.NameScope(read_net.NextName(self.name)):
status = read_net.NextName()
fields = read_net.SafeDequeueBlobs(
self.blobs_queue, self._schema.field_names() + [status])
return (fields[-1], fields[:-1]) | [
203
] |
async def METHOD_NAME(self, client):
await client.number.put_small_float(3.402823e-20)
assert (await client.number.get_small_float()) == 3.402823e-20 | [
9,
565,
1819
] |
def METHOD_NAME():
store = NdarrayStore()
assert not store.can_write(None, None, np.array([object()])) | [
9,
3438,
77,
635
] |
def METHOD_NAME(event):
self.press = None
ax.figure.canvas.draw() | [
69,
586
] |
def METHOD_NAME(self, analysis_plugin, stub_object, tmpdir):
random_file = Path(tmpdir.dirname, 'random')
random_file.write_bytes(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
stub_object.file_path = str(random_file.absolute())
result = analysis_plugin._analyze_elf(stub_object)
assert result == {} | [
9,
902,
2892,
1068,
171
] |
def METHOD_NAME(
self,
hdr: foundation.ZCLHeader,
args: List[Any],
*,
dst_addressing: Optional[
Union[t.Addressing.Group, t.Addressing.IEEE, t.Addressing.NWK]
] = None,
):
"""Handle the cluster command."""
_LOGGER.debug(
"PhilipsRemoteCluster - handle_cluster_request tsn: [%s] command id: %s - args: [%s]",
hdr.tsn,
hdr.command_id,
args,
)
button = self.BUTTONS.get(args[0], args[0])
press_type = self.PRESS_TYPES.get(args[2], args[2])
event_args = {
BUTTON: button,
PRESS_TYPE: press_type,
COMMAND_ID: hdr.command_id,
ARGS: args,
}
def send_press_event(click_count):
_LOGGER.debug(
"PhilipsRemoteCluster - send_press_event click_count: [%s]", click_count
)
press_type = None
if click_count == 1:
press_type = "press"
elif click_count == 2:
press_type = "double_press"
elif click_count == 3:
press_type = "triple_press"
elif click_count == 4:
press_type = "quadruple_press"
elif click_count > 4:
press_type = "quintuple_press"
if press_type:
# Override PRESS_TYPE
event_args[PRESS_TYPE] = press_type
action = f"{button}_{press_type}"
self.listener_event(ZHA_SEND_EVENT, action, event_args)
# Derive Multiple Presses
if press_type == "press":
self.button_press_queue.press(send_press_event, button)
else:
action = f"{button}_{press_type}"
self.listener_event(ZHA_SEND_EVENT, action, event_args) | [
276,
2059,
377
] |
def METHOD_NAME(self):
self.cpp_info.set_property("pkg_config_name", "libupnp")
self.cpp_info.libs = ["upnp", "ixml"]
self.cpp_info.includedirs.append(os.path.join("include", "upnp"))
if self.settings.os in ["Linux", "FreeBSD"]:
self.cpp_info.system_libs.extend(["pthread"])
self.cpp_info.cflags.extend(["-pthread"])
self.cpp_info.cxxflags.extend(["-pthread"])
elif self.settings.os == "Windows":
self.cpp_info.system_libs.extend(["iphlpapi", "ws2_32"]) | [
360,
100
] |
def METHOD_NAME(name):
"""Gets an implementation of a fuzzing engine, or None if one does not
exist."""
engine_class = _ENGINES.METHOD_NAME(name)
if engine_class:
return engine_class()
return None | [
19
] |
def METHOD_NAME():
"""
:return: True if the ase module can be imported, False otherwise.
"""
# pylint: disable=unused-import,unused-variable
try:
import MySQLdb
except ImportError:
try:
import pymysql as MySQLdb
except ImportError:
return False
return True | [
220,
18062
] |
def METHOD_NAME(self):
path, nodes, namespace = "path", {1, 2, 3}, "namespace"
command_context = mock.MagicMock()
parent_context = config_utils.ConfigContext(path, nodes, command_context, namespace,)
child = parent_context.build_child_context("child")
assert_equal(child.path, "%s.child" % path)
assert_equal(child.nodes, nodes)
assert_equal(child.namespace, namespace)
assert_equal(child.command_context, command_context)
assert not child.partial | [
9,
56,
200,
198
] |
def METHOD_NAME(self) -> None:
contains_rx(GOLD_GETTY_FILE, r"Fo.r", r"f[abc]thers", "dedi[cdef]ated")
msg = rf"Missing regex in {GOLD_GETTY_FILE_RX}: r'm\[opq\]thers'"
with pytest.raises(AssertionError, match=msg):
contains_rx(GOLD_GETTY_FILE, r"Fo.r", r"m[opq]thers") | [
9,
1992,
2068
] |
def METHOD_NAME(cmdline=None):
"""Run program"""
parse_messages(cmdline=cmdline) | [
57
] |
def METHOD_NAME() -> Dict[str, Any]:
return load_dataset_with_replacement(
"data/saas/dataset/segment_dataset.yml",
"<instance_fides_key>",
"segment_instance",
)[0] | [
4373,
126
] |
def METHOD_NAME():
parser = argparse.ArgumentParser(description='ActivityNet downloader')
parser.add_argument(
'--bsn',
action='store_true',
help='download for BSN annotation or official one')
args = parser.METHOD_NAME()
return args | [
214,
335
] |
def METHOD_NAME(self):
"""Re-build the data objects. Needed if the models were modified.
Warning: this will delete any information stored in all data objects."""
self.data, self.collision_data, self.visual_data = createDatas(
self.model, self.collision_model, self.visual_model
) | [
2040,
365
] |
def METHOD_NAME(fsm):
"""
Generates a Mermaid text definition for a state diagram
representing the FSM.
Details on Mermaid UML syntax:
https://mermaid.js.org/syntax/stateDiagram.html
:param fsm: the FSM code containing its transition table
:returns: the mermaid.js text definition for FSM diagram
"""
# Regex match to extract transition table from the FSM
transition_table_match = re.search(r"make_transition_table\(([\s\S]*?)\);", fsm)
if not transition_table_match:
return
transition_table = transition_table_match.group(1)
# Remove comment lines
transition_table = re.sub(r"//.*$", "", transition_table, flags=re.MULTILINE)
# Remove all whitespace
transition_table = re.sub(r"\s+", "", transition_table, flags=re.MULTILINE)
diagram = ""
transitions = transition_table.split(",")
for transition in transitions:
# Transitions have the following format:
# src_state + event [guard] / action = dest_state
# Extract dest_state from transition, which is after '=' sign
transition, *rest = transition.split("=")
dest_state = rest[0] if rest else ""
# Extract action from transition, which is after '/' sign
transition, *rest = transition.split("/")
action = rest[0] if rest else ""
# Extract guard contained between square brackets
guard = next(iter(re.findall(r"\[(.*?)\]", transition)), "")
# Extract src_state from transition, which is before '+' sign
src_state = transition.split("+")[0]
def remove_suffix(str, suffix):
return str[: -len(suffix)] if str.endswith(suffix) else str
# Remove suffixes from states, guard, action
src_state = remove_suffix(src_state, "_S")
dest_state = remove_suffix(dest_state, "_S")
guard = remove_suffix(guard, "_G")
action = remove_suffix(action, "_A")
# Terminate state is marked with X in transition table.
# Give terminate state custom styling with the
# :::terminate classDef style
if dest_state == "X":
dest_state = "Terminate:::terminate"
if src_state == "X":
src_state = "Terminate:::terminate"
# Initial state is marked with '*' prefix, so need to add
# special transition from start to initial state in our diagram
if src_state.startswith("*"):
src_state = src_state[1:]
diagram += f"[*] --> {src_state}\n"
# If dest_state is omitted, it is an internal transition
if not dest_state:
dest_state = src_state
diagram += f"{src_state} --> {dest_state}"
if guard:
diagram += f" : [{guard}]"
if action:
diagram += f"\\n<i>{action}</i>"
elif action:
diagram += f" : <i>{action}</i>"
diagram += "\n"
return diagram | [
567,
2056
] |
async def METHOD_NAME(db: Database) -> Dict[str, str]:
records = db.execute_and_fetchall('SELECT product, version FROM latest_product_versions')
return {record['product']: record['version'] async for record in records} | [
1920,
1188,
295,
280,
1267
] |
def METHOD_NAME(request, name, path, resize_to_shape):
img = cv2.imread(path).astype(np.float32) # BGR color format, shape HWC
img = cv2.resize(img, (resize_to_shape[1], resize_to_shape[0]))
target_shape = (img.shape[0], img.shape[1])
img = img.reshape(1,target_shape[0],target_shape[1],3)
request.inputs[name].CopyFrom(make_tensor_proto(img, shape=img.shape)) | [
123,
2029,
362,
623,
6097,
275
] |
def METHOD_NAME(self):
return getattr(self._quantizer, "num_bits", None) | [
181,
2791
] |
def METHOD_NAME():
with mlflow.start_run():
mlflow.log_param("p", "param")
mlflow.log_metric("m", 1.0)
mlflow.set_tag("t", "tag")
mlflow.pyfunc.log_model(
artifact_path="model", python_model=Model(), registered_model_name="model"
) | [
447,
22,
61,
390,
365
] |
def METHOD_NAME(value):
num = value[CONF_NUMBER]
mode = value[CONF_MODE]
is_input = mode[CONF_INPUT]
is_output = mode[CONF_OUTPUT]
is_open_drain = mode[CONF_OPEN_DRAIN]
is_pullup = mode[CONF_PULLUP]
is_pulldown = mode[CONF_PULLDOWN]
is_analog = mode[CONF_ANALOG]
if (not is_analog) and num == 17:
raise cv.Invalid(
"GPIO17 (TOUT) is an analog-only pin on the ESP8266.",
[CONF_MODE],
)
if is_analog and num != 17:
raise cv.Invalid(
"Only GPIO17 is analog-capable on ESP8266.",
[CONF_MODE, CONF_ANALOG],
)
if is_open_drain and not is_output:
raise cv.Invalid(
"Open-drain only works with output mode", [CONF_MODE, CONF_OPEN_DRAIN]
)
if is_pullup and num == 16:
raise cv.Invalid(
"GPIO Pin 16 does not support pullup pin mode. "
"Please choose another pin.",
[CONF_MODE, CONF_PULLUP],
)
if is_pulldown and num != 16:
raise cv.Invalid("Only GPIO16 supports pulldown.", [CONF_MODE, CONF_PULLDOWN])
# (input, output, open_drain, pullup, pulldown)
supported_modes = {
# INPUT
(True, False, False, False, False),
# OUTPUT
(False, True, False, False, False),
# INPUT_PULLUP
(True, False, False, True, False),
# INPUT_PULLDOWN_16
(True, False, False, False, True),
# OUTPUT_OPEN_DRAIN
(False, True, True, False, False),
}
key = (is_input, is_output, is_open_drain, is_pullup, is_pulldown)
if key not in supported_modes:
raise cv.Invalid(
"This pin mode is not supported on ESP8266",
[CONF_MODE],
)
return value | [
187,
1466
] |
def METHOD_NAME(registration_definition_id: Optional[str] = None,
scope: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistrationDefinitionResult:
"""
Gets the registration definition details.
:param str registration_definition_id: The GUID of the registration definition.
:param str scope: The scope of the resource.
"""
__args__ = dict()
__args__['registrationDefinitionId'] = registration_definition_id
__args__['scope'] = scope
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('azure-native:managedservices/v20221001:getRegistrationDefinition', __args__, opts=opts, typ=GetRegistrationDefinitionResult).value
return AwaitableGetRegistrationDefinitionResult(
id=pulumi.get(__ret__, 'id'),
name=pulumi.get(__ret__, 'name'),
plan=pulumi.get(__ret__, 'plan'),
properties=pulumi.get(__ret__, 'properties'),
system_data=pulumi.get(__ret__, 'system_data'),
type=pulumi.get(__ret__, 'type')) | [
19,
2213,
1208
] |
def METHOD_NAME(**kwargs: Any) -> HttpRequest:
# Construct URL
_url = kwargs.pop("template_url", "/http/success/404")
return HttpRequest(method="HEAD", url=_url, **kwargs) | [
56,
12954,
377
] |
def METHOD_NAME(self):
cfg_path = 'kie/sdmgr/sdmgr_unet16_60e_wildreceipt.py'
self.visual_model_cfg = self._get_cfg(cfg_path)
self.visual_model = MODELS.build(self.visual_model_cfg)
cfg_path = 'kie/sdmgr/sdmgr_novisual_60e_wildreceipt.py'
self.novisual_model_cfg = self._get_cfg(cfg_path)
self.novisual_model = MODELS.build(self.novisual_model_cfg)
data_sample = KIEDataSample()
data_sample.gt_instances = InstanceData(
bboxes=torch.FloatTensor([[0, 0, 1, 1], [1, 1, 2, 2]]),
labels=torch.LongTensor([0, 1]),
edge_labels=torch.LongTensor([[0, 1], [1, 0]]),
texts=['text1', 'text2'],
relations=torch.rand((2, 2, 5)))
self.visual_data = dict(
inputs=[torch.rand((3, 10, 10))], data_samples=[data_sample])
self.novisual_data = dict(
inputs=[torch.Tensor([]).reshape((0, 0, 0))],
data_samples=[data_sample]) | [
0,
1
] |
def METHOD_NAME(self):
parameters = {
**self.serialize_header_param(
"Accept", "application/json",
),
}
return parameters | [
572,
386
] |
def METHOD_NAME(c):
"""Quote a single character."""
assert isinstance(c, bytes) and len(c)==1
c = ord(c)
return ESCAPE + bytes((HEX[c//16], HEX[c%16])) | [
3565
] |
def METHOD_NAME(self):
self.autostart()
return self._bandpassed | [
-1
] |
def METHOD_NAME(self):
if WINDOWS:
return
# PTY use adds another utf-8 decode spot which can also fail.
run("echo '\xff'", pty=True, hide="stderr") | [
-1,
321,
1613
] |
def METHOD_NAME(self, pkg, spec, prefix):
super().METHOD_NAME(pkg, spec, prefix)
if "+fortran" in spec:
make("-C", "fortran") | [
56
] |
def METHOD_NAME(self):
"""Houston pdb should have the right matchLabels."""
template = "charts/astronomer/templates/houston/api/houston-deployment.yaml"
labels = render_chart(show_only=[template])[0]["spec"]["template"]["metadata"][
"labels"
]
assert labels["tier"] == "astronomer"
assert labels["component"] == "houston" | [
9,
-1,
58,
10251,
1503
] |
def METHOD_NAME(self, module):
"""
Invoke job_info() with the scan module argument of the wrong type
"""
with pytest.raises(TypeError):
self.as_connection.job_info(self.job_id, module) | [
9,
202,
100,
41,
298,
909,
44
] |
def METHOD_NAME():
fd = FileLoader(EXAMPLES_DIR / 'lambdarank', 'rank')
X_train, y_train, _ = fd.load_dataset('.train', is_sparse=True)
X_test, _, X_test_fn = fd.load_dataset('.test', is_sparse=True)
group_train = fd.load_field('.train.query')
lgb_train = lgb.Dataset(X_train, y_train, group=group_train)
params = dict(fd.params)
params['force_col_wise'] = True
gbm = lgb.LGBMRanker(**params)
gbm.fit(X_train, y_train, group=group_train)
sk_pred = gbm.predict(X_test)
fd.train_predict_check(lgb_train, X_test, X_test_fn, sk_pred)
fd.file_load_check(lgb_train, '.train') | [
9,
-1
] |
async def METHOD_NAME(self):
ready_pattern = self.debug_config.server_ready_pattern
timeout = 60 if ready_pattern else 10
elapsed = 0
delay = 0.5
auto_ready_delay = 0.5
while not self._ready and self.is_running() and elapsed < timeout:
await asyncio.sleep(delay)
if not ready_pattern:
self._ready = self._last_activity < (time.time() - auto_ready_delay)
elapsed += delay | [
618,
1238,
1338
] |
def METHOD_NAME(client, monkeypatch, transaction_data, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
fields = ["Award ID", "Recipient Name", "Mod"]
request = {
"filters": {"keyword": "test", "award_type_codes": ["A", "B", "C", "D"]},
"fields": fields,
"page": 1,
"limit": 5,
"sort": "Award ID",
"order": "desc",
}
resp = client.post(ENDPOINT, content_type="application/json", data=json.dumps(request))
assert resp.status_code == status.HTTP_200_OK
assert len(resp.data["results"]) > 0
for result in resp.data["results"]:
for field in fields:
assert field in result, f"Response item is missing field {field}"
assert "internal_id" in result
assert "generated_internal_id" in result
assert "Last Date to Order" not in result | [
9,
593,
47,
342,
2475
] |
def METHOD_NAME(h, s, v):
"""Converts HSV to RGB.
Based on the Foley and Van Dam HSV algorithm used
by James Westervelt's (CERL) hsv.rgb.sh script from GRASS 4/5."""
# Hue: 0-360 degrees
# Saturation: 0.0-1.0
# Value: 0.0-1.0
if v == 0.0:
return (0, 0, 0)
if v == 1.0:
return (255, 255, 255)
if h >= 360:
h -= 360
h = h / 60.0
i = int(h)
f = h - i
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
# init/fallback
R = G = B = 0
# red
if i == 0:
R = v
if i == 1:
R = q
if i == 2:
R = p
if i == 3:
R = p
if i == 4:
R = t
if i == 5:
R = v
# green
if i == 0:
G = t
if i == 1:
G = v
if i == 2:
G = v
if i == 3:
G = q
if i == 4:
G = p
if i == 5:
G = p
# blue
if i == 0:
B = p
if i == 1:
B = p
if i == 2:
B = t
if i == 3:
B = v
if i == 4:
B = v
if i == 5:
B = q
return (R * 255, G * 255, B * 255) | [
7349,
14099,
2310
] |
def METHOD_NAME(self, line):
if line.startswith('Arena'):
self._header['ARId'] = line.strip(',')
return 0
elif line.startswith('Results from time'):
self._period = [True, line.strip(',')]
return 0
elif line.startswith('Sample Id'):
if self._period[0]: # If there is a period, we should save it
self._period[0] = False
self._header[self._period[1]] = self._period[2:]
self._end_header = True
self._columns = line.split(',')
elif self._period[0]: # Is a date
date = self.csvDate2BikaDate(line.strip(','))
self._period.append(date)
return 0
else:
self.err('Unexpected header format', numline=self._numline)
return -1 | [
214,
-1
] |
def METHOD_NAME(self, pa_table: pa.Table) -> "torch.Tensor":
column = self.numpy_arrow_extractor().extract_column(pa_table)
column = self.python_features_decoder.decode_column(column, pa_table.column_names[0])
column = self.recursive_tensorize(column)
column = self._consolidate(column)
return column | [
275,
105
] |
def METHOD_NAME(self) -> str:
return self.value.METHOD_NAME | [
16427,
44
] |
def METHOD_NAME(self):
super().METHOD_NAME()
# Make sure all the models created in keras has been deleted and cleared
# from the global keras grpah, also do a force GC to recycle the GPU
# memory.
tf.keras.backend.clear_session()
gc.collect() | [
531,
481
] |
def METHOD_NAME(self):
process.system("ppc64_cpu --smt=on")
for i in ["off", "on", 4, 2]:
for j in [2, 4, "on", "off"]:
process.system("ppc64_cpu --smt=%s" % j)
smt_initial = process.system_output(
"ppc64_cpu --smt", shell=True)
if process.system("smtstate --save", ignore_status=True):
self.fail("smtstate save failed")
process.system("ppc64_cpu --smt=%s" % i)
self.log.info("SMT level before load = %s" %
process.system_output("ppc64_cpu --smt"))
if process.system("smtstate --load", ignore_status=True):
self.fail("smtstate load failed")
smt_final = process.system_output(
"ppc64_cpu --smt", shell=True)
self.log.info("SMT level after load = %s" %
process.system_output("ppc64_cpu --smt"))
if smt_initial == smt_final:
self.log.info("SMT load is successful for SMT=%s" % j)
else:
self.fail("smt load failed") | [
9
] |
def METHOD_NAME(pipeline_response):
deserialized = self._deserialize("ResourceSkuCollection", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem) | [
297,
365
] |
def METHOD_NAME(self, value):
return value < self.value | [
1171,
4245
] |
def METHOD_NAME(self):
"""
Refresh main widget.
"""
self.get_widget().METHOD_NAME() | [
1920
] |
def METHOD_NAME(self):
output_blob_name = next(iter(self.outputs))
output_size = self.outputs[output_blob_name].shape
if len(output_size) != 3:
self.raise_error("Unexpected output blob shape {}. Only 3D output blob is supported".format(output_size))
return output_blob_name | [
19,
141
] |
def METHOD_NAME(n=10, L=12):
box = [0, L, 0, L]
qmesh = StructureQuadMesh(box, n, n)
node = qmesh.node
cell = qmesh.ds.cell
quadtree = Quadtree(node, cell)
return quadtree | [
5161
] |
def METHOD_NAME(self, METHOD_NAME):
return os.METHOD_NAME.join(self.tmp, METHOD_NAME) | [
157
] |
def METHOD_NAME(subType, ver, data):
# ***** Node Comm SECURE UDT VERSION 1 Memory Layout *****
# 4 bytes : Target HUID
# 8 bytes : Length of In/Out Buffer
# 8 bytes : Access Type (DeviceFW::AccessType)
# 1 byte : Op Type (DeviceFW::OperationType)
# 1 byte : Mode (XBUS or ABUS)
# 1 byte : LinkId
# 1 byte : MboxId
d = dict()
subd = dict()
i = 0
subd['Target HUID 0x'], i=memConcat(data, i, i+4)
subd['Length I/O Buff 0x'], i=memConcat(data, i, i+8)
subd['Access Type 0x'], i=memConcat(data, i, i+8)
d['Secure Node Comm Info'] = subd
subd2 = dict()
op = data[i]
i += 1
subd2['Op Type Value 0x']=f'{op:02x}'
# Keep this check in sync with DeviceFW::OperationType values
# in src/include/usr/devicefw/driverif.H
if op == 0:
d['Node Comm Read']=subd2
elif op == 1:
d['Node Comm Write']=subd2
else:
d['Unknown Node Comm Operation']=subd2
subd3 = dict()
op2 = data[i]
i += 1
subd3['MODE 0x']=f'{op2:02x}'
subd3['LinkId 0x'], i=memConcat(data, i, i+1)
subd3['MboxID 0x'], i=memConcat(data, i, i+1)
if op2 == 0:
d['Node Comm Mode: XBUS']=subd3
elif op2 == 1:
d['Node Comm Mode: ABUS']=subd3
else:
d['INVALID Node Comm Mode']=subd3
jsonStr = json.dumps(d, indent=2)
return jsonStr | [
8400,
1319,
1716,
11060,
100
] |
def METHOD_NAME(self, y_true, y_pred, mask_privileged_group):
return 0.5 * (self._compute_base_metric(y_true[mask_privileged_group], y_pred[mask_privileged_group]) +
self._compute_base_metric(y_true[~mask_privileged_group], y_pred[~mask_privileged_group])) | [
226,
9705,
1341
] |
def METHOD_NAME(precision) -> int:
trainer = get_trainer(precision)
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
trainer.eval()
return torch.cuda.max_memory_allocated() | [
1171,
61,
599,
1645
] |
def METHOD_NAME():
"""Prepare setup specific environment"""
grid_data = [
{
"left_edge": [0.0, 0.0, 0.0],
"right_edge": [1.0, 1.0, 1.0],
"level": 0,
"dimensions": [16, 16, 16],
},
{
"left_edge": [0.25, 0.25, 0.25],
"right_edge": [0.75, 0.75, 0.75],
"level": 1,
"dimensions": [16, 16, 16],
},
{
"left_edge": [0.25, 0.25, 0.375],
"right_edge": [0.5, 0.5, 0.625],
"level": 2,
"dimensions": [16, 16, 16],
},
{
"left_edge": [0.5, 0.5, 0.375],
"right_edge": [0.75, 0.75, 0.625],
"level": 2,
"dimensions": [16, 16, 16],
},
{
"left_edge": [0.3125, 0.3125, 0.4375],
"right_edge": [0.4375, 0.4375, 0.5625],
"level": 3,
"dimensions": [16, 16, 16],
},
{
"left_edge": [0.5625, 0.5625, 0.4375],
"right_edge": [0.6875, 0.6875, 0.5625],
"level": 3,
"dimensions": [16, 16, 16],
},
]
for grid in grid_data:
grid["density"] = (
np.random.random(grid["dimensions"]) * 2 ** grid["level"],
"g/cm**3",
)
return load_amr_grids(grid_data, [16, 16, 16]) | [
102,
9,
2491
] |
def METHOD_NAME(self, assign_result: AssignResult, pred_instances: InstanceData,
gt_instances: InstanceData,
**kwargs) -> MultiInstanceSamplingResult:
"""Sample positive and negative bboxes.
Args:
assign_result (:obj:`AssignResult`): Assigning results from
MultiInstanceAssigner.
pred_instances (:obj:`InstanceData`): Instances of model
predictions. It includes ``priors``, and the priors can
be anchors or points, or the bboxes predicted by the
previous stage, has shape (n, 4). The bboxes predicted by
the current model or stage will be named ``bboxes``,
``labels``, and ``scores``, the same as the ``InstanceData``
in other places.
gt_instances (:obj:`InstanceData`): Ground truth of instance
annotations. It usually includes ``bboxes``, with shape (k, 4),
and ``labels``, with shape (k, ).
Returns:
:obj:`MultiInstanceSamplingResult`: Sampling result.
"""
assert 'batch_gt_instances_ignore' in kwargs, \
'batch_gt_instances_ignore is necessary for MultiInsRandomSampler'
gt_bboxes = gt_instances.bboxes
ignore_bboxes = kwargs['batch_gt_instances_ignore'].bboxes
gt_and_ignore_bboxes = torch.cat([gt_bboxes, ignore_bboxes], dim=0)
priors = pred_instances.priors
if len(priors.shape) < 2:
priors = priors[None, :]
priors = priors[:, :4]
gt_flags = priors.new_zeros((priors.shape[0], ), dtype=torch.uint8)
priors = torch.cat([priors, gt_and_ignore_bboxes], dim=0)
gt_ones = priors.new_ones(
gt_and_ignore_bboxes.shape[0], dtype=torch.uint8)
gt_flags = torch.cat([gt_flags, gt_ones])
num_expected_pos = int(self.num * self.pos_fraction)
pos_inds = self.pos_sampler._sample_pos(assign_result,
num_expected_pos)
# We found that sampled indices have duplicated items occasionally.
# (may be a bug of PyTorch)
pos_inds = pos_inds.unique()
num_sampled_pos = pos_inds.numel()
num_expected_neg = self.num - num_sampled_pos
if self.neg_pos_ub >= 0:
_pos = max(1, num_sampled_pos)
neg_upper_bound = int(self.neg_pos_ub * _pos)
if num_expected_neg > neg_upper_bound:
num_expected_neg = neg_upper_bound
neg_inds = self.neg_sampler._sample_neg(assign_result,
num_expected_neg)
neg_inds = neg_inds.unique()
sampling_result = MultiInstanceSamplingResult(
pos_inds=pos_inds,
neg_inds=neg_inds,
priors=priors,
gt_and_ignore_bboxes=gt_and_ignore_bboxes,
assign_result=assign_result,
gt_flags=gt_flags)
return sampling_result | [
734
] |
def METHOD_NAME(MockAppController, ieee_mock):
"""Zigpy device mock."""
def _dev(ieee=None, nwk=zigpy.types.NWK(0x1234)):
if ieee is None:
ieee = ieee_mock
device = MockAppController.add_device(ieee, nwk)
return device
return _dev | [
11298,
398,
248
] |
def METHOD_NAME(self, g_mouse_reading: SpaceNavigator) -> bool:
"""Checks if user has pressed right mouse button.
Returns True only if button was previously not pressed and is now.
:param g_mouse_reading: mouse input
:return: if button was pressed return True, else False
"""
if g_mouse_reading.buttons[1] == 1:
if self.rb_pressed:
return False
else:
self.rb_pressed = True
return True
else:
self.rb_pressed = False
return False | [
2571,
1974,
2786,
1975
] |
def METHOD_NAME(self, tth, I):
"""
Reconstruct a perfect image according to 2th / I given in
input
:param tth: 2 theta array
:type tth: ndarray
:param I: intensity array
:type I: ndarray
:return: a reconstructed image
:rtype: ndarray
"""
return numpy.interp(self.ai.twoThetaArray(self.shape), tth, I) | [
5122
] |
def METHOD_NAME(counts):
if args.sort == "all":
return (counts[1].rbytes + counts[1].wbytes + counts[1].reads + counts[1].writes)
else:
return getattr(counts[1], args.sort) | [
266,
667
] |
def METHOD_NAME(head): return \ | [
4556,
1010,
4742,
227,
1796
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.