nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tegaki/tegaki | eceec69fe651d0733c8c8752dae569d2283d0f3c | tegaki-python/tegaki/charcol.py | python | CharacterCollection.__init__ | (self, path=":memory:") | Construct a collection.
@type path: str
@param path: an XML file or a DB file (see also L{bind}) | Construct a collection. | [
"Construct",
"a",
"collection",
"."
] | def __init__(self, path=":memory:"):
"""
Construct a collection.
@type path: str
@param path: an XML file or a DB file (see also L{bind})
"""
if path is None:
path = ":memory:"
if not path in ("", ":memory:") and not path.endswith(".chardb"):
# this should be an XML character collection
gzip, bz2 = _gzipbz2(path)
self.bind(":memory:")
self.read(path, gzip=gzip, bz2=bz2)
self._path = path # contains the path to the xml file
else:
# this should be either a .chardb, ":memory:" or ""
self.bind(path)
self._path = None | [
"def",
"__init__",
"(",
"self",
",",
"path",
"=",
"\":memory:\"",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"\":memory:\"",
"if",
"not",
"path",
"in",
"(",
"\"\"",
",",
"\":memory:\"",
")",
"and",
"not",
"path",
".",
"endswith",
"(",
"\... | https://github.com/tegaki/tegaki/blob/eceec69fe651d0733c8c8752dae569d2283d0f3c/tegaki-python/tegaki/charcol.py#L330-L353 | ||
CJWorkbench/cjworkbench | e0b878d8ff819817fa049a4126efcbfcec0b50e6 | renderer/execute/step.py | python | execute_step | (
*,
chroot_context: ChrootContext,
workflow: Workflow,
step: Step,
module_zipfile: Optional[ModuleZipfile],
params: Dict[str, Any],
tab_name: str,
input_path: Path,
input_table_columns: List[Column],
tab_results: Dict[Tab, Optional[StepResult]],
output_path: Path,
) | return StepResult(
path=loaded_render_result.path, columns=loaded_render_result.columns
) | Render a single Step; cache, broadcast and return output.
CONCURRENCY NOTES: This function is reasonably concurrency-friendly:
* It returns a valid cache result immediately.
* It checks with the database that `step` hasn't been deleted from
its workflow.
* It checks with the database that `step` hasn't been deleted from
the database entirely.
* It checks with the database that `step` hasn't been modified. (It
is very common for a user to request a module's output -- kicking off a
sequence of `execute_step` -- and then change a param in a prior
module, making all those calls obsolete.
* It locks the workflow while collecting `render()` input data.
* When writing results to the database, it avoids writing if the module has
changed.
These guarantees mean:
* TODO It's relatively cheap to render twice.
* Users who modify a Step while it's rendering will be stalled -- for
as short a duration as possible.
* When a user changes a workflow significantly, all prior renders will end
relatively cheaply.
Raises `UnneededExecution` when the input Step should not be rendered. | Render a single Step; cache, broadcast and return output. | [
"Render",
"a",
"single",
"Step",
";",
"cache",
"broadcast",
"and",
"return",
"output",
"."
] | async def execute_step(
*,
chroot_context: ChrootContext,
workflow: Workflow,
step: Step,
module_zipfile: Optional[ModuleZipfile],
params: Dict[str, Any],
tab_name: str,
input_path: Path,
input_table_columns: List[Column],
tab_results: Dict[Tab, Optional[StepResult]],
output_path: Path,
) -> StepResult:
"""Render a single Step; cache, broadcast and return output.
CONCURRENCY NOTES: This function is reasonably concurrency-friendly:
* It returns a valid cache result immediately.
* It checks with the database that `step` hasn't been deleted from
its workflow.
* It checks with the database that `step` hasn't been deleted from
the database entirely.
* It checks with the database that `step` hasn't been modified. (It
is very common for a user to request a module's output -- kicking off a
sequence of `execute_step` -- and then change a param in a prior
module, making all those calls obsolete.
* It locks the workflow while collecting `render()` input data.
* When writing results to the database, it avoids writing if the module has
changed.
These guarantees mean:
* TODO It's relatively cheap to render twice.
* Users who modify a Step while it's rendering will be stalled -- for
as short a duration as possible.
* When a user changes a workflow significantly, all prior renders will end
relatively cheaply.
Raises `UnneededExecution` when the input Step should not be rendered.
"""
# may raise UnneededExecution
loaded_render_result = await _render_step(
chroot_context=chroot_context,
workflow=workflow,
step=step,
module_zipfile=module_zipfile,
raw_params=params,
tab_name=tab_name,
input_path=input_path,
input_table_columns=input_table_columns,
tab_results=tab_results,
output_path=output_path,
)
# may raise UnneededExecution
crr, output_delta = await _execute_step_save(workflow, step, loaded_render_result)
update = clientside.Update(
steps={
step.id: clientside.StepUpdate(
render_result=crr, module_slug=step.module_id_name
)
}
)
await rabbitmq.send_update_to_workflow_clients(workflow.id, update)
# Email notification if data has changed. Do this outside of the database
# lock, because SMTP can be slow, and Django's email backend is
# synchronous.
if output_delta and workflow.owner_id is not None:
loop = asyncio.get_event_loop()
await loop.run_in_executor(
None,
notifications.email_output_delta,
output_delta,
datetime.datetime.now(),
)
# TODO if there's no change, is it possible for us to skip the render
# of future modules, setting their cached_render_result_delta_id =
# last_relevant_delta_id? Investigate whether this is worthwhile.
return StepResult(
path=loaded_render_result.path, columns=loaded_render_result.columns
) | [
"async",
"def",
"execute_step",
"(",
"*",
",",
"chroot_context",
":",
"ChrootContext",
",",
"workflow",
":",
"Workflow",
",",
"step",
":",
"Step",
",",
"module_zipfile",
":",
"Optional",
"[",
"ModuleZipfile",
"]",
",",
"params",
":",
"Dict",
"[",
"str",
",... | https://github.com/CJWorkbench/cjworkbench/blob/e0b878d8ff819817fa049a4126efcbfcec0b50e6/renderer/execute/step.py#L510-L593 | |
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | reviewboard/reviews/search_indexes.py | python | ReviewRequestIndex.prepare_private | (self, review_request) | return not review_request.is_accessible_by(AnonymousUser(),
silent=True) | Prepare the private flag for the index.
This will be set to true if the review request isn't generally
accessible to users. | Prepare the private flag for the index. | [
"Prepare",
"the",
"private",
"flag",
"for",
"the",
"index",
"."
] | def prepare_private(self, review_request):
"""Prepare the private flag for the index.
This will be set to true if the review request isn't generally
accessible to users.
"""
return not review_request.is_accessible_by(AnonymousUser(),
silent=True) | [
"def",
"prepare_private",
"(",
"self",
",",
"review_request",
")",
":",
"return",
"not",
"review_request",
".",
"is_accessible_by",
"(",
"AnonymousUser",
"(",
")",
",",
"silent",
"=",
"True",
")"
] | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/reviews/search_indexes.py#L69-L76 | |
PyThaiNLP/pythainlp | de38b8507bf0934540aa5094e5f7f57d7f67e2dc | pythainlp/translate/en_th.py | python | EnThTranslator.translate | (self, text: str) | return translated.replace(" ", "").replace("▁", " ").strip() | Translate text from English to Thai
:param str text: input text in source language
:return: translated text in target language
:rtype: str
:Example:
Translate text from English to Thai::
from pythainlp.translate import EnThTranslator
enth = EnThTranslator()
enth.translate("I love cat.")
# output: ฉันรักแมว | Translate text from English to Thai | [
"Translate",
"text",
"from",
"English",
"to",
"Thai"
] | def translate(self, text: str) -> str:
"""
Translate text from English to Thai
:param str text: input text in source language
:return: translated text in target language
:rtype: str
:Example:
Translate text from English to Thai::
from pythainlp.translate import EnThTranslator
enth = EnThTranslator()
enth.translate("I love cat.")
# output: ฉันรักแมว
"""
tokens = " ".join(self._tokenizer.tokenize(text))
translated = self._model.translate(tokens)
return translated.replace(" ", "").replace("▁", " ").strip() | [
"def",
"translate",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"str",
":",
"tokens",
"=",
"\" \"",
".",
"join",
"(",
"self",
".",
"_tokenizer",
".",
"tokenize",
"(",
"text",
")",
")",
"translated",
"=",
"self",
".",
"_model",
".",
"translate",
... | https://github.com/PyThaiNLP/pythainlp/blob/de38b8507bf0934540aa5094e5f7f57d7f67e2dc/pythainlp/translate/en_th.py#L81-L103 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Environment.__getitem__ | (self, project_name) | return self._distmap.get(distribution_key, []) | Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project's distributions use their project's name converted to all
lowercase as their key. | Return a newest-to-oldest list of distributions for `project_name` | [
"Return",
"a",
"newest",
"-",
"to",
"-",
"oldest",
"list",
"of",
"distributions",
"for",
"project_name"
] | def __getitem__(self, project_name):
"""Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project's distributions use their project's name converted to all
lowercase as their key.
"""
distribution_key = project_name.lower()
return self._distmap.get(distribution_key, []) | [
"def",
"__getitem__",
"(",
"self",
",",
"project_name",
")",
":",
"distribution_key",
"=",
"project_name",
".",
"lower",
"(",
")",
"return",
"self",
".",
"_distmap",
".",
"get",
"(",
"distribution_key",
",",
"[",
"]",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/pkg_resources/__init__.py#L1083-L1092 | |
spack/spack | 675210bd8bd1c5d32ad1cc83d898fb43b569ed74 | lib/spack/llnl/util/filesystem.py | python | install | (src, dest) | Install the file(s) *src* to the file or directory *dest*.
Same as :py:func:`copy` with the addition of setting proper
permissions on the installed file.
Parameters:
src (str): the file(s) to install
dest (str): the destination file or directory
Raises:
IOError: if *src* does not match any files or directories
ValueError: if *src* matches multiple files but *dest* is
not a directory | Install the file(s) *src* to the file or directory *dest*. | [
"Install",
"the",
"file",
"(",
"s",
")",
"*",
"src",
"*",
"to",
"the",
"file",
"or",
"directory",
"*",
"dest",
"*",
"."
] | def install(src, dest):
"""Install the file(s) *src* to the file or directory *dest*.
Same as :py:func:`copy` with the addition of setting proper
permissions on the installed file.
Parameters:
src (str): the file(s) to install
dest (str): the destination file or directory
Raises:
IOError: if *src* does not match any files or directories
ValueError: if *src* matches multiple files but *dest* is
not a directory
"""
copy(src, dest, _permissions=True) | [
"def",
"install",
"(",
"src",
",",
"dest",
")",
":",
"copy",
"(",
"src",
",",
"dest",
",",
"_permissions",
"=",
"True",
")"
] | https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/llnl/util/filesystem.py#L395-L410 | ||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | rpython/rtyper/lltypesystem/lltype.py | python | identityhash | (p) | return p._identityhash() | Returns the lltype-level hash of the given GcStruct.
Not for NULL. See rlib.objectmodel.compute_identity_hash() for more
information about the RPython-level meaning of this. | Returns the lltype-level hash of the given GcStruct.
Not for NULL. See rlib.objectmodel.compute_identity_hash() for more
information about the RPython-level meaning of this. | [
"Returns",
"the",
"lltype",
"-",
"level",
"hash",
"of",
"the",
"given",
"GcStruct",
".",
"Not",
"for",
"NULL",
".",
"See",
"rlib",
".",
"objectmodel",
".",
"compute_identity_hash",
"()",
"for",
"more",
"information",
"about",
"the",
"RPython",
"-",
"level",
... | def identityhash(p):
"""Returns the lltype-level hash of the given GcStruct.
Not for NULL. See rlib.objectmodel.compute_identity_hash() for more
information about the RPython-level meaning of this.
"""
assert p
return p._identityhash() | [
"def",
"identityhash",
"(",
"p",
")",
":",
"assert",
"p",
"return",
"p",
".",
"_identityhash",
"(",
")"
] | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/rpython/rtyper/lltypesystem/lltype.py#L2422-L2428 | |
deepmind/bsuite | f305972cf05042f6ce23d638477ea9b33918ba17 | bsuite/experiments/mountain_car_scale/mountain_car_scale.py | python | load | (reward_scale: float, seed: int) | return env | Load a mountain_car experiment with the prescribed settings. | Load a mountain_car experiment with the prescribed settings. | [
"Load",
"a",
"mountain_car",
"experiment",
"with",
"the",
"prescribed",
"settings",
"."
] | def load(reward_scale: float, seed: int):
"""Load a mountain_car experiment with the prescribed settings."""
env = wrappers.RewardScale(
env=mountain_car.MountainCar(seed=seed),
reward_scale=reward_scale,
seed=seed)
env.bsuite_num_episodes = sweep.NUM_EPISODES
return env | [
"def",
"load",
"(",
"reward_scale",
":",
"float",
",",
"seed",
":",
"int",
")",
":",
"env",
"=",
"wrappers",
".",
"RewardScale",
"(",
"env",
"=",
"mountain_car",
".",
"MountainCar",
"(",
"seed",
"=",
"seed",
")",
",",
"reward_scale",
"=",
"reward_scale",... | https://github.com/deepmind/bsuite/blob/f305972cf05042f6ce23d638477ea9b33918ba17/bsuite/experiments/mountain_car_scale/mountain_car_scale.py#L24-L31 | |
openembedded/bitbake | 98407efc8c670abd71d3fa88ec3776ee9b5c38f3 | lib/bb/parse/parse_py/BBHandler.py | python | supports | (fn, d) | return os.path.splitext(fn)[-1] in [".bb", ".bbclass", ".inc"] | Return True if fn has a supported extension | Return True if fn has a supported extension | [
"Return",
"True",
"if",
"fn",
"has",
"a",
"supported",
"extension"
] | def supports(fn, d):
"""Return True if fn has a supported extension"""
return os.path.splitext(fn)[-1] in [".bb", ".bbclass", ".inc"] | [
"def",
"supports",
"(",
"fn",
",",
"d",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"fn",
")",
"[",
"-",
"1",
"]",
"in",
"[",
"\".bb\"",
",",
"\".bbclass\"",
",",
"\".inc\"",
"]"
] | https://github.com/openembedded/bitbake/blob/98407efc8c670abd71d3fa88ec3776ee9b5c38f3/lib/bb/parse/parse_py/BBHandler.py#L39-L41 | |
daoluan/decode-Django | d46a858b45b56de48b0355f50dd9e45402d04cfd | Django-1.5.1/django/contrib/localflavor/mx/forms.py | python | MXRFCField._has_homoclave | (self, rfc) | return not rfc_without_homoclave_re.match(rfc) | This check is done due to the existance of RFCs without a *homoclave*
since the current algorithm to calculate it had not been created for
the first RFCs ever in Mexico. | This check is done due to the existance of RFCs without a *homoclave*
since the current algorithm to calculate it had not been created for
the first RFCs ever in Mexico. | [
"This",
"check",
"is",
"done",
"due",
"to",
"the",
"existance",
"of",
"RFCs",
"without",
"a",
"*",
"homoclave",
"*",
"since",
"the",
"current",
"algorithm",
"to",
"calculate",
"it",
"had",
"not",
"been",
"created",
"for",
"the",
"first",
"RFCs",
"ever",
... | def _has_homoclave(self, rfc):
"""
This check is done due to the existance of RFCs without a *homoclave*
since the current algorithm to calculate it had not been created for
the first RFCs ever in Mexico.
"""
rfc_without_homoclave_re = re.compile(r'^[A-Z&Ññ]{3,4}%s$' % DATE_RE,
re.IGNORECASE)
return not rfc_without_homoclave_re.match(rfc) | [
"def",
"_has_homoclave",
"(",
"self",
",",
"rfc",
")",
":",
"rfc_without_homoclave_re",
"=",
"re",
".",
"compile",
"(",
"r'^[A-Z&Ññ]{3,4}%s$' %",
"D",
"TE_RE,",
"",
"re",
".",
"IGNORECASE",
")",
"return",
"not",
"rfc_without_homoclave_re",
".",
"match",
"(",
"... | https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/contrib/localflavor/mx/forms.py#L132-L140 | |
VirtueSecurity/aws-extender | d123b7e1a845847709ba3a481f11996bddc68a1c | BappModules/boto3/dynamodb/conditions.py | python | AttributeBase.gt | (self, value) | return GreaterThan(self, value) | Creates a condition where the attribute is greater than the value.
:param value: The value that the attribute is greater than. | Creates a condition where the attribute is greater than the value. | [
"Creates",
"a",
"condition",
"where",
"the",
"attribute",
"is",
"greater",
"than",
"the",
"value",
"."
] | def gt(self, value):
"""Creates a condition where the attribute is greater than the value.
:param value: The value that the attribute is greater than.
"""
return GreaterThan(self, value) | [
"def",
"gt",
"(",
"self",
",",
"value",
")",
":",
"return",
"GreaterThan",
"(",
"self",
",",
"value",
")"
] | https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto3/dynamodb/conditions.py#L96-L101 | |
feisuzhu/thbattle | ac0dee1b2d86de7664289cf432b157ef25427ba1 | src/pyglet/gl/win32.py | python | Win32Config._get_arb_pixel_format_matching_configs | (self, canvas) | return formats | Get configs using the WGL_ARB_pixel_format extension.
This method assumes a (dummy) GL context is already created. | Get configs using the WGL_ARB_pixel_format extension.
This method assumes a (dummy) GL context is already created. | [
"Get",
"configs",
"using",
"the",
"WGL_ARB_pixel_format",
"extension",
".",
"This",
"method",
"assumes",
"a",
"(",
"dummy",
")",
"GL",
"context",
"is",
"already",
"created",
"."
] | def _get_arb_pixel_format_matching_configs(self, canvas):
'''Get configs using the WGL_ARB_pixel_format extension.
This method assumes a (dummy) GL context is already created.'''
# Check for required extensions
if self.sample_buffers or self.samples:
if not gl_info.have_extension('GL_ARB_multisample'):
return []
# Construct array of attributes
attrs = []
for name, value in self.get_gl_attributes():
attr = Win32CanvasConfigARB.attribute_ids.get(name, None)
if attr and value is not None:
attrs.extend([attr, int(value)])
attrs.append(0)
attrs = (c_int * len(attrs))(*attrs)
pformats = (c_int * 16)()
nformats = c_uint(16)
wglext_arb.wglChoosePixelFormatARB(canvas.hdc, attrs, None,
nformats, pformats, nformats)
formats = [Win32CanvasConfigARB(canvas, pf, self) \
for pf in pformats[:nformats.value]]
return formats | [
"def",
"_get_arb_pixel_format_matching_configs",
"(",
"self",
",",
"canvas",
")",
":",
"# Check for required extensions ",
"if",
"self",
".",
"sample_buffers",
"or",
"self",
".",
"samples",
":",
"if",
"not",
"gl_info",
".",
"have_extension",
"(",
"'GL_ARB_multi... | https://github.com/feisuzhu/thbattle/blob/ac0dee1b2d86de7664289cf432b157ef25427ba1/src/pyglet/gl/win32.py#L77-L102 | |
openworm/owmeta | 4d546107c12ecb12f3d946db7a44b93b80877132 | owmeta/bibtex.py | python | parse_bibtex_into_documents | (file_name, context=None) | return res | Parses BibTeX records into a dictionary of `.Document` instances
Parameters
----------
bibtex_file : :term:`file object`
File containing one or more BibTeX records
Returns
-------
dict
`.Document` instances from the records in the file | Parses BibTeX records into a dictionary of `.Document` instances | [
"Parses",
"BibTeX",
"records",
"into",
"a",
"dictionary",
"of",
".",
"Document",
"instances"
] | def parse_bibtex_into_documents(file_name, context=None):
'''
Parses BibTeX records into a dictionary of `.Document` instances
Parameters
----------
bibtex_file : :term:`file object`
File containing one or more BibTeX records
Returns
-------
dict
`.Document` instances from the records in the file
'''
res = dict()
bib_database = load_from_file_named(file_name)
for entry in bib_database.entries:
entry_id = entry['ID']
res[entry_id] = bibtex_to_document(entry, context)
return res | [
"def",
"parse_bibtex_into_documents",
"(",
"file_name",
",",
"context",
"=",
"None",
")",
":",
"res",
"=",
"dict",
"(",
")",
"bib_database",
"=",
"load_from_file_named",
"(",
"file_name",
")",
"for",
"entry",
"in",
"bib_database",
".",
"entries",
":",
"entry_i... | https://github.com/openworm/owmeta/blob/4d546107c12ecb12f3d946db7a44b93b80877132/owmeta/bibtex.py#L96-L116 | |
networkx/networkx | 1620568e36702b1cfeaf1c0277b167b6cb93e48d | networkx/classes/multigraph.py | python | MultiGraph.number_of_edges | (self, u=None, v=None) | return len(edgedata) | Returns the number of edges between two nodes.
Parameters
----------
u, v : nodes, optional (Gefault=all edges)
If u and v are specified, return the number of edges between
u and v. Otherwise return the total number of all edges.
Returns
-------
nedges : int
The number of edges in the graph. If nodes `u` and `v` are
specified return the number of edges between those nodes. If
the graph is directed, this only returns the number of edges
from `u` to `v`.
See Also
--------
size
Examples
--------
For undirected multigraphs, this method counts the total number
of edges in the graph::
>>> G = nx.MultiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges
joining the two nodes::
>>> G.number_of_edges(0, 1)
2
For directed multigraphs, this method can count the total number
of directed edges from `u` to `v`::
>>> G = nx.MultiDiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1 | Returns the number of edges between two nodes. | [
"Returns",
"the",
"number",
"of",
"edges",
"between",
"two",
"nodes",
"."
] | def number_of_edges(self, u=None, v=None):
"""Returns the number of edges between two nodes.
Parameters
----------
u, v : nodes, optional (Gefault=all edges)
If u and v are specified, return the number of edges between
u and v. Otherwise return the total number of all edges.
Returns
-------
nedges : int
The number of edges in the graph. If nodes `u` and `v` are
specified return the number of edges between those nodes. If
the graph is directed, this only returns the number of edges
from `u` to `v`.
See Also
--------
size
Examples
--------
For undirected multigraphs, this method counts the total number
of edges in the graph::
>>> G = nx.MultiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges
joining the two nodes::
>>> G.number_of_edges(0, 1)
2
For directed multigraphs, this method can count the total number
of directed edges from `u` to `v`::
>>> G = nx.MultiDiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1
"""
if u is None:
return self.size()
try:
edgedata = self._adj[u][v]
except KeyError:
return 0 # no such edge
return len(edgedata) | [
"def",
"number_of_edges",
"(",
"self",
",",
"u",
"=",
"None",
",",
"v",
"=",
"None",
")",
":",
"if",
"u",
"is",
"None",
":",
"return",
"self",
".",
"size",
"(",
")",
"try",
":",
"edgedata",
"=",
"self",
".",
"_adj",
"[",
"u",
"]",
"[",
"v",
"... | https://github.com/networkx/networkx/blob/1620568e36702b1cfeaf1c0277b167b6cb93e48d/networkx/classes/multigraph.py#L1123-L1179 | |
nipy/nipype | cd4c34d935a43812d1756482fdc4034844e485b8 | nipype/interfaces/fsl/base.py | python | FSLCommand.set_default_output_type | (cls, output_type) | Set the default output type for FSL classes.
This method is used to set the default output type for all fSL
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.output_type. | Set the default output type for FSL classes. | [
"Set",
"the",
"default",
"output",
"type",
"for",
"FSL",
"classes",
"."
] | def set_default_output_type(cls, output_type):
"""Set the default output type for FSL classes.
This method is used to set the default output type for all fSL
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.output_type.
"""
if output_type in Info.ftypes:
cls._output_type = output_type
else:
raise AttributeError("Invalid FSL output_type: %s" % output_type) | [
"def",
"set_default_output_type",
"(",
"cls",
",",
"output_type",
")",
":",
"if",
"output_type",
"in",
"Info",
".",
"ftypes",
":",
"cls",
".",
"_output_type",
"=",
"output_type",
"else",
":",
"raise",
"AttributeError",
"(",
"\"Invalid FSL output_type: %s\"",
"%",
... | https://github.com/nipy/nipype/blob/cd4c34d935a43812d1756482fdc4034844e485b8/nipype/interfaces/fsl/base.py#L188-L200 | ||
JasonKessler/scattertext | ef33f06d4c31f9d64b551a7ab86bf157aca82644 | scattertext/semioticsquare/SemioticSquare.py | python | SemioticSquare.__init__ | (self,
term_doc_matrix,
category_a,
category_b,
neutral_categories,
labels=None,
term_ranker=AbsoluteFrequencyRanker,
scorer=None) | Parameters
----------
term_doc_matrix : TermDocMatrix
TermDocMatrix (or descendant) which will be used in constructing square.
category_a : str
Category name for term A
category_b : str
Category name for term B (in opposition to A)
neutral_categories : list[str]
List of category names that A and B will be contrasted to. Should be in same domain.
labels : dict
None by default. Labels are dictionary of {'a_and_b': 'A and B', ...} to be shown
above each category.
term_ranker : TermRanker
Class for returning a term-frequency convention_df
scorer : termscoring class, optional
Term scoring class for lexicon mining. Default: `scattertext.termscoring.ScaledFScore` | Parameters
----------
term_doc_matrix : TermDocMatrix
TermDocMatrix (or descendant) which will be used in constructing square.
category_a : str
Category name for term A
category_b : str
Category name for term B (in opposition to A)
neutral_categories : list[str]
List of category names that A and B will be contrasted to. Should be in same domain.
labels : dict
None by default. Labels are dictionary of {'a_and_b': 'A and B', ...} to be shown
above each category.
term_ranker : TermRanker
Class for returning a term-frequency convention_df
scorer : termscoring class, optional
Term scoring class for lexicon mining. Default: `scattertext.termscoring.ScaledFScore` | [
"Parameters",
"----------",
"term_doc_matrix",
":",
"TermDocMatrix",
"TermDocMatrix",
"(",
"or",
"descendant",
")",
"which",
"will",
"be",
"used",
"in",
"constructing",
"square",
".",
"category_a",
":",
"str",
"Category",
"name",
"for",
"term",
"A",
"category_b",
... | def __init__(self,
term_doc_matrix,
category_a,
category_b,
neutral_categories,
labels=None,
term_ranker=AbsoluteFrequencyRanker,
scorer=None):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
TermDocMatrix (or descendant) which will be used in constructing square.
category_a : str
Category name for term A
category_b : str
Category name for term B (in opposition to A)
neutral_categories : list[str]
List of category names that A and B will be contrasted to. Should be in same domain.
labels : dict
None by default. Labels are dictionary of {'a_and_b': 'A and B', ...} to be shown
above each category.
term_ranker : TermRanker
Class for returning a term-frequency convention_df
scorer : termscoring class, optional
Term scoring class for lexicon mining. Default: `scattertext.termscoring.ScaledFScore`
'''
assert category_a in term_doc_matrix.get_categories()
assert category_b in term_doc_matrix.get_categories()
for category in neutral_categories:
assert category in term_doc_matrix.get_categories()
if len(neutral_categories) == 0:
raise EmptyNeutralCategoriesError()
self.category_a_ = category_a
self.category_b_ = category_b
self.neutral_categories_ = neutral_categories
self._build_square(term_doc_matrix, term_ranker, labels, scorer) | [
"def",
"__init__",
"(",
"self",
",",
"term_doc_matrix",
",",
"category_a",
",",
"category_b",
",",
"neutral_categories",
",",
"labels",
"=",
"None",
",",
"term_ranker",
"=",
"AbsoluteFrequencyRanker",
",",
"scorer",
"=",
"None",
")",
":",
"assert",
"category_a",... | https://github.com/JasonKessler/scattertext/blob/ef33f06d4c31f9d64b551a7ab86bf157aca82644/scattertext/semioticsquare/SemioticSquare.py#L55-L91 | ||
Bitmessage/PyBitmessage | 97612b049e0453867d6d90aa628f8e7b007b4d85 | src/network/bmproto.py | python | BMProto.bm_command_portcheck | (self) | return True | Incoming port check request, queue it. | Incoming port check request, queue it. | [
"Incoming",
"port",
"check",
"request",
"queue",
"it",
"."
] | def bm_command_portcheck(self):
"""Incoming port check request, queue it."""
portCheckerQueue.put(Peer(self.destination, self.peerNode.port))
return True | [
"def",
"bm_command_portcheck",
"(",
"self",
")",
":",
"portCheckerQueue",
".",
"put",
"(",
"Peer",
"(",
"self",
".",
"destination",
",",
"self",
".",
"peerNode",
".",
"port",
")",
")",
"return",
"True"
] | https://github.com/Bitmessage/PyBitmessage/blob/97612b049e0453867d6d90aa628f8e7b007b4d85/src/network/bmproto.py#L476-L479 | |
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/inject/thirdparty/bottle/bottle.py | python | BaseRequest.params | (self) | return params | A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. | A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. | [
"A",
":",
"class",
":",
"FormsDict",
"with",
"the",
"combined",
"values",
"of",
":",
"attr",
":",
"query",
"and",
":",
"attr",
":",
"forms",
".",
"File",
"uploads",
"are",
"stored",
"in",
":",
"attr",
":",
"files",
"."
] | def params(self):
""" A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. """
params = FormsDict()
for key, value in self.query.allitems():
params[key] = value
for key, value in self.forms.allitems():
params[key] = value
return params | [
"def",
"params",
"(",
"self",
")",
":",
"params",
"=",
"FormsDict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"query",
".",
"allitems",
"(",
")",
":",
"params",
"[",
"key",
"]",
"=",
"value",
"for",
"key",
",",
"value",
"in",
"self... | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/bottle/bottle.py#L983-L991 | |
robotlearn/pyrobolearn | 9cd7c060723fda7d2779fa255ac998c2c82b8436 | pyrobolearn/simulators/bullet.py | python | Bullet.get_base_linear_velocity | (self, body_id) | return self.get_base_velocity(body_id)[0] | Return the linear velocity of the base.
Args:
body_id (int): object unique id, as returned from `load_urdf`.
Returns:
np.array[float[3]]: linear velocity of the base in Cartesian world space coordinates | Return the linear velocity of the base. | [
"Return",
"the",
"linear",
"velocity",
"of",
"the",
"base",
"."
] | def get_base_linear_velocity(self, body_id):
"""
Return the linear velocity of the base.
Args:
body_id (int): object unique id, as returned from `load_urdf`.
Returns:
np.array[float[3]]: linear velocity of the base in Cartesian world space coordinates
"""
return self.get_base_velocity(body_id)[0] | [
"def",
"get_base_linear_velocity",
"(",
"self",
",",
"body_id",
")",
":",
"return",
"self",
".",
"get_base_velocity",
"(",
"body_id",
")",
"[",
"0",
"]"
] | https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/simulators/bullet.py#L1383-L1393 | |
projectatomic/atomicapp | fba5cbb0a42b79418ac85ab93036a4404b92a431 | atomicapp/utils.py | python | Utils.getUserName | () | return user | Finds the username of the user running the application. Uses the
SUDO_USER and USER environment variables. If runnning within a
container, SUDO_USER and USER varibles must be passed for proper
detection.
Ex. docker run -v /:/host -e SUDO_USER -e USER foobar | Finds the username of the user running the application. Uses the
SUDO_USER and USER environment variables. If runnning within a
container, SUDO_USER and USER varibles must be passed for proper
detection.
Ex. docker run -v /:/host -e SUDO_USER -e USER foobar | [
"Finds",
"the",
"username",
"of",
"the",
"user",
"running",
"the",
"application",
".",
"Uses",
"the",
"SUDO_USER",
"and",
"USER",
"environment",
"variables",
".",
"If",
"runnning",
"within",
"a",
"container",
"SUDO_USER",
"and",
"USER",
"varibles",
"must",
"be... | def getUserName():
"""
Finds the username of the user running the application. Uses the
SUDO_USER and USER environment variables. If runnning within a
container, SUDO_USER and USER varibles must be passed for proper
detection.
Ex. docker run -v /:/host -e SUDO_USER -e USER foobar
"""
sudo_user = os.environ.get('SUDO_USER')
if os.getegid() == 0 and sudo_user is None:
user = 'root'
elif sudo_user is not None:
user = sudo_user
else:
user = os.environ.get('USER')
return user | [
"def",
"getUserName",
"(",
")",
":",
"sudo_user",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SUDO_USER'",
")",
"if",
"os",
".",
"getegid",
"(",
")",
"==",
"0",
"and",
"sudo_user",
"is",
"None",
":",
"user",
"=",
"'root'",
"elif",
"sudo_user",
"is"... | https://github.com/projectatomic/atomicapp/blob/fba5cbb0a42b79418ac85ab93036a4404b92a431/atomicapp/utils.py#L439-L455 | |
malwaredllc/byob | 3924dd6aea6d0421397cdf35f692933b340bfccf | web-gui/buildyourownbotnet/core/payloads.py | python | Payload.kill | (self) | Shutdown the current connection | Shutdown the current connection | [
"Shutdown",
"the",
"current",
"connection"
] | def kill(self):
"""
Shutdown the current connection
"""
try:
self.flags.connection.clear()
self.flags.passive.clear()
self.flags.prompt.clear()
self.connection.close()
# kill threads
for thread in list(self.handlers):
try:
self.stop(thread)
except Exception as e:
log("{} error: {}".format(self.kill.__name__, str(e)))
# kill sub processes (subprocess.Popen)
for proc in self.execute.process_list.values():
try:
proc.kill()
except: pass
# kill child processes (multiprocessing.Process)
for child_proc in self.child_procs.values():
try:
child_proc.terminate()
except: pass
except Exception as e:
log("{} error: {}".format(self.kill.__name__, str(e))) | [
"def",
"kill",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"flags",
".",
"connection",
".",
"clear",
"(",
")",
"self",
".",
"flags",
".",
"passive",
".",
"clear",
"(",
")",
"self",
".",
"flags",
".",
"prompt",
".",
"clear",
"(",
")",
"self",
... | https://github.com/malwaredllc/byob/blob/3924dd6aea6d0421397cdf35f692933b340bfccf/web-gui/buildyourownbotnet/core/payloads.py#L367-L397 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/proxy/v1/service/session/participant/message_interaction.py | python | MessageInteractionPage.__init__ | (self, version, response, solution) | Initialize the MessageInteractionPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the resource's parent Service
:param session_sid: The SID of the resource's parent Session
:param participant_sid: The SID of the Participant resource
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage | Initialize the MessageInteractionPage | [
"Initialize",
"the",
"MessageInteractionPage"
] | def __init__(self, version, response, solution):
"""
Initialize the MessageInteractionPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The SID of the resource's parent Service
:param session_sid: The SID of the resource's parent Session
:param participant_sid: The SID of the Participant resource
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage
"""
super(MessageInteractionPage, self).__init__(version, response)
# Path Solution
self._solution = solution | [
"def",
"__init__",
"(",
"self",
",",
"version",
",",
"response",
",",
"solution",
")",
":",
"super",
"(",
"MessageInteractionPage",
",",
"self",
")",
".",
"__init__",
"(",
"version",
",",
"response",
")",
"# Path Solution",
"self",
".",
"_solution",
"=",
"... | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/proxy/v1/service/session/participant/message_interaction.py#L191-L207 | ||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/psycopg2/extras.py | python | wait_select | (conn) | Wait until a connection or cursor has data available.
The function is an example of a wait callback to be registered with
`~psycopg2.extensions.set_wait_callback()`. This function uses
:py:func:`~select.select()` to wait for data available. | Wait until a connection or cursor has data available. | [
"Wait",
"until",
"a",
"connection",
"or",
"cursor",
"has",
"data",
"available",
"."
] | def wait_select(conn):
"""Wait until a connection or cursor has data available.
The function is an example of a wait callback to be registered with
`~psycopg2.extensions.set_wait_callback()`. This function uses
:py:func:`~select.select()` to wait for data available.
"""
import select
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
while 1:
state = conn.poll()
if state == POLL_OK:
break
elif state == POLL_READ:
select.select([conn.fileno()], [], [])
elif state == POLL_WRITE:
select.select([], [conn.fileno()], [])
else:
raise conn.OperationalError("bad state from poll: %s" % state) | [
"def",
"wait_select",
"(",
"conn",
")",
":",
"import",
"select",
"from",
"psycopg2",
".",
"extensions",
"import",
"POLL_OK",
",",
"POLL_READ",
",",
"POLL_WRITE",
"while",
"1",
":",
"state",
"=",
"conn",
".",
"poll",
"(",
")",
"if",
"state",
"==",
"POLL_O... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/psycopg2/extras.py#L566-L586 | ||
jbjorne/TEES | caf19a4a1352ac59f5dc13a8684cc42ce4342d9d | Utils/Combine.py | python | getInteractions | (a, b, gold, skip=None, skipCounts=None) | return interactions | [] | def getInteractions(a, b, gold, skip=None, skipCounts=None):
interactions = OrderedDict()
for interaction in a.findall('interaction'):
addInteraction(interaction, interactions, "a", skip, skipCounts)
for interaction in b.findall('interaction'):
addInteraction(interaction, interactions, "b", skip, skipCounts)
if gold:
numIntersentence = 0
for interaction in gold.findall('interaction'):
#print interaction.get("e1").split(".i")[0], interaction.get("e2").split(".i")[0]
if interaction.get("e1").split(".e")[0] != interaction.get("e2").split(".e")[0]:
numIntersentence += 1
continue
addInteraction(interaction, interactions, "gold", skip, skipCounts)
#print "Skipped", numIntersentence, "intersentence interactions"
return interactions | [
"def",
"getInteractions",
"(",
"a",
",",
"b",
",",
"gold",
",",
"skip",
"=",
"None",
",",
"skipCounts",
"=",
"None",
")",
":",
"interactions",
"=",
"OrderedDict",
"(",
")",
"for",
"interaction",
"in",
"a",
".",
"findall",
"(",
"'interaction'",
")",
":"... | https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/Combine.py#L55-L70 | |||
Anaconda-Platform/anaconda-project | df5ec33c12591e6512436d38d36c6132fa2e9618 | anaconda_project/internal/cli/upload.py | python | main | (args) | return upload_command(args.directory, args.private, args.site, args.user, args.token, args.suffix) | Start the upload command and return exit status code. | Start the upload command and return exit status code. | [
"Start",
"the",
"upload",
"command",
"and",
"return",
"exit",
"status",
"code",
"."
] | def main(args):
"""Start the upload command and return exit status code."""
return upload_command(args.directory, args.private, args.site, args.user, args.token, args.suffix) | [
"def",
"main",
"(",
"args",
")",
":",
"return",
"upload_command",
"(",
"args",
".",
"directory",
",",
"args",
".",
"private",
",",
"args",
".",
"site",
",",
"args",
".",
"user",
",",
"args",
".",
"token",
",",
"args",
".",
"suffix",
")"
] | https://github.com/Anaconda-Platform/anaconda-project/blob/df5ec33c12591e6512436d38d36c6132fa2e9618/anaconda_project/internal/cli/upload.py#L32-L34 | |
joxeankoret/pyew | 8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8 | vtrace/tools/win32heap.py | python | Win32Heap.getUCRDict | (self) | return self.ucrdict | Retrieve a dictionary of <ucr_address>:<ucr_size> items.
(If this windows version doesn't support UCRs, the dict will be empty) | Retrieve a dictionary of <ucr_address>:<ucr_size> items. | [
"Retrieve",
"a",
"dictionary",
"of",
"<ucr_address",
">",
":",
"<ucr_size",
">",
"items",
"."
] | def getUCRDict(self):
'''
Retrieve a dictionary of <ucr_address>:<ucr_size> items.
(If this windows version doesn't support UCRs, the dict will be empty)
'''
if self.ucrdict == None:
self.ucrdict = {}
if self.heap.vsHasField('UCRList'):
listhead_va = self.address + self.heap.vsGetOffset('UCRList')
for lva in self._getListEntries(listhead_va):
ucrent = self.trace.getStruct('ntdll.HEAP_UCR_DESCRIPTOR', lva)
if ucrent.Size != 0:
self.ucrdict[ucrent.Address] = ucrent.Size
return self.ucrdict | [
"def",
"getUCRDict",
"(",
"self",
")",
":",
"if",
"self",
".",
"ucrdict",
"==",
"None",
":",
"self",
".",
"ucrdict",
"=",
"{",
"}",
"if",
"self",
".",
"heap",
".",
"vsHasField",
"(",
"'UCRList'",
")",
":",
"listhead_va",
"=",
"self",
".",
"address",
... | https://github.com/joxeankoret/pyew/blob/8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8/vtrace/tools/win32heap.py#L144-L159 | |
ganeti/ganeti | d340a9ddd12f501bef57da421b5f9b969a4ba905 | lib/cmdlib/instance_set_params.py | python | LUInstanceSetParams._InstanceCommunicationDDM | (cfg, instance_communication, instance) | Create a NIC mod that adds or removes the instance
communication NIC to a running instance.
The NICS are dynamically created using the Dynamic Device
Modification (DDM). This function produces a NIC modification
(mod) that inserts an additional NIC meant for instance
communication in or removes an existing instance communication NIC
from a running instance, using DDM.
@type cfg: L{config.ConfigWriter}
@param cfg: cluster configuration
@type instance_communication: boolean
@param instance_communication: whether instance communication is
enabled or disabled
@type instance: L{objects.Instance}
@param instance: instance to which the NIC mod will be applied to
@rtype: (L{constants.DDM_ADD}, -1, parameters) or
(L{constants.DDM_REMOVE}, -1, parameters) or
L{None}
@return: DDM mod containing an action to add or remove the NIC, or
None if nothing needs to be done | Create a NIC mod that adds or removes the instance
communication NIC to a running instance. | [
"Create",
"a",
"NIC",
"mod",
"that",
"adds",
"or",
"removes",
"the",
"instance",
"communication",
"NIC",
"to",
"a",
"running",
"instance",
"."
] | def _InstanceCommunicationDDM(cfg, instance_communication, instance):
"""Create a NIC mod that adds or removes the instance
communication NIC to a running instance.
The NICS are dynamically created using the Dynamic Device
Modification (DDM). This function produces a NIC modification
(mod) that inserts an additional NIC meant for instance
communication in or removes an existing instance communication NIC
from a running instance, using DDM.
@type cfg: L{config.ConfigWriter}
@param cfg: cluster configuration
@type instance_communication: boolean
@param instance_communication: whether instance communication is
enabled or disabled
@type instance: L{objects.Instance}
@param instance: instance to which the NIC mod will be applied to
@rtype: (L{constants.DDM_ADD}, -1, parameters) or
(L{constants.DDM_REMOVE}, -1, parameters) or
L{None}
@return: DDM mod containing an action to add or remove the NIC, or
None if nothing needs to be done
"""
nic_name = ComputeInstanceCommunicationNIC(instance.name)
instance_communication_nic = None
for nic in instance.nics:
if nic.name == nic_name:
instance_communication_nic = nic
break
if instance_communication and not instance_communication_nic:
action = constants.DDM_ADD
params = {constants.INIC_NAME: nic_name,
constants.INIC_MAC: constants.VALUE_GENERATE,
constants.INIC_IP: constants.NIC_IP_POOL,
constants.INIC_NETWORK:
cfg.GetInstanceCommunicationNetwork()}
elif not instance_communication and instance_communication_nic:
action = constants.DDM_REMOVE
params = None
else:
action = None
params = None
if action is not None:
return (action, -1, params)
else:
return None | [
"def",
"_InstanceCommunicationDDM",
"(",
"cfg",
",",
"instance_communication",
",",
"instance",
")",
":",
"nic_name",
"=",
"ComputeInstanceCommunicationNIC",
"(",
"instance",
".",
"name",
")",
"instance_communication_nic",
"=",
"None",
"for",
"nic",
"in",
"instance",
... | https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/cmdlib/instance_set_params.py#L844-L897 | ||
limodou/ulipad | 4c7d590234f39cac80bb1d36dca095b646e287fb | modules/wxctrl/FlatNotebook.py | python | PageContainer.SetImageList | (self, imglist) | Sets the image list for the page control. | Sets the image list for the page control. | [
"Sets",
"the",
"image",
"list",
"for",
"the",
"page",
"control",
"."
] | def SetImageList(self, imglist):
""" Sets the image list for the page control. """
self._ImageList = imglist | [
"def",
"SetImageList",
"(",
"self",
",",
"imglist",
")",
":",
"self",
".",
"_ImageList",
"=",
"imglist"
] | https://github.com/limodou/ulipad/blob/4c7d590234f39cac80bb1d36dca095b646e287fb/modules/wxctrl/FlatNotebook.py#L4888-L4891 | ||
x0rz/EQGRP_Lost_in_Translation | 6692b1486f562f027567a49523b8c151a4050988 | windows/exploits/ZIBE/pyreadline/console/ironpython_console.py | python | Console.getkeypress | (self) | u'''Return next key press event from the queue, ignoring others. | u'''Return next key press event from the queue, ignoring others. | [
"u",
"Return",
"next",
"key",
"press",
"event",
"from",
"the",
"queue",
"ignoring",
"others",
"."
] | def getkeypress(self):
u'''Return next key press event from the queue, ignoring others.'''
ck = System.ConsoleKey
while 1:
e = System.Console.ReadKey(True)
if e.Key == System.ConsoleKey.PageDown: #PageDown
self.scroll_window(12)
elif e.Key == System.ConsoleKey.PageUp:#PageUp
self.scroll_window(-12)
elif str(e.KeyChar) == u"\000":#Drop deadkeys
log(u"Deadkey: %s"%e)
return event(self, e)
else:
return event(self, e) | [
"def",
"getkeypress",
"(",
"self",
")",
":",
"ck",
"=",
"System",
".",
"ConsoleKey",
"while",
"1",
":",
"e",
"=",
"System",
".",
"Console",
".",
"ReadKey",
"(",
"True",
")",
"if",
"e",
".",
"Key",
"==",
"System",
".",
"ConsoleKey",
".",
"PageDown",
... | https://github.com/x0rz/EQGRP_Lost_in_Translation/blob/6692b1486f562f027567a49523b8c151a4050988/windows/exploits/ZIBE/pyreadline/console/ironpython_console.py#L303-L316 | ||
CenterForOpenScience/osf.io | cc02691be017e61e2cd64f19b848b2f4c18dcc84 | osf/models/conference.py | python | Conference.valid_submissions | (self) | return self.submissions.filter(is_public=True, is_deleted=False) | Returns valid conference submissions - nodes can't be public or deleted | Returns valid conference submissions - nodes can't be public or deleted | [
"Returns",
"valid",
"conference",
"submissions",
"-",
"nodes",
"can",
"t",
"be",
"public",
"or",
"deleted"
] | def valid_submissions(self):
"""
Returns valid conference submissions - nodes can't be public or deleted
"""
return self.submissions.filter(is_public=True, is_deleted=False) | [
"def",
"valid_submissions",
"(",
"self",
")",
":",
"return",
"self",
".",
"submissions",
".",
"filter",
"(",
"is_public",
"=",
"True",
",",
"is_deleted",
"=",
"False",
")"
] | https://github.com/CenterForOpenScience/osf.io/blob/cc02691be017e61e2cd64f19b848b2f4c18dcc84/osf/models/conference.py#L85-L89 | |
yt-project/yt | dc7b24f9b266703db4c843e329c6c8644d47b824 | yt/frontends/amrvac/data_structures.py | python | AMRVACHierarchy.__init__ | (self, ds, dataset_type="amrvac") | [] | def __init__(self, ds, dataset_type="amrvac"):
self.dataset_type = dataset_type
self.dataset = weakref.proxy(ds)
# the index file *is* the datfile
self.index_filename = self.dataset.parameter_filename
self.directory = os.path.dirname(self.index_filename)
self.float_type = np.float64
super().__init__(ds, dataset_type) | [
"def",
"__init__",
"(",
"self",
",",
"ds",
",",
"dataset_type",
"=",
"\"amrvac\"",
")",
":",
"self",
".",
"dataset_type",
"=",
"dataset_type",
"self",
".",
"dataset",
"=",
"weakref",
".",
"proxy",
"(",
"ds",
")",
"# the index file *is* the datfile",
"self",
... | https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/frontends/amrvac/data_structures.py#L88-L96 | ||||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/chat/v2/service/channel/__init__.py | python | ChannelPage.get_instance | (self, payload) | return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) | Build an instance of ChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.channel.ChannelInstance
:rtype: twilio.rest.chat.v2.service.channel.ChannelInstance | Build an instance of ChannelInstance | [
"Build",
"an",
"instance",
"of",
"ChannelInstance"
] | def get_instance(self, payload):
"""
Build an instance of ChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.channel.ChannelInstance
:rtype: twilio.rest.chat.v2.service.channel.ChannelInstance
"""
return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"ChannelInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
")"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/chat/v2/service/channel/__init__.py#L209-L218 | |
enzienaudio/hvcc | 30e47328958d600c54889e2a254c3f17f2b2fd06 | core/hv2ir/HLangRandom.py | python | HLangRandom.__init__ | (self, obj_type, args, graph, annotations=None) | [] | def __init__(self, obj_type, args, graph, annotations=None):
assert obj_type == "random"
HeavyLangObject.__init__(self, obj_type, args, graph,
num_inlets=2,
num_outlets=1,
annotations=annotations) | [
"def",
"__init__",
"(",
"self",
",",
"obj_type",
",",
"args",
",",
"graph",
",",
"annotations",
"=",
"None",
")",
":",
"assert",
"obj_type",
"==",
"\"random\"",
"HeavyLangObject",
".",
"__init__",
"(",
"self",
",",
"obj_type",
",",
"args",
",",
"graph",
... | https://github.com/enzienaudio/hvcc/blob/30e47328958d600c54889e2a254c3f17f2b2fd06/core/hv2ir/HLangRandom.py#L25-L30 | ||||
pyjs/pyjs | 6c4a3d3a67300cd5df7f95a67ca9dcdc06950523 | pyjs/linker.py | python | BaseLinker.merge_resources | (self, dir_name) | gets a directory path for each module visited, this can be
used to collect resources e.g. public folders | gets a directory path for each module visited, this can be
used to collect resources e.g. public folders | [
"gets",
"a",
"directory",
"path",
"for",
"each",
"module",
"visited",
"this",
"can",
"be",
"used",
"to",
"collect",
"resources",
"e",
".",
"g",
".",
"public",
"folders"
] | def merge_resources(self, dir_name):
"""gets a directory path for each module visited, this can be
used to collect resources e.g. public folders"""
pass | [
"def",
"merge_resources",
"(",
"self",
",",
"dir_name",
")",
":",
"pass"
] | https://github.com/pyjs/pyjs/blob/6c4a3d3a67300cd5df7f95a67ca9dcdc06950523/pyjs/linker.py#L409-L412 | ||
FreeOpcUa/python-opcua | 67f15551884d7f11659d52483e7b932999ca3a75 | opcua/common/node.py | python | Node.get_variables | (self) | return self.get_children(refs=ua.ObjectIds.HasComponent, nodeclassmask=ua.NodeClass.Variable) | return variables of node.
properties are child nodes with a reference of type HasComponent and a NodeClass of Variable | return variables of node.
properties are child nodes with a reference of type HasComponent and a NodeClass of Variable | [
"return",
"variables",
"of",
"node",
".",
"properties",
"are",
"child",
"nodes",
"with",
"a",
"reference",
"of",
"type",
"HasComponent",
"and",
"a",
"NodeClass",
"of",
"Variable"
] | def get_variables(self):
"""
return variables of node.
properties are child nodes with a reference of type HasComponent and a NodeClass of Variable
"""
return self.get_children(refs=ua.ObjectIds.HasComponent, nodeclassmask=ua.NodeClass.Variable) | [
"def",
"get_variables",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_children",
"(",
"refs",
"=",
"ua",
".",
"ObjectIds",
".",
"HasComponent",
",",
"nodeclassmask",
"=",
"ua",
".",
"NodeClass",
".",
"Variable",
")"
] | https://github.com/FreeOpcUa/python-opcua/blob/67f15551884d7f11659d52483e7b932999ca3a75/opcua/common/node.py#L325-L330 | |
alanhamlett/pip-update-requirements | ce875601ef278c8ce00ad586434a978731525561 | pur/packages/pip/_vendor/distlib/_backport/tarfile.py | python | TarFile._load | (self) | Read through the entire archive file and look for readable
members. | Read through the entire archive file and look for readable
members. | [
"Read",
"through",
"the",
"entire",
"archive",
"file",
"and",
"look",
"for",
"readable",
"members",
"."
] | def _load(self):
"""Read through the entire archive file and look for readable
members.
"""
while True:
tarinfo = self.next()
if tarinfo is None:
break
self._loaded = True | [
"def",
"_load",
"(",
"self",
")",
":",
"while",
"True",
":",
"tarinfo",
"=",
"self",
".",
"next",
"(",
")",
"if",
"tarinfo",
"is",
"None",
":",
"break",
"self",
".",
"_loaded",
"=",
"True"
] | https://github.com/alanhamlett/pip-update-requirements/blob/ce875601ef278c8ce00ad586434a978731525561/pur/packages/pip/_vendor/distlib/_backport/tarfile.py#L2486-L2494 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/whoosh/matching/binary.py | python | UnionMatcher.spans | (self) | [] | def spans(self):
if not self.a.is_active():
return self.b.spans()
if not self.b.is_active():
return self.a.spans()
id_a = self.a.id()
id_b = self.b.id()
if id_a < id_b:
return self.a.spans()
elif id_b < id_a:
return self.b.spans()
else:
return sorted(set(self.a.spans()) | set(self.b.spans())) | [
"def",
"spans",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"a",
".",
"is_active",
"(",
")",
":",
"return",
"self",
".",
"b",
".",
"spans",
"(",
")",
"if",
"not",
"self",
".",
"b",
".",
"is_active",
"(",
")",
":",
"return",
"self",
".",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/matching/binary.py#L221-L234 | ||||
awslabs/dgl-ke | e9d4f4916f570d2c9f2e1aa3bdec9196c68120e5 | python/dglke/models/pytorch/tensor_models.py | python | ExternalEmbedding.update | (self, gpu_id=-1) | Update embeddings in a sparse manner
Sparse embeddings are updated in mini batches. we maintains gradient states for
each embedding so they can be updated separately.
Parameters
----------
gpu_id : int
Which gpu to accelerate the calculation. if -1 is provided, cpu is used. | Update embeddings in a sparse manner
Sparse embeddings are updated in mini batches. we maintains gradient states for
each embedding so they can be updated separately. | [
"Update",
"embeddings",
"in",
"a",
"sparse",
"manner",
"Sparse",
"embeddings",
"are",
"updated",
"in",
"mini",
"batches",
".",
"we",
"maintains",
"gradient",
"states",
"for",
"each",
"embedding",
"so",
"they",
"can",
"be",
"updated",
"separately",
"."
] | def update(self, gpu_id=-1):
""" Update embeddings in a sparse manner
Sparse embeddings are updated in mini batches. we maintains gradient states for
each embedding so they can be updated separately.
Parameters
----------
gpu_id : int
Which gpu to accelerate the calculation. if -1 is provided, cpu is used.
"""
self.state_step += 1
with th.no_grad():
for idx, data in self.trace:
grad = data.grad.data
clr = self.args.lr
#clr = self.args.lr / (1 + (self.state_step - 1) * group['lr_decay'])
# the update is non-linear so indices must be unique
grad_indices = idx
grad_values = grad
if self.async_q is not None:
grad_indices.share_memory_()
grad_values.share_memory_()
self.async_q.put((grad_indices, grad_values, gpu_id))
else:
grad_sum = (grad_values * grad_values).mean(1)
device = self.state_sum.device
if device != grad_indices.device:
grad_indices = grad_indices.to(device)
if device != grad_sum.device:
grad_sum = grad_sum.to(device)
if self.has_cross_rel:
cpu_mask = self.cpu_bitmap[grad_indices]
cpu_idx = grad_indices[cpu_mask]
if cpu_idx.shape[0] > 0:
cpu_grad = grad_values[cpu_mask]
cpu_sum = grad_sum[cpu_mask].cpu()
cpu_idx = cpu_idx.cpu()
self.global_emb.state_sum.index_add_(0, cpu_idx, cpu_sum)
std = self.global_emb.state_sum[cpu_idx]
if gpu_id >= 0:
std = std.cuda(gpu_id)
std_values = std.sqrt_().add_(1e-10).unsqueeze(1)
tmp = (-clr * cpu_grad / std_values)
tmp = tmp.cpu()
self.global_emb.emb.index_add_(0, cpu_idx, tmp)
self.state_sum.index_add_(0, grad_indices, grad_sum)
std = self.state_sum[grad_indices] # _sparse_mask
if gpu_id >= 0:
std = std.cuda(gpu_id)
std_values = std.sqrt_().add_(1e-10).unsqueeze(1)
tmp = (-clr * grad_values / std_values)
if tmp.device != device:
tmp = tmp.to(device)
# TODO(zhengda) the overhead is here.
self.emb.index_add_(0, grad_indices, tmp)
self.trace = [] | [
"def",
"update",
"(",
"self",
",",
"gpu_id",
"=",
"-",
"1",
")",
":",
"self",
".",
"state_step",
"+=",
"1",
"with",
"th",
".",
"no_grad",
"(",
")",
":",
"for",
"idx",
",",
"data",
"in",
"self",
".",
"trace",
":",
"grad",
"=",
"data",
".",
"grad... | https://github.com/awslabs/dgl-ke/blob/e9d4f4916f570d2c9f2e1aa3bdec9196c68120e5/python/dglke/models/pytorch/tensor_models.py#L304-L362 | ||
nipy/nibabel | 4703f4d8e32be4cec30e829c2d93ebe54759bb62 | nibabel/nifti1.py | python | Nifti1Extensions.get_codes | (self) | return [e.get_code() for e in self] | Return a list of the extension code of all available extensions | Return a list of the extension code of all available extensions | [
"Return",
"a",
"list",
"of",
"the",
"extension",
"code",
"of",
"all",
"available",
"extensions"
] | def get_codes(self):
"""Return a list of the extension code of all available extensions"""
return [e.get_code() for e in self] | [
"def",
"get_codes",
"(",
"self",
")",
":",
"return",
"[",
"e",
".",
"get_code",
"(",
")",
"for",
"e",
"in",
"self",
"]"
] | https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/nifti1.py#L512-L514 | |
gitless-vcs/gitless | 3ac28e39e170acdcd1590e0a25a06790ae0e6922 | gitless/core.py | python | init_repository | (url=None, only=None, exclude=None) | Creates a new Gitless's repository in the cwd.
Args:
url: if given the local repository will be a clone of the remote repository
given by this url.
only: if given, this local repository will consist only of the branches
in this set
exclude: if given, and only is not given, this local repository will
consistent of all branches not in this set | Creates a new Gitless's repository in the cwd. | [
"Creates",
"a",
"new",
"Gitless",
"s",
"repository",
"in",
"the",
"cwd",
"."
] | def init_repository(url=None, only=None, exclude=None):
"""Creates a new Gitless's repository in the cwd.
Args:
url: if given the local repository will be a clone of the remote repository
given by this url.
only: if given, this local repository will consist only of the branches
in this set
exclude: if given, and only is not given, this local repository will
consistent of all branches not in this set
"""
cwd = os.getcwd()
try:
error_on_none(pygit2.discover_repository(cwd))
raise GlError('You are already in a Gitless repository')
except KeyError: # Expected
if not url:
repo = pygit2.init_repository(cwd)
# We also create an initial root commit
git('commit', '--allow-empty', '-m', 'Initialize repository')
return repo
try:
git('clone', url, cwd)
except CalledProcessError as e:
raise GlError(e.stderr)
# We get all remote branches as well and create local equivalents
# Flags: only branches take precedence over exclude branches.
repo = Repository()
remote = repo.remotes['origin']
for rb in (remote.lookup_branch(bn) for bn in remote.listall_branches()):
if rb.branch_name == 'master':
continue
if only and rb.branch_name not in only:
continue
elif not only and exclude and rb.branch_name in exclude:
continue
new_b = repo.create_branch(rb.branch_name, rb.head)
new_b.upstream = rb
return repo | [
"def",
"init_repository",
"(",
"url",
"=",
"None",
",",
"only",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"error_on_none",
"(",
"pygit2",
".",
"discover_repository",
"(",
"cwd",
")",
")... | https://github.com/gitless-vcs/gitless/blob/3ac28e39e170acdcd1590e0a25a06790ae0e6922/gitless/core.py#L54-L94 | ||
spectacles/CodeComplice | 8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62 | libs/codeintel2/util.py | python | indent | (s, width=4, skip_first_line=False) | indent(s, [width=4]) -> 's' indented by 'width' spaces
The optional "skip_first_line" argument is a boolean (default False)
indicating if the first line should NOT be indented. | indent(s, [width=4]) -> 's' indented by 'width' spaces | [
"indent",
"(",
"s",
"[",
"width",
"=",
"4",
"]",
")",
"-",
">",
"s",
"indented",
"by",
"width",
"spaces"
] | def indent(s, width=4, skip_first_line=False):
"""indent(s, [width=4]) -> 's' indented by 'width' spaces
The optional "skip_first_line" argument is a boolean (default False)
indicating if the first line should NOT be indented.
"""
lines = s.splitlines(1)
indentstr = ' '*width
if skip_first_line:
return indentstr.join(lines)
else:
return indentstr + indentstr.join(lines) | [
"def",
"indent",
"(",
"s",
",",
"width",
"=",
"4",
",",
"skip_first_line",
"=",
"False",
")",
":",
"lines",
"=",
"s",
".",
"splitlines",
"(",
"1",
")",
"indentstr",
"=",
"' '",
"*",
"width",
"if",
"skip_first_line",
":",
"return",
"indentstr",
".",
"... | https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/util.py#L711-L722 | ||
mcneel/rhinoscriptsyntax | c49bd0bf24c2513bdcb84d1bf307144489600fd9 | Scripts/rhinoscript/material.py | python | IsMaterialDefault | (material_index) | return mat and mat.IsDefaultMaterial | Verifies a material is a copy of Rhino's built-in "default" material.
The default material is used by objects and layers that have not been
assigned a material.
Parameters:
material_index (number): the zero-based material index
Returns:
bool: True or False indicating success or failure
Example:
import rhinoscriptsyntax as rs
obj = rs.GetObject()
if obj:
index = rs.ObjectMaterialIndex(obj)
if rs.IsMaterialDefault(index):
print "Object is assigned default material."
else:
print "Object is not assigned default material."
See Also:
LayerMaterialIndex
ObjectMaterialIndex | Verifies a material is a copy of Rhino's built-in "default" material.
The default material is used by objects and layers that have not been
assigned a material.
Parameters:
material_index (number): the zero-based material index
Returns:
bool: True or False indicating success or failure
Example:
import rhinoscriptsyntax as rs
obj = rs.GetObject()
if obj:
index = rs.ObjectMaterialIndex(obj)
if rs.IsMaterialDefault(index):
print "Object is assigned default material."
else:
print "Object is not assigned default material."
See Also:
LayerMaterialIndex
ObjectMaterialIndex | [
"Verifies",
"a",
"material",
"is",
"a",
"copy",
"of",
"Rhino",
"s",
"built",
"-",
"in",
"default",
"material",
".",
"The",
"default",
"material",
"is",
"used",
"by",
"objects",
"and",
"layers",
"that",
"have",
"not",
"been",
"assigned",
"a",
"material",
... | def IsMaterialDefault(material_index):
"""Verifies a material is a copy of Rhino's built-in "default" material.
The default material is used by objects and layers that have not been
assigned a material.
Parameters:
material_index (number): the zero-based material index
Returns:
bool: True or False indicating success or failure
Example:
import rhinoscriptsyntax as rs
obj = rs.GetObject()
if obj:
index = rs.ObjectMaterialIndex(obj)
if rs.IsMaterialDefault(index):
print "Object is assigned default material."
else:
print "Object is not assigned default material."
See Also:
LayerMaterialIndex
ObjectMaterialIndex
"""
mat = scriptcontext.doc.Materials[material_index]
return mat and mat.IsDefaultMaterial | [
"def",
"IsMaterialDefault",
"(",
"material_index",
")",
":",
"mat",
"=",
"scriptcontext",
".",
"doc",
".",
"Materials",
"[",
"material_index",
"]",
"return",
"mat",
"and",
"mat",
".",
"IsDefaultMaterial"
] | https://github.com/mcneel/rhinoscriptsyntax/blob/c49bd0bf24c2513bdcb84d1bf307144489600fd9/Scripts/rhinoscript/material.py#L91-L113 | |
twisted/twisted | dee676b040dd38b847ea6fb112a712cb5e119490 | src/twisted/internet/interfaces.py | python | IReactorWin32Events.removeEvent | (event: object) | Remove an event.
@param event: a Win32 event object added using L{IReactorWin32Events.addEvent}
@return: None | Remove an event. | [
"Remove",
"an",
"event",
"."
] | def removeEvent(event: object) -> None:
"""
Remove an event.
@param event: a Win32 event object added using L{IReactorWin32Events.addEvent}
@return: None
""" | [
"def",
"removeEvent",
"(",
"event",
":",
"object",
")",
"->",
"None",
":"
] | https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/internet/interfaces.py#L881-L888 | ||
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/core/types/containers.py | python | LiteralList.__init__ | (self, literal_value) | [] | def __init__(self, literal_value):
self.is_types_iterable(literal_value)
self._literal_init(list(literal_value))
self.types = tuple(literal_value)
self.count = len(self.types)
self.name = "LiteralList({})".format(literal_value) | [
"def",
"__init__",
"(",
"self",
",",
"literal_value",
")",
":",
"self",
".",
"is_types_iterable",
"(",
"literal_value",
")",
"self",
".",
"_literal_init",
"(",
"list",
"(",
"literal_value",
")",
")",
"self",
".",
"types",
"=",
"tuple",
"(",
"literal_value",
... | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/types/containers.py#L477-L482 | ||||
avisingh599/reward-learning-rl | 8070d93e9379204f153e9044e03079bd9a354183 | softlearning/policies/base_policy.py | python | BasePolicy.actions | (self, conditions) | Compute (symbolic) actions given conditions (observations) | Compute (symbolic) actions given conditions (observations) | [
"Compute",
"(",
"symbolic",
")",
"actions",
"given",
"conditions",
"(",
"observations",
")"
] | def actions(self, conditions):
"""Compute (symbolic) actions given conditions (observations)"""
raise NotImplementedError | [
"def",
"actions",
"(",
"self",
",",
"conditions",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/avisingh599/reward-learning-rl/blob/8070d93e9379204f153e9044e03079bd9a354183/softlearning/policies/base_policy.py#L16-L18 | ||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/reprlib.py | python | Repr.repr_list | (self, x, level) | return self._repr_iterable(x, level, '[', ']', self.maxlist) | [] | def repr_list(self, x, level):
return self._repr_iterable(x, level, '[', ']', self.maxlist) | [
"def",
"repr_list",
"(",
"self",
",",
"x",
",",
"level",
")",
":",
"return",
"self",
".",
"_repr_iterable",
"(",
"x",
",",
"level",
",",
"'['",
",",
"']'",
",",
"self",
".",
"maxlist",
")"
] | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/reprlib.py#L83-L84 | |||
Droidtown/ArticutAPI | ee415bb30c9722a85334d54d7015d5ad3870205f | ArticutAPI/WS_ArticutAPI.py | python | WS_Articut.bulk_getContentWordLIST | (self, parseResultLIST, indexWithPOS=True) | return resultLIST | 取出斷詞結果中的實詞 (content word)。
每個句子內的實詞為一個 list。 | 取出斷詞結果中的實詞 (content word)。
每個句子內的實詞為一個 list。 | [
"取出斷詞結果中的實詞",
"(",
"content",
"word",
")",
"。",
"每個句子內的實詞為一個",
"list。"
] | def bulk_getContentWordLIST(self, parseResultLIST, indexWithPOS=True):
'''
取出斷詞結果中的實詞 (content word)。
每個句子內的實詞為一個 list。
'''
resultLIST = [self.POS.getContentWordLIST(x, indexWithPOS) for x in parseResultLIST]
return resultLIST | [
"def",
"bulk_getContentWordLIST",
"(",
"self",
",",
"parseResultLIST",
",",
"indexWithPOS",
"=",
"True",
")",
":",
"resultLIST",
"=",
"[",
"self",
".",
"POS",
".",
"getContentWordLIST",
"(",
"x",
",",
"indexWithPOS",
")",
"for",
"x",
"in",
"parseResultLIST",
... | https://github.com/Droidtown/ArticutAPI/blob/ee415bb30c9722a85334d54d7015d5ad3870205f/ArticutAPI/WS_ArticutAPI.py#L372-L378 | |
datitran/object_detector_app | 44e8eddeb931cced5d8cf1e283383c720a5706bf | object_detection/core/losses.py | python | HardExampleMiner.__init__ | (self,
num_hard_examples=64,
iou_threshold=0.7,
loss_type='both',
cls_loss_weight=0.05,
loc_loss_weight=0.06,
max_negatives_per_positive=None,
min_negatives_per_image=0) | Constructor.
The hard example mining implemented by this class can replicate the behavior
in the two aforementioned papers (Srivastava et al., and Liu et al).
To replicate the A2 paper (Srivastava et al), num_hard_examples is set
to a fixed parameter (64 by default) and iou_threshold is set to .7 for
running non-max-suppression the predicted boxes prior to hard mining.
In order to replicate the SSD paper (Liu et al), num_hard_examples should
be set to None, max_negatives_per_positive should be 3 and iou_threshold
should be 1.0 (in order to effectively turn off NMS).
Args:
num_hard_examples: maximum number of hard examples to be
selected per image (prior to enforcing max negative to positive ratio
constraint). If set to None, all examples obtained after NMS are
considered.
iou_threshold: minimum intersection over union for an example
to be discarded during NMS.
loss_type: use only classification losses ('cls', default),
localization losses ('loc') or both losses ('both').
In the last case, cls_loss_weight and loc_loss_weight are used to
compute weighted sum of the two losses.
cls_loss_weight: weight for classification loss.
loc_loss_weight: weight for location loss.
max_negatives_per_positive: maximum number of negatives to retain for
each positive anchor. By default, num_negatives_per_positive is None,
which means that we do not enforce a prespecified negative:positive
ratio. Note also that num_negatives_per_positives can be a float
(and will be converted to be a float even if it is passed in otherwise).
min_negatives_per_image: minimum number of negative anchors to sample for
a given image. Setting this to a positive number allows sampling
negatives in an image without any positive anchors and thus not biased
towards at least one detection per image. | Constructor. | [
"Constructor",
"."
] | def __init__(self,
num_hard_examples=64,
iou_threshold=0.7,
loss_type='both',
cls_loss_weight=0.05,
loc_loss_weight=0.06,
max_negatives_per_positive=None,
min_negatives_per_image=0):
"""Constructor.
The hard example mining implemented by this class can replicate the behavior
in the two aforementioned papers (Srivastava et al., and Liu et al).
To replicate the A2 paper (Srivastava et al), num_hard_examples is set
to a fixed parameter (64 by default) and iou_threshold is set to .7 for
running non-max-suppression the predicted boxes prior to hard mining.
In order to replicate the SSD paper (Liu et al), num_hard_examples should
be set to None, max_negatives_per_positive should be 3 and iou_threshold
should be 1.0 (in order to effectively turn off NMS).
Args:
num_hard_examples: maximum number of hard examples to be
selected per image (prior to enforcing max negative to positive ratio
constraint). If set to None, all examples obtained after NMS are
considered.
iou_threshold: minimum intersection over union for an example
to be discarded during NMS.
loss_type: use only classification losses ('cls', default),
localization losses ('loc') or both losses ('both').
In the last case, cls_loss_weight and loc_loss_weight are used to
compute weighted sum of the two losses.
cls_loss_weight: weight for classification loss.
loc_loss_weight: weight for location loss.
max_negatives_per_positive: maximum number of negatives to retain for
each positive anchor. By default, num_negatives_per_positive is None,
which means that we do not enforce a prespecified negative:positive
ratio. Note also that num_negatives_per_positives can be a float
(and will be converted to be a float even if it is passed in otherwise).
min_negatives_per_image: minimum number of negative anchors to sample for
a given image. Setting this to a positive number allows sampling
negatives in an image without any positive anchors and thus not biased
towards at least one detection per image.
"""
self._num_hard_examples = num_hard_examples
self._iou_threshold = iou_threshold
self._loss_type = loss_type
self._cls_loss_weight = cls_loss_weight
self._loc_loss_weight = loc_loss_weight
self._max_negatives_per_positive = max_negatives_per_positive
self._min_negatives_per_image = min_negatives_per_image
if self._max_negatives_per_positive is not None:
self._max_negatives_per_positive = float(self._max_negatives_per_positive)
self._num_positives_list = None
self._num_negatives_list = None | [
"def",
"__init__",
"(",
"self",
",",
"num_hard_examples",
"=",
"64",
",",
"iou_threshold",
"=",
"0.7",
",",
"loss_type",
"=",
"'both'",
",",
"cls_loss_weight",
"=",
"0.05",
",",
"loc_loss_weight",
"=",
"0.06",
",",
"max_negatives_per_positive",
"=",
"None",
",... | https://github.com/datitran/object_detector_app/blob/44e8eddeb931cced5d8cf1e283383c720a5706bf/object_detection/core/losses.py#L355-L407 | ||
paramiko/paramiko | 88f35a537428e430f7f26eee8026715e357b55d6 | paramiko/transport.py | python | Transport.open_x11_channel | (self, src_addr=None) | return self.open_channel("x11", src_addr=src_addr) | Request a new channel to the client, of type ``"x11"``. This
is just an alias for ``open_channel('x11', src_addr=src_addr)``.
:param tuple src_addr:
the source address (``(str, int)``) of the x11 server (port is the
x11 port, ie. 6010)
:return: a new `.Channel`
:raises:
`.SSHException` -- if the request is rejected or the session ends
prematurely | Request a new channel to the client, of type ``"x11"``. This
is just an alias for ``open_channel('x11', src_addr=src_addr)``. | [
"Request",
"a",
"new",
"channel",
"to",
"the",
"client",
"of",
"type",
"x11",
".",
"This",
"is",
"just",
"an",
"alias",
"for",
"open_channel",
"(",
"x11",
"src_addr",
"=",
"src_addr",
")",
"."
] | def open_x11_channel(self, src_addr=None):
"""
Request a new channel to the client, of type ``"x11"``. This
is just an alias for ``open_channel('x11', src_addr=src_addr)``.
:param tuple src_addr:
the source address (``(str, int)``) of the x11 server (port is the
x11 port, ie. 6010)
:return: a new `.Channel`
:raises:
`.SSHException` -- if the request is rejected or the session ends
prematurely
"""
return self.open_channel("x11", src_addr=src_addr) | [
"def",
"open_x11_channel",
"(",
"self",
",",
"src_addr",
"=",
"None",
")",
":",
"return",
"self",
".",
"open_channel",
"(",
"\"x11\"",
",",
"src_addr",
"=",
"src_addr",
")"
] | https://github.com/paramiko/paramiko/blob/88f35a537428e430f7f26eee8026715e357b55d6/paramiko/transport.py#L926-L940 | |
cortex-lab/phy | 9a330b9437a3d0b40a37a201d147224e6e7fb462 | phy/apps/base.py | python | BaseController._amplitude_getter | (self, cluster_ids, name=None, load_all=False) | return out | Return the data requested by the amplitude view, wich depends on the
type of amplitude.
Parameters
----------
cluster_ids : list
List of clusters.
name : str
Amplitude name, see `self._amplitude_functions`.
load_all : boolean
Whether to load all spikes from the requested clusters, or a subselection just
for display. | Return the data requested by the amplitude view, wich depends on the
type of amplitude. | [
"Return",
"the",
"data",
"requested",
"by",
"the",
"amplitude",
"view",
"wich",
"depends",
"on",
"the",
"type",
"of",
"amplitude",
"."
] | def _amplitude_getter(self, cluster_ids, name=None, load_all=False):
"""Return the data requested by the amplitude view, wich depends on the
type of amplitude.
Parameters
----------
cluster_ids : list
List of clusters.
name : str
Amplitude name, see `self._amplitude_functions`.
load_all : boolean
Whether to load all spikes from the requested clusters, or a subselection just
for display.
"""
out = []
n = self.n_spikes_amplitudes if not load_all else None
# Find the first cluster, used to determine the best channels.
first_cluster = next(cluster_id for cluster_id in cluster_ids if cluster_id is not None)
# Best channels of the first cluster.
channel_ids = self.get_best_channels(first_cluster)
# Best channel of the first cluster.
channel_id = channel_ids[0]
# All clusters appearing on the first cluster's peak channel.
other_clusters = self.get_clusters_on_channel(channel_id)
# Remove selected clusters from other_clusters to prevent them from being included
# in both the grey dots and grey histogram
other_clusters = [e for e in other_clusters if e not in cluster_ids]
# Get the amplitude method.
f = self._get_amplitude_functions()[name]
# Take spikes from the waveform selection if we're loading the raw amplitudes,
# or by minimzing the number of chunks to load if fetching waveforms directly
# from the raw data.
# Otherwise we load the spikes randomly from the whole dataset.
subset_chunks = subset_spikes = None
if name == 'raw':
if self.model.spike_waveforms is not None:
subset_spikes = self.model.spike_waveforms.spike_ids
else:
subset_chunks = True
# Go through each cluster in order to select spikes from each.
for cluster_id in cluster_ids:
if cluster_id is not None:
# Cluster spikes.
spike_ids = self.get_spike_ids(
cluster_id, n=n, subset_spikes=subset_spikes, subset_chunks=subset_chunks)
else:
# Background spikes.
spike_ids = self.selector(
n, other_clusters, subset_spikes=subset_spikes, subset_chunks=subset_chunks)
# Get the spike times.
spike_times = self._get_spike_times_reordered(spike_ids)
if name in ('feature', 'raw'):
# Retrieve the feature PC selected in the feature view
# or the channel selected in the waveform view.
channel_id = self.selection.get('channel_id', channel_id)
pc = self.selection.get('feature_pc', None)
# Call the spike amplitude getter function.
amplitudes = f(
spike_ids, channel_ids=channel_ids, channel_id=channel_id, pc=pc,
first_cluster=first_cluster)
if amplitudes is None:
continue
assert amplitudes.shape == spike_ids.shape == spike_times.shape
out.append(Bunch(
amplitudes=amplitudes,
spike_ids=spike_ids,
spike_times=spike_times,
))
return out | [
"def",
"_amplitude_getter",
"(",
"self",
",",
"cluster_ids",
",",
"name",
"=",
"None",
",",
"load_all",
"=",
"False",
")",
":",
"out",
"=",
"[",
"]",
"n",
"=",
"self",
".",
"n_spikes_amplitudes",
"if",
"not",
"load_all",
"else",
"None",
"# Find the first c... | https://github.com/cortex-lab/phy/blob/9a330b9437a3d0b40a37a201d147224e6e7fb462/phy/apps/base.py#L1290-L1359 | |
dropbox/stone | b7b64320631b3a4d2f10681dca64e0718ebe68ee | stone/ir/api.py | python | ApiNamespace.get_route_io_data_types | (self) | return sorted(data_types, key=lambda dt: dt.name) | Returns a list of all user-defined data types that are referenced as
either an argument, result, or error of a route. If a List or Nullable
data type is referenced, then the contained data type is returned
assuming it's a user-defined type. | Returns a list of all user-defined data types that are referenced as
either an argument, result, or error of a route. If a List or Nullable
data type is referenced, then the contained data type is returned
assuming it's a user-defined type. | [
"Returns",
"a",
"list",
"of",
"all",
"user",
"-",
"defined",
"data",
"types",
"that",
"are",
"referenced",
"as",
"either",
"an",
"argument",
"result",
"or",
"error",
"of",
"a",
"route",
".",
"If",
"a",
"List",
"or",
"Nullable",
"data",
"type",
"is",
"r... | def get_route_io_data_types(self):
# type: () -> typing.List[UserDefined]
"""
Returns a list of all user-defined data types that are referenced as
either an argument, result, or error of a route. If a List or Nullable
data type is referenced, then the contained data type is returned
assuming it's a user-defined type.
"""
data_types = set() # type: typing.Set[UserDefined]
for route in self.routes:
data_types |= self.get_route_io_data_types_for_route(route)
return sorted(data_types, key=lambda dt: dt.name) | [
"def",
"get_route_io_data_types",
"(",
"self",
")",
":",
"# type: () -> typing.List[UserDefined]",
"data_types",
"=",
"set",
"(",
")",
"# type: typing.Set[UserDefined]",
"for",
"route",
"in",
"self",
".",
"routes",
":",
"data_types",
"|=",
"self",
".",
"get_route_io_d... | https://github.com/dropbox/stone/blob/b7b64320631b3a4d2f10681dca64e0718ebe68ee/stone/ir/api.py#L257-L268 | |
sabnzbd/sabnzbd | 52d21e94d3cc6e30764a833fe2a256783d1a8931 | sabnzbd/lang.py | python | set_locale_info | (domain, localedir) | Setup the domain and localedir for translations | Setup the domain and localedir for translations | [
"Setup",
"the",
"domain",
"and",
"localedir",
"for",
"translations"
] | def set_locale_info(domain, localedir):
"""Setup the domain and localedir for translations"""
global _DOMAIN, _LOCALEDIR
_DOMAIN = domain
_LOCALEDIR = localedir | [
"def",
"set_locale_info",
"(",
"domain",
",",
"localedir",
")",
":",
"global",
"_DOMAIN",
",",
"_LOCALEDIR",
"_DOMAIN",
"=",
"domain",
"_LOCALEDIR",
"=",
"localedir"
] | https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/lang.py#L47-L51 | ||
spyder-ide/spyder | 55da47c032dfcf519600f67f8b30eab467f965e7 | spyder/widgets/mixins.py | python | BaseEditMixin.move_cursor | (self, chars=0) | Move cursor to left or right (unit: characters) | Move cursor to left or right (unit: characters) | [
"Move",
"cursor",
"to",
"left",
"or",
"right",
"(",
"unit",
":",
"characters",
")"
] | def move_cursor(self, chars=0):
"""Move cursor to left or right (unit: characters)"""
direction = QTextCursor.Right if chars > 0 else QTextCursor.Left
for _i in range(abs(chars)):
self.moveCursor(direction, QTextCursor.MoveAnchor) | [
"def",
"move_cursor",
"(",
"self",
",",
"chars",
"=",
"0",
")",
":",
"direction",
"=",
"QTextCursor",
".",
"Right",
"if",
"chars",
">",
"0",
"else",
"QTextCursor",
".",
"Left",
"for",
"_i",
"in",
"range",
"(",
"abs",
"(",
"chars",
")",
")",
":",
"s... | https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/widgets/mixins.py#L823-L827 | ||
Juniper/py-junos-eznc | fd81d476e37ac1a234b503ab77f76ec658d04590 | lib/jnpr/junos/facts/is_linux.py | python | get_facts | (device) | return {
"_is_linux": is_linux,
} | Gathers the _is_linux fact using the <file-show/> RPC on the EVO version file. | Gathers the _is_linux fact using the <file-show/> RPC on the EVO version file. | [
"Gathers",
"the",
"_is_linux",
"fact",
"using",
"the",
"<file",
"-",
"show",
"/",
">",
"RPC",
"on",
"the",
"EVO",
"version",
"file",
"."
] | def get_facts(device):
"""
Gathers the _is_linux fact using the <file-show/> RPC on the EVO version file.
"""
# Temporary implementation until PR 1245634 is implemented.
LINUX_VERSION_PATH = "/usr/share/cevo/cevo_version"
is_linux = None
try:
rsp = device.rpc.file_show(normalize=True, filename=LINUX_VERSION_PATH)
if rsp.tag == "file-content":
is_linux = True
else:
is_linux = False
except RpcError:
is_linux = False
return {
"_is_linux": is_linux,
} | [
"def",
"get_facts",
"(",
"device",
")",
":",
"# Temporary implementation until PR 1245634 is implemented.",
"LINUX_VERSION_PATH",
"=",
"\"/usr/share/cevo/cevo_version\"",
"is_linux",
"=",
"None",
"try",
":",
"rsp",
"=",
"device",
".",
"rpc",
".",
"file_show",
"(",
"norm... | https://github.com/Juniper/py-junos-eznc/blob/fd81d476e37ac1a234b503ab77f76ec658d04590/lib/jnpr/junos/facts/is_linux.py#L14-L34 | |
awslabs/sockeye | ec2d13f7beb42d8c4f389dba0172250dc9154d5a | sockeye/model_pt.py | python | initialize_parameters | (module: pt.nn.Module) | Can be applied to a SockeyeModel (via `model.apply(initialize_parameters)`)
to initialize the parameters of a PyTorch SockeyeModel.
For reproducibility, set pt.random.manual_seed.
This implementation follows the default MXNet initialization scheme:
- linear/feed-forward weights: Xavier(uniform, avg, magnitude=3.0)
- biases: 0.0
- layer norm gamma / weight: 1.0
- layer norm beta / bias: 0.0
- embedding parameters: uniform(-0.07, 0.07) [matches MXNet's default initialization]
MXNet computes the uniform bounds for Xavier initialization as follows:
sqrt(3 / ((fan_in + fan_out) / 2))
PyTorch computes the uniform bounds for Xavier initialization as follows:
(sqrt(2/(fan_in + fan_out)) * gain) * sqrt(3)
where gain is set to 1.0 by default
Both are equivalent.
For some background on the equivalence of mx.init.Xavier and pt.nn.init.xavier_uniform_, see
https: // jamesmccaffrey.wordpress.com / 2020 / 11 / 20 / the - gain - parameter - | Can be applied to a SockeyeModel (via `model.apply(initialize_parameters)`)
to initialize the parameters of a PyTorch SockeyeModel.
For reproducibility, set pt.random.manual_seed. | [
"Can",
"be",
"applied",
"to",
"a",
"SockeyeModel",
"(",
"via",
"model",
".",
"apply",
"(",
"initialize_parameters",
")",
")",
"to",
"initialize",
"the",
"parameters",
"of",
"a",
"PyTorch",
"SockeyeModel",
".",
"For",
"reproducibility",
"set",
"pt",
".",
"ran... | def initialize_parameters(module: pt.nn.Module):
"""
Can be applied to a SockeyeModel (via `model.apply(initialize_parameters)`)
to initialize the parameters of a PyTorch SockeyeModel.
For reproducibility, set pt.random.manual_seed.
This implementation follows the default MXNet initialization scheme:
- linear/feed-forward weights: Xavier(uniform, avg, magnitude=3.0)
- biases: 0.0
- layer norm gamma / weight: 1.0
- layer norm beta / bias: 0.0
- embedding parameters: uniform(-0.07, 0.07) [matches MXNet's default initialization]
MXNet computes the uniform bounds for Xavier initialization as follows:
sqrt(3 / ((fan_in + fan_out) / 2))
PyTorch computes the uniform bounds for Xavier initialization as follows:
(sqrt(2/(fan_in + fan_out)) * gain) * sqrt(3)
where gain is set to 1.0 by default
Both are equivalent.
For some background on the equivalence of mx.init.Xavier and pt.nn.init.xavier_uniform_, see
https: // jamesmccaffrey.wordpress.com / 2020 / 11 / 20 / the - gain - parameter -
"""
import math
if isinstance(module, pt.nn.Linear) or isinstance(module, layers_pt.PyTorchOutputLayer):
# TODO: consider using gain=1 / math.sqrt(2)
pt.nn.init.xavier_uniform_(module.weight, gain=1)
if module.bias is not None:
pt.nn.init.zeros_(module.bias)
elif isinstance(module, pt.nn.Embedding):
pt.nn.init.uniform_(module.weight, -0.07, 0.07)
elif isinstance(module, pt.nn.LayerNorm):
if module.elementwise_affine:
pt.nn.init.ones_(module.weight)
pt.nn.init.zeros_(module.bias)
elif isinstance(module, layers_pt.PyTorchLHUC):
pt.nn.init.uniform_(module.weight, a=0.1)
elif isinstance(module, layers_pt.PyTorchPositionalEmbeddings):
if module.weight_type == C.LEARNED_POSITIONAL_EMBEDDING:
pt.nn.init.xavier_uniform(module.weight, gain=1.0) | [
"def",
"initialize_parameters",
"(",
"module",
":",
"pt",
".",
"nn",
".",
"Module",
")",
":",
"import",
"math",
"if",
"isinstance",
"(",
"module",
",",
"pt",
".",
"nn",
".",
"Linear",
")",
"or",
"isinstance",
"(",
"module",
",",
"layers_pt",
".",
"PyTo... | https://github.com/awslabs/sockeye/blob/ec2d13f7beb42d8c4f389dba0172250dc9154d5a/sockeye/model_pt.py#L561-L599 | ||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | bin/x86/Debug/scripting_engine/Lib/logging/__init__.py | python | critical | (msg, *args, **kwargs) | Log a message with severity 'CRITICAL' on the root logger. | Log a message with severity 'CRITICAL' on the root logger. | [
"Log",
"a",
"message",
"with",
"severity",
"CRITICAL",
"on",
"the",
"root",
"logger",
"."
] | def critical(msg, *args, **kwargs):
"""
Log a message with severity 'CRITICAL' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
root.critical(msg, *args, **kwargs) | [
"def",
"critical",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"root",
".",
"handlers",
")",
"==",
"0",
":",
"basicConfig",
"(",
")",
"root",
".",
"critical",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
... | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/logging/__init__.py#L1551-L1557 | ||
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-modules/twisted/twisted/words/protocols/irc.py | python | ServerSupportedFeatures.isupport_SAFELIST | (self, params) | return True | Flag indicating that a client may request a LIST without being
disconnected due to the large amount of data generated. | Flag indicating that a client may request a LIST without being
disconnected due to the large amount of data generated. | [
"Flag",
"indicating",
"that",
"a",
"client",
"may",
"request",
"a",
"LIST",
"without",
"being",
"disconnected",
"due",
"to",
"the",
"large",
"amount",
"of",
"data",
"generated",
"."
] | def isupport_SAFELIST(self, params):
"""
Flag indicating that a client may request a LIST without being
disconnected due to the large amount of data generated.
"""
return True | [
"def",
"isupport_SAFELIST",
"(",
"self",
",",
"params",
")",
":",
"return",
"True"
] | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/words/protocols/irc.py#L938-L943 | |
PySimpleGUI/PySimpleGUI | 6c0d1fb54f493d45e90180b322fbbe70f7a5af3c | PySimpleGUIQt/PySimpleGUIQt.py | python | AddToReturnDictionary | (form, element, value) | return | [] | def AddToReturnDictionary(form, element, value):
form.ReturnValuesDictionary[element.Key] = value
return
if element.Key is None:
form.ReturnValuesDictionary[form.DictionaryKeyCounter] = value
element.Key = form.DictionaryKeyCounter
form.DictionaryKeyCounter += 1
else:
form.ReturnValuesDictionary[element.Key] = value | [
"def",
"AddToReturnDictionary",
"(",
"form",
",",
"element",
",",
"value",
")",
":",
"form",
".",
"ReturnValuesDictionary",
"[",
"element",
".",
"Key",
"]",
"=",
"value",
"return",
"if",
"element",
".",
"Key",
"is",
"None",
":",
"form",
".",
"ReturnValuesD... | https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/PySimpleGUIQt/PySimpleGUIQt.py#L5476-L5484 | |||
omaha-consulting/omaha-server | 1aa507b51e3656b490f72a3c9d60ee9d085e389e | omaha_server/omaha/statistics.py | python | get_users_versions | (app_id, date=None) | return data | [] | def get_users_versions(app_id, date=None):
if not date:
date = timezone.now()
platforms = Platform.objects.values_list('name', flat=True)
data = dict() # try to move it in the separate function
for platform in platforms:
platform_data = get_users_versions_by_platform(app_id, platform, date)
data.update({platform: platform_data})
return data | [
"def",
"get_users_versions",
"(",
"app_id",
",",
"date",
"=",
"None",
")",
":",
"if",
"not",
"date",
":",
"date",
"=",
"timezone",
".",
"now",
"(",
")",
"platforms",
"=",
"Platform",
".",
"objects",
".",
"values_list",
"(",
"'name'",
",",
"flat",
"=",
... | https://github.com/omaha-consulting/omaha-server/blob/1aa507b51e3656b490f72a3c9d60ee9d085e389e/omaha_server/omaha/statistics.py#L184-L194 | |||
cantools/cantools | 8d86d61bc010f328cf414150331fecfd4b6f4dc3 | cantools/database/can/signal.py | python | Signal.scale | (self) | return self._scale | The scale factor of the signal value. | The scale factor of the signal value. | [
"The",
"scale",
"factor",
"of",
"the",
"signal",
"value",
"."
] | def scale(self) -> float:
"""The scale factor of the signal value.
"""
return self._scale | [
"def",
"scale",
"(",
"self",
")",
"->",
"float",
":",
"return",
"self",
".",
"_scale"
] | https://github.com/cantools/cantools/blob/8d86d61bc010f328cf414150331fecfd4b6f4dc3/cantools/database/can/signal.py#L348-L353 | |
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/templates/historic/RLPPTM/dcc.py | python | DCC.from_result | (cls, test_id, result_id, first_name, last_name, dob) | return instance | Create a DCC instance from a test result
@param test_id: the identifier under which the result has been
reported to CWA (report to CWA is mandatory for DCC)
@param result_id: case diagnostics record ID
@param first_name: the first name to use in the DCC
@param last_name: the last name to use in the DCC
@param dob: the date of birth to use in the DCC (date instance or ISO-formatted)
@returns: DCC instance
@raises: ValueError if the data are invalid | Create a DCC instance from a test result | [
"Create",
"a",
"DCC",
"instance",
"from",
"a",
"test",
"result"
] | def from_result(cls, test_id, result_id, first_name, last_name, dob):
"""
Create a DCC instance from a test result
@param test_id: the identifier under which the result has been
reported to CWA (report to CWA is mandatory for DCC)
@param result_id: case diagnostics record ID
@param first_name: the first name to use in the DCC
@param last_name: the last name to use in the DCC
@param dob: the date of birth to use in the DCC (date instance or ISO-formatted)
@returns: DCC instance
@raises: ValueError if the data are invalid
"""
# Generate instance ID (=hash of the test ID)
if not isinstance(test_id, str) or not test_id:
raise ValueError("Test ID is required")
instance_id = hashlib.sha256(test_id.encode("utf-8")).hexdigest().lower()
# Template for error messages
error = lambda msg: current.T("Cannot certify result [%(reason)s]") % {"reason": msg}
# Check person data are complete
if not all((first_name, last_name, dob)):
raise ValueError(error("incomplete person data"))
try:
cls.format_name(first_name)
cls.format_name(last_name)
except ValueError:
raise ValueError(error("invalid name"))
# Lookup probe date, result, name of test station, and device code
s3db = current.s3db
rtable = s3db.disease_case_diagnostics
dtable = s3db.disease_testing_device
ftable = s3db.org_facility
left = [ftable.on((ftable.site_id == rtable.site_id) & \
(ftable.deleted == False)),
dtable.on((dtable.id == rtable.device_id) & \
(dtable.deleted == False)),
]
query = (rtable.id == result_id) & \
(rtable.deleted == False)
row = current.db(query).select(rtable.id,
rtable.disease_id,
rtable.result,
rtable.probe_date,
ftable.site_id,
dtable.id,
dtable.code,
left = left,
limitby = (0, 1),
).first()
if not row:
raise ValueError(error("result record not found"))
# Make sure result is conclusive
result = row.disease_case_diagnostics
if result.result not in ("POS", "NEG"):
raise ValueError(error("inconclusive result"))
# Make sure the test facility is valid
facility = row.org_facility
issuer_id = cls.get_issuer_id(facility.site_id)
if not issuer_id:
raise ValueError(error("invalid test facility"))
# If we have no previous DCC with this issuer_id:
# - try to register the the issuer_id
if cls.is_new_issuer(issuer_id):
if not cls.register_issuer(issuer_id):
raise ValueError(error("issuer ID could not be registered"))
# Make sure the test device is known
device = row.disease_testing_device
if not device.id or not device.code:
raise ValueError(error("testing device unknown"))
# Determine probe data and thence, expiry date
probe_date = result.probe_date
expires = probe_date + datetime.timedelta(hours=48)
#if expires < datetime.datetime.utcnow():
# raise ValueError(error("result has expired"))
# Create the instance and fill with data
instance = cls(instance_id)
instance.status = "PENDING"
instance.issuer_id = issuer_id
instance.data = {"fn": first_name,
"ln": last_name,
"dob": dob.isoformat() if isinstance(dob, datetime.date) else dob,
"disease": result.disease_id,
"site": facility.site_id,
"device": device.code,
"timestamp": int(probe_date.replace(microsecond=0).timestamp()),
"expires": int(expires.replace(microsecond=0).timestamp()),
"result": result.result,
}
return instance | [
"def",
"from_result",
"(",
"cls",
",",
"test_id",
",",
"result_id",
",",
"first_name",
",",
"last_name",
",",
"dob",
")",
":",
"# Generate instance ID (=hash of the test ID)",
"if",
"not",
"isinstance",
"(",
"test_id",
",",
"str",
")",
"or",
"not",
"test_id",
... | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/templates/historic/RLPPTM/dcc.py#L102-L206 | |
linuxlewis/channels-api | ec2a81a1ae83606980ad5bb709bca517fdde077d | channels_api/mixins.py | python | PatchModelMixin.patch | (self, pk, data, **kwargs) | return serializer.data, 200 | [] | def patch(self, pk, data, **kwargs):
instance = self.get_object_or_404(pk)
serializer = self.get_serializer(instance, data=data, partial=True)
serializer.is_valid(raise_exception=True)
self.perform_patch(serializer)
return serializer.data, 200 | [
"def",
"patch",
"(",
"self",
",",
"pk",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"self",
".",
"get_object_or_404",
"(",
"pk",
")",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
"instance",
",",
"data",
"=",
"data",
",... | https://github.com/linuxlewis/channels-api/blob/ec2a81a1ae83606980ad5bb709bca517fdde077d/channels_api/mixins.py#L59-L64 | |||
007gzs/dingtalk-sdk | 7979da2e259fdbc571728cae2425a04dbc65850a | dingtalk/client/api/taobao.py | python | TbALiJianKang.alibaba_alihealth_ms_area_province_list | (
self
) | return self._top_request(
"alibaba.alihealth.ms.area.province.list"
) | 疫苗预约省份列表查询
微信小程序疫苗预约省份列表查询
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37697 | 疫苗预约省份列表查询
微信小程序疫苗预约省份列表查询
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37697 | [
"疫苗预约省份列表查询",
"微信小程序疫苗预约省份列表查询",
"文档地址:https",
":",
"//",
"open",
"-",
"doc",
".",
"dingtalk",
".",
"com",
"/",
"docs",
"/",
"api",
".",
"htm?apiId",
"=",
"37697"
] | def alibaba_alihealth_ms_area_province_list(
self
):
"""
疫苗预约省份列表查询
微信小程序疫苗预约省份列表查询
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37697
"""
return self._top_request(
"alibaba.alihealth.ms.area.province.list"
) | [
"def",
"alibaba_alihealth_ms_area_province_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"_top_request",
"(",
"\"alibaba.alihealth.ms.area.province.list\"",
")"
] | https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L103982-L103993 | |
JacquesLucke/animation_nodes | b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1 | animation_nodes/utils/timing.py | python | prettyTime | (seconds) | [] | def prettyTime(seconds):
if seconds > 1.5: return "{:.2f} s".format(seconds)
else: return "{:.4f} ms".format(seconds * 1000) | [
"def",
"prettyTime",
"(",
"seconds",
")",
":",
"if",
"seconds",
">",
"1.5",
":",
"return",
"\"{:.2f} s\"",
".",
"format",
"(",
"seconds",
")",
"else",
":",
"return",
"\"{:.4f} ms\"",
".",
"format",
"(",
"seconds",
"*",
"1000",
")"
] | https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/utils/timing.py#L5-L7 | ||||
aleju/imgaug | 0101108d4fed06bc5056c4a03e2bcb0216dac326 | imgaug/random.py | python | generate_seeds_ | (generator, n) | return polyfill_integers(generator, SEED_MIN_VALUE, SEED_MAX_VALUE,
size=(n,)) | Sample `n` seeds from the provided generator.
This function advances the generator's state.
Parameters
----------
generator : numpy.random.Generator or numpy.random.RandomState
The generator from which to sample the seed.
n : int
Number of seeds to sample.
Returns
-------
ndarray
1D-array of ``int32`` seeds. | Sample `n` seeds from the provided generator. | [
"Sample",
"n",
"seeds",
"from",
"the",
"provided",
"generator",
"."
] | def generate_seeds_(generator, n):
"""Sample `n` seeds from the provided generator.
This function advances the generator's state.
Parameters
----------
generator : numpy.random.Generator or numpy.random.RandomState
The generator from which to sample the seed.
n : int
Number of seeds to sample.
Returns
-------
ndarray
1D-array of ``int32`` seeds.
"""
return polyfill_integers(generator, SEED_MIN_VALUE, SEED_MAX_VALUE,
size=(n,)) | [
"def",
"generate_seeds_",
"(",
"generator",
",",
"n",
")",
":",
"return",
"polyfill_integers",
"(",
"generator",
",",
"SEED_MIN_VALUE",
",",
"SEED_MAX_VALUE",
",",
"size",
"=",
"(",
"n",
",",
")",
")"
] | https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/random.py#L1155-L1175 | |
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/xml/dom/minidom.py | python | Document.isSupported | (self, feature, version) | return self.implementation.hasFeature(feature, version) | [] | def isSupported(self, feature, version):
return self.implementation.hasFeature(feature, version) | [
"def",
"isSupported",
"(",
"self",
",",
"feature",
",",
"version",
")",
":",
"return",
"self",
".",
"implementation",
".",
"hasFeature",
"(",
"feature",
",",
"version",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/xml/dom/minidom.py#L1781-L1782 | |||
fastai/imagenet-fast | faa0f9dfc9e8e058ffd07a248724bf384f526fae | imagenet_nv/models/resnext.py | python | resnext34 | (**kwargs) | return model | Constructs a ResNeXt-34 model. | Constructs a ResNeXt-34 model. | [
"Constructs",
"a",
"ResNeXt",
"-",
"34",
"model",
"."
] | def resnext34(**kwargs):
"""Constructs a ResNeXt-34 model.
"""
model = ResNeXt(BasicBlock, [3, 4, 6, 3], **kwargs)
return model | [
"def",
"resnext34",
"(",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"ResNeXt",
"(",
"BasicBlock",
",",
"[",
"3",
",",
"4",
",",
"6",
",",
"3",
"]",
",",
"*",
"*",
"kwargs",
")",
"return",
"model"
] | https://github.com/fastai/imagenet-fast/blob/faa0f9dfc9e8e058ffd07a248724bf384f526fae/imagenet_nv/models/resnext.py#L158-L162 | |
marcoeilers/nagini | a2a19df7d833e67841e03c9885869c3dddef3327 | src/nagini_translation/translators/obligation/loop_node.py | python | ObligationLoopNodeConstructor._add_leak_check | (self) | Add leak checks to invariant. | Add leak checks to invariant. | [
"Add",
"leak",
"checks",
"to",
"invariant",
"."
] | def _add_leak_check(self) -> None:
"""Add leak checks to invariant."""
reference_name = self._ctx.actual_function.get_fresh_name('_r')
leak_check = self._obligation_manager.create_leak_check(reference_name)
loop_check_before = sil.BoolVar(
self._loop_obligation_info.loop_check_before_var)
termination_flag = sil.BoolVar(
self._loop_obligation_info.termination_flag_var)
if not obligation_config.disable_loop_context_leak_check:
must_terminate = self._obligation_manager.must_terminate_obligation
predicate = must_terminate.create_predicate_access(
self._obligation_info.current_thread_var)
termination_leak_check = sil.CurrentPerm(predicate) == sil.NoPerm()
loop_cond = self._loop_obligation_info.construct_loop_condition()
before_loop_leak_check = sil.InhaleExhale(
sil.TrueLit(),
sil.Implies(
loop_check_before,
sil.BigOr([
termination_flag,
sil.Not(loop_cond),
sil.BigAnd([termination_leak_check, leak_check])
])
)
)
info = self._to_info('Leak check for context.')
position = self._to_position(
conversion_rules=rules.OBLIGATION_LOOP_CONTEXT_LEAK_CHECK_FAIL)
self._obligation_loop.append_invariants([
before_loop_leak_check.translate(
self._translator, self._ctx, position, info)])
if not obligation_config.disable_loop_body_leak_check:
body_leak_check = sil.InhaleExhale(
sil.TrueLit(),
sil.Implies(sil.Not(loop_check_before), leak_check))
info = self._to_info('Leak check for loop body.')
position = self._to_position(
conversion_rules=rules.OBLIGATION_LOOP_BODY_LEAK_CHECK_FAIL)
self._obligation_loop.append_invariants([
body_leak_check.translate(
self._translator, self._ctx, position, info)]) | [
"def",
"_add_leak_check",
"(",
"self",
")",
"->",
"None",
":",
"reference_name",
"=",
"self",
".",
"_ctx",
".",
"actual_function",
".",
"get_fresh_name",
"(",
"'_r'",
")",
"leak_check",
"=",
"self",
".",
"_obligation_manager",
".",
"create_leak_check",
"(",
"r... | https://github.com/marcoeilers/nagini/blob/a2a19df7d833e67841e03c9885869c3dddef3327/src/nagini_translation/translators/obligation/loop_node.py#L127-L169 | ||
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/swift/swift/obj/expirer.py | python | ObjectExpirer.delete_actual_object | (self, actual_obj, timestamp) | Deletes the end-user object indicated by the actual object name given
'<account>/<container>/<object>' if and only if the X-Delete-At value
of the object is exactly the timestamp given.
:param actual_obj: The name of the end-user object to delete:
'<account>/<container>/<object>'
:param timestamp: The timestamp the X-Delete-At value must match to
perform the actual delete. | Deletes the end-user object indicated by the actual object name given
'<account>/<container>/<object>' if and only if the X-Delete-At value
of the object is exactly the timestamp given. | [
"Deletes",
"the",
"end",
"-",
"user",
"object",
"indicated",
"by",
"the",
"actual",
"object",
"name",
"given",
"<account",
">",
"/",
"<container",
">",
"/",
"<object",
">",
"if",
"and",
"only",
"if",
"the",
"X",
"-",
"Delete",
"-",
"At",
"value",
"of",... | def delete_actual_object(self, actual_obj, timestamp):
"""
Deletes the end-user object indicated by the actual object name given
'<account>/<container>/<object>' if and only if the X-Delete-At value
of the object is exactly the timestamp given.
:param actual_obj: The name of the end-user object to delete:
'<account>/<container>/<object>'
:param timestamp: The timestamp the X-Delete-At value must match to
perform the actual delete.
"""
self.swift.make_request('DELETE', '/v1/%s' % actual_obj.lstrip('/'),
{'X-If-Delete-At': str(timestamp)},
(2, HTTP_NOT_FOUND, HTTP_PRECONDITION_FAILED)) | [
"def",
"delete_actual_object",
"(",
"self",
",",
"actual_obj",
",",
"timestamp",
")",
":",
"self",
".",
"swift",
".",
"make_request",
"(",
"'DELETE'",
",",
"'/v1/%s'",
"%",
"actual_obj",
".",
"lstrip",
"(",
"'/'",
")",
",",
"{",
"'X-If-Delete-At'",
":",
"s... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/swift/swift/obj/expirer.py#L154-L167 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/six.py | python | add_metaclass | (metaclass) | return wrapper | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | [
"Class",
"decorator",
"for",
"creating",
"a",
"class",
"with",
"a",
"metaclass",
"."
] | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
if hasattr(cls, '__qualname__'):
orig_vars['__qualname__'] = cls.__qualname__
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/six.py#L880-L895 | |
kkroening/ffmpeg-python | f3079726fae7b7b71e4175f79c5eeaddc1d205fb | ffmpeg/_filters.py | python | colorchannelmixer | (stream, *args, **kwargs) | return FilterNode(stream, colorchannelmixer.__name__, kwargs=kwargs).stream() | Adjust video input frames by re-mixing color channels.
Official documentation: `colorchannelmixer <https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer>`__ | Adjust video input frames by re-mixing color channels. | [
"Adjust",
"video",
"input",
"frames",
"by",
"re",
"-",
"mixing",
"color",
"channels",
"."
] | def colorchannelmixer(stream, *args, **kwargs):
"""Adjust video input frames by re-mixing color channels.
Official documentation: `colorchannelmixer <https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer>`__
"""
return FilterNode(stream, colorchannelmixer.__name__, kwargs=kwargs).stream() | [
"def",
"colorchannelmixer",
"(",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FilterNode",
"(",
"stream",
",",
"colorchannelmixer",
".",
"__name__",
",",
"kwargs",
"=",
"kwargs",
")",
".",
"stream",
"(",
")"
] | https://github.com/kkroening/ffmpeg-python/blob/f3079726fae7b7b71e4175f79c5eeaddc1d205fb/ffmpeg/_filters.py#L437-L442 | |
haiwen/seahub | e92fcd44e3e46260597d8faa9347cb8222b8b10d | tools/batch-delete.py | python | check_settings | () | [] | def check_settings():
if settings.DATABASE_ENGINE == 'mysql':
sys.stderr.write('[ERROR] Current settings is mysql, need sqlite settings\n')
sys.exit(1) | [
"def",
"check_settings",
"(",
")",
":",
"if",
"settings",
".",
"DATABASE_ENGINE",
"==",
"'mysql'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'[ERROR] Current settings is mysql, need sqlite settings\\n'",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/tools/batch-delete.py#L19-L22 | ||||
karanchahal/distiller | a17ec06cbeafcdd2aea19d7c7663033c951392f5 | models/vision/googlenet.py | python | BasicConv2d.__init__ | (self, in_channels, out_channels, **kwargs) | [] | def __init__(self, in_channels, out_channels, **kwargs):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)
self.bn = nn.BatchNorm2d(out_channels, eps=0.001) | [
"def",
"__init__",
"(",
"self",
",",
"in_channels",
",",
"out_channels",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"BasicConv2d",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"conv",
"=",
"nn",
".",
"Conv2d",
"(",
"in_channels",
"... | https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/models/vision/googlenet.py#L280-L283 | ||||
twisted/twisted | dee676b040dd38b847ea6fb112a712cb5e119490 | src/twisted/trial/runner.py | python | ErrorHolder.__init__ | (self, description, error) | @param description: A string used by C{TestResult}s to identify this
error. Generally, this is the name of a module that failed to import.
@param error: The error to be added to the result. Can be an `exc_info`
tuple or a L{twisted.python.failure.Failure}. | @param description: A string used by C{TestResult}s to identify this
error. Generally, this is the name of a module that failed to import. | [
"@param",
"description",
":",
"A",
"string",
"used",
"by",
"C",
"{",
"TestResult",
"}",
"s",
"to",
"identify",
"this",
"error",
".",
"Generally",
"this",
"is",
"the",
"name",
"of",
"a",
"module",
"that",
"failed",
"to",
"import",
"."
] | def __init__(self, description, error):
"""
@param description: A string used by C{TestResult}s to identify this
error. Generally, this is the name of a module that failed to import.
@param error: The error to be added to the result. Can be an `exc_info`
tuple or a L{twisted.python.failure.Failure}.
"""
super().__init__(description)
self.error = util.excInfoOrFailureToExcInfo(error) | [
"def",
"__init__",
"(",
"self",
",",
"description",
",",
"error",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"description",
")",
"self",
".",
"error",
"=",
"util",
".",
"excInfoOrFailureToExcInfo",
"(",
"error",
")"
] | https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/trial/runner.py#L338-L347 | ||
nvaccess/nvda | 20d5a25dced4da34338197f0ef6546270ebca5d0 | source/COMRegistrationFixes/__init__.py | python | fixCOMRegistrations | () | Registers most common COM proxies, in case they have accidentally been unregistered or overwritten by
3rd party software installs or uninstalls. | Registers most common COM proxies, in case they have accidentally been unregistered or overwritten by
3rd party software installs or uninstalls. | [
"Registers",
"most",
"common",
"COM",
"proxies",
"in",
"case",
"they",
"have",
"accidentally",
"been",
"unregistered",
"or",
"overwritten",
"by",
"3rd",
"party",
"software",
"installs",
"or",
"uninstalls",
"."
] | def fixCOMRegistrations():
"""Registers most common COM proxies, in case they have accidentally been unregistered or overwritten by
3rd party software installs or uninstalls.
"""
is64bit = os.environ.get("PROCESSOR_ARCHITEW6432", "").endswith("64")
winVer = winVersion.getWinVer()
OSMajorMinor = (winVer.major, winVer.minor)
log.debug(
f"Fixing COM registrations for Windows {OSMajorMinor[0]}.{OSMajorMinor[1]}, "
"{} bit.".format("64" if is64bit else "32")
)
# OLEACC (MSAA) proxies
apply32bitRegistryPatch(OLEACC_REG_FILE_PATH)
if is64bit:
apply64bitRegistryPatch(OLEACC_REG_FILE_PATH)
# IDispatch and other common OLE interfaces
register32bitServer(os.path.join(SYSTEM32, "oleaut32.dll"))
register32bitServer(os.path.join(SYSTEM32, "actxprxy.dll"))
if is64bit:
register64bitServer(os.path.join(SYSTEM32, "oleaut32.dll"))
register64bitServer(os.path.join(SYSTEM32, "actxprxy.dll"))
# IServiceProvider on windows 7 can become unregistered
if OSMajorMinor == (6, 1): # Windows 7
# There was no "Program Files (x86)" in Windows 7 32-bit, so we cover both cases
register32bitServer(os.path.join(
PROGRAM_FILES_X86 if is64bit else PROGRAM_FILES,
"Internet Explorer", "ieproxy.dll"
))
if is64bit:
register64bitServer(os.path.join(PROGRAM_FILES, "Internet Explorer", "ieproxy.dll")) | [
"def",
"fixCOMRegistrations",
"(",
")",
":",
"is64bit",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PROCESSOR_ARCHITEW6432\"",
",",
"\"\"",
")",
".",
"endswith",
"(",
"\"64\"",
")",
"winVer",
"=",
"winVersion",
".",
"getWinVer",
"(",
")",
"OSMajorMinor",
... | https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/COMRegistrationFixes/__init__.py#L113-L142 | ||
WerWolv/EdiZon_CheatsConfigsAndScripts | d16d36c7509c01dca770f402babd83ff2e9ae6e7 | Scripts/lib/python3.5/ipaddress.py | python | _IPAddressBase.reverse_pointer | (self) | return self._reverse_pointer() | The name of the reverse DNS pointer for the IP address, e.g.:
>>> ipaddress.ip_address("127.0.0.1").reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> ipaddress.ip_address("2001:db8::1").reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' | The name of the reverse DNS pointer for the IP address, e.g.:
>>> ipaddress.ip_address("127.0.0.1").reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> ipaddress.ip_address("2001:db8::1").reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' | [
"The",
"name",
"of",
"the",
"reverse",
"DNS",
"pointer",
"for",
"the",
"IP",
"address",
"e",
".",
"g",
".",
":",
">>>",
"ipaddress",
".",
"ip_address",
"(",
"127",
".",
"0",
".",
"0",
".",
"1",
")",
".",
"reverse_pointer",
"1",
".",
"0",
".",
"0"... | def reverse_pointer(self):
"""The name of the reverse DNS pointer for the IP address, e.g.:
>>> ipaddress.ip_address("127.0.0.1").reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> ipaddress.ip_address("2001:db8::1").reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
"""
return self._reverse_pointer() | [
"def",
"reverse_pointer",
"(",
"self",
")",
":",
"return",
"self",
".",
"_reverse_pointer",
"(",
")"
] | https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/ipaddress.py#L402-L410 | |
PokemonGoF/PokemonGo-Bot-Desktop | 4bfa94f0183406c6a86f93645eff7abd3ad4ced8 | build/pywin/Lib/cookielib.py | python | is_HDN | (text) | return True | Return True if text is a host domain name. | Return True if text is a host domain name. | [
"Return",
"True",
"if",
"text",
"is",
"a",
"host",
"domain",
"name",
"."
] | def is_HDN(text):
"""Return True if text is a host domain name."""
# XXX
# This may well be wrong. Which RFC is HDN defined in, if any (for
# the purposes of RFC 2965)?
# For the current implementation, what about IPv6? Remember to look
# at other uses of IPV4_RE also, if change this.
if IPV4_RE.search(text):
return False
if text == "":
return False
if text[0] == "." or text[-1] == ".":
return False
return True | [
"def",
"is_HDN",
"(",
"text",
")",
":",
"# XXX",
"# This may well be wrong. Which RFC is HDN defined in, if any (for",
"# the purposes of RFC 2965)?",
"# For the current implementation, what about IPv6? Remember to look",
"# at other uses of IPV4_RE also, if change this.",
"if",
"IPV4_RE... | https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/cookielib.py#L513-L526 | |
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python3-alpha/python-libs/gdata/apps/organization/service.py | python | OrganizationService.UpdateOrgUser | (self, customer_id, user_email, org_unit_path) | return self._PutProperties(uri, properties) | Update the OrgUnit of a OrgUser.
Args:
customer_id: The ID of the Google Apps customer.
user_email: The email address of the user.
org_unit_path: The new organization's full path name.
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
Returns:
A dict containing the result of the update operation. | Update the OrgUnit of a OrgUser. | [
"Update",
"the",
"OrgUnit",
"of",
"a",
"OrgUser",
"."
] | def UpdateOrgUser(self, customer_id, user_email, org_unit_path):
"""Update the OrgUnit of a OrgUser.
Args:
customer_id: The ID of the Google Apps customer.
user_email: The email address of the user.
org_unit_path: The new organization's full path name.
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
Returns:
A dict containing the result of the update operation.
"""
uri = USER_URL % (customer_id, user_email)
properties = {}
if org_unit_path:
properties['orgUnitPath'] = org_unit_path
return self._PutProperties(uri, properties) | [
"def",
"UpdateOrgUser",
"(",
"self",
",",
"customer_id",
",",
"user_email",
",",
"org_unit_path",
")",
":",
"uri",
"=",
"USER_URL",
"%",
"(",
"customer_id",
",",
"user_email",
")",
"properties",
"=",
"{",
"}",
"if",
"org_unit_path",
":",
"properties",
"[",
... | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/apps/organization/service.py#L220-L237 | |
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/whoosh/src/whoosh/util.py | python | float_to_byte | (value, mantissabits=5, zeroexp=2) | return b(result) | Encodes a floating point number in a single byte. | Encodes a floating point number in a single byte. | [
"Encodes",
"a",
"floating",
"point",
"number",
"in",
"a",
"single",
"byte",
"."
] | def float_to_byte(value, mantissabits=5, zeroexp=2):
"""Encodes a floating point number in a single byte.
"""
# Assume int size == float size
fzero = (63 - zeroexp) << mantissabits
bits = unpack("i", pack("f", value))[0]
smallfloat = bits >> (24 - mantissabits)
if smallfloat < fzero:
# Map negative numbers and 0 to 0
# Map underflow to next smallest non-zero number
if bits <= 0:
result = chr(0)
else:
result = chr(1)
elif smallfloat >= fzero + 0x100:
# Map overflow to largest number
result = chr(255)
else:
result = chr(smallfloat - fzero)
return b(result) | [
"def",
"float_to_byte",
"(",
"value",
",",
"mantissabits",
"=",
"5",
",",
"zeroexp",
"=",
"2",
")",
":",
"# Assume int size == float size",
"fzero",
"=",
"(",
"63",
"-",
"zeroexp",
")",
"<<",
"mantissabits",
"bits",
"=",
"unpack",
"(",
"\"i\"",
",",
"pack"... | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/whoosh/src/whoosh/util.py#L253-L274 | |
pallets/click | 051d57cef4ce59212dc1175ad4550743bf47d840 | src/click/core.py | python | BaseCommand.invoke | (self, ctx: Context) | Given a context, this invokes the command. The default
implementation is raising a not implemented error. | Given a context, this invokes the command. The default
implementation is raising a not implemented error. | [
"Given",
"a",
"context",
"this",
"invokes",
"the",
"command",
".",
"The",
"default",
"implementation",
"is",
"raising",
"a",
"not",
"implemented",
"error",
"."
] | def invoke(self, ctx: Context) -> t.Any:
"""Given a context, this invokes the command. The default
implementation is raising a not implemented error.
"""
raise NotImplementedError("Base commands are not invokable by default") | [
"def",
"invoke",
"(",
"self",
",",
"ctx",
":",
"Context",
")",
"->",
"t",
".",
"Any",
":",
"raise",
"NotImplementedError",
"(",
"\"Base commands are not invokable by default\"",
")"
] | https://github.com/pallets/click/blob/051d57cef4ce59212dc1175ad4550743bf47d840/src/click/core.py#L923-L927 | ||
gramps-project/gramps | 04d4651a43eb210192f40a9f8c2bad8ee8fa3753 | gramps/gen/db/base.py | python | DbWriteBase.remove_repository | (self, handle, transaction) | Remove the Repository specified by the database handle from the
database, preserving the change in the passed transaction. | Remove the Repository specified by the database handle from the
database, preserving the change in the passed transaction. | [
"Remove",
"the",
"Repository",
"specified",
"by",
"the",
"database",
"handle",
"from",
"the",
"database",
"preserving",
"the",
"change",
"in",
"the",
"passed",
"transaction",
"."
] | def remove_repository(self, handle, transaction):
"""
Remove the Repository specified by the database handle from the
database, preserving the change in the passed transaction.
"""
raise NotImplementedError | [
"def",
"remove_repository",
"(",
"self",
",",
"handle",
",",
"transaction",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/db/base.py#L1711-L1716 | ||
SickChill/SickChill | 01020f3636d01535f60b83464d8127ea0efabfc7 | sickchill/views/api/webapi.py | python | CMDPostProcess.run | (self) | return _responds(RESULT_SUCCESS, data=data, msg="Started post-process for {0}".format(self.release_name or self.path)) | Manually post-process the files in the download folder | Manually post-process the files in the download folder | [
"Manually",
"post",
"-",
"process",
"the",
"files",
"in",
"the",
"download",
"folder"
] | def run(self):
"""Manually post-process the files in the download folder"""
if not self.path and not settings.TV_DOWNLOAD_DIR:
return _responds(RESULT_FAILURE, msg="You need to provide a path or set TV Download Dir")
if not self.path:
self.path = settings.TV_DOWNLOAD_DIR
if not self.type:
self.type = "manual"
data = settings.postProcessorTaskScheduler.action.add_item(
self.path,
self.release_name,
method=self.process_method,
force=self.force_replace,
is_priority=self.is_priority,
failed=self.failed,
delete=self.delete,
mode=self.type,
force_next=self.force_next,
)
if not self.return_data:
data = ""
return _responds(RESULT_SUCCESS, data=data, msg="Started post-process for {0}".format(self.release_name or self.path)) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"path",
"and",
"not",
"settings",
".",
"TV_DOWNLOAD_DIR",
":",
"return",
"_responds",
"(",
"RESULT_FAILURE",
",",
"msg",
"=",
"\"You need to provide a path or set TV Download Dir\"",
")",
"if",
"not"... | https://github.com/SickChill/SickChill/blob/01020f3636d01535f60b83464d8127ea0efabfc7/sickchill/views/api/webapi.py#L1383-L1409 | |
vzhong/embeddings | 868b117bca4d9ac3e967bba5d895625db02cb2f3 | embeddings/concat.py | python | ConcatEmbedding.__init__ | (self, embeddings, default='none') | Args:
embeddings: embeddings to concatenate.
default: how to embed words that are out of vocabulary. Can use zeros, return ``None``, or generate random between ``[-0.1, 0.1]``. | [] | def __init__(self, embeddings, default='none'):
"""
Args:
embeddings: embeddings to concatenate.
default: how to embed words that are out of vocabulary. Can use zeros, return ``None``, or generate random between ``[-0.1, 0.1]``.
"""
for e in embeddings:
assert isinstance(e, Embedding), '{} is not an Embedding object'.format(e)
assert default in {'none', 'random', 'zero'}
self.embeddings = embeddings
self.default = default | [
"def",
"__init__",
"(",
"self",
",",
"embeddings",
",",
"default",
"=",
"'none'",
")",
":",
"for",
"e",
"in",
"embeddings",
":",
"assert",
"isinstance",
"(",
"e",
",",
"Embedding",
")",
",",
"'{} is not an Embedding object'",
".",
"format",
"(",
"e",
")",
... | https://github.com/vzhong/embeddings/blob/868b117bca4d9ac3e967bba5d895625db02cb2f3/embeddings/concat.py#L9-L21 | |||
conan-io/conan | 28ec09f6cbf1d7e27ec27393fd7bbc74891e74a8 | conans/client/rest/rest_client_v1.py | python | RestV1Methods._download_files | (self, file_urls, snapshot_md5) | :param: file_urls is a dict with {filename: url}
:param snapshot_md5: dict with {filaname: md5 checksum} of files to be downloaded
Its a generator, so it yields elements for memory performance | :param: file_urls is a dict with {filename: url}
:param snapshot_md5: dict with {filaname: md5 checksum} of files to be downloaded | [
":",
"param",
":",
"file_urls",
"is",
"a",
"dict",
"with",
"{",
"filename",
":",
"url",
"}",
":",
"param",
"snapshot_md5",
":",
"dict",
"with",
"{",
"filaname",
":",
"md5",
"checksum",
"}",
"of",
"files",
"to",
"be",
"downloaded"
] | def _download_files(self, file_urls, snapshot_md5):
"""
:param: file_urls is a dict with {filename: url}
:param snapshot_md5: dict with {filaname: md5 checksum} of files to be downloaded
Its a generator, so it yields elements for memory performance
"""
# Take advantage of filenames ordering, so that conan_package.tgz and conan_export.tgz
# can be < conanfile, conaninfo, and sent always the last, so smaller files go first
retry = self._config.retry
retry_wait = self._config.retry_wait
download_cache = self._config.download_cache
for filename, resource_url in sorted(file_urls.items(), reverse=True):
auth, _ = self._file_server_capabilities(resource_url)
md5 = snapshot_md5.get(filename, None) if snapshot_md5 else None
assert not download_cache or snapshot_md5, \
"if download_cache is set, we need the file checksums"
contents = run_downloader(self.requester, None, self.verify_ssl, retry=retry,
retry_wait=retry_wait, download_cache=download_cache,
url=resource_url, auth=auth, md5=md5)
yield os.path.normpath(filename), contents | [
"def",
"_download_files",
"(",
"self",
",",
"file_urls",
",",
"snapshot_md5",
")",
":",
"# Take advantage of filenames ordering, so that conan_package.tgz and conan_export.tgz",
"# can be < conanfile, conaninfo, and sent always the last, so smaller files go first",
"retry",
"=",
"self",
... | https://github.com/conan-io/conan/blob/28ec09f6cbf1d7e27ec27393fd7bbc74891e74a8/conans/client/rest/rest_client_v1.py#L40-L60 | ||
IdentityPython/pysaml2 | 6badb32d212257bd83ffcc816f9b625f68281b47 | src/saml2/mdstore.py | python | destinations | (srvs) | return values | [] | def destinations(srvs):
warn_msg = (
"`saml2.mdstore.destinations` function is deprecated; "
"instead, use `saml2.mdstore.locations` or `saml2.mdstore.all_locations`."
)
logger.warning(warn_msg)
_warn(warn_msg, DeprecationWarning)
values = list(locations(srvs))
return values | [
"def",
"destinations",
"(",
"srvs",
")",
":",
"warn_msg",
"=",
"(",
"\"`saml2.mdstore.destinations` function is deprecated; \"",
"\"instead, use `saml2.mdstore.locations` or `saml2.mdstore.all_locations`.\"",
")",
"logger",
".",
"warning",
"(",
"warn_msg",
")",
"_warn",
"(",
... | https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/mdstore.py#L200-L208 | |||
ganeti/ganeti | d340a9ddd12f501bef57da421b5f9b969a4ba905 | qa/qa_utils.py | python | GetNodeInstances | (node, secondaries=False) | return instances | Gets a list of instances on a node. | Gets a list of instances on a node. | [
"Gets",
"a",
"list",
"of",
"instances",
"on",
"a",
"node",
"."
] | def GetNodeInstances(node, secondaries=False):
"""Gets a list of instances on a node.
"""
master = qa_config.GetMasterNode()
node_name = ResolveNodeName(node)
# Get list of all instances
cmd = ["gnt-instance", "list", "--separator=:", "--no-headers",
"--output=name,pnode,snodes"]
output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd))
instances = []
for line in output.splitlines():
(name, pnode, snodes) = line.split(":", 2)
if ((not secondaries and pnode == node_name) or
(secondaries and node_name in snodes.split(","))):
instances.append(name)
return instances | [
"def",
"GetNodeInstances",
"(",
"node",
",",
"secondaries",
"=",
"False",
")",
":",
"master",
"=",
"qa_config",
".",
"GetMasterNode",
"(",
")",
"node_name",
"=",
"ResolveNodeName",
"(",
"node",
")",
"# Get list of all instances",
"cmd",
"=",
"[",
"\"gnt-instance... | https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/qa/qa_utils.py#L579-L598 | |
google-research/tapas | a3e069b50c71f50b12a6e5bb3dad10fb51f6fe68 | tapas/retrieval/tfidf_baseline_utils.py | python | InvertedIndex.retrieve | (self, question) | return scored_hits | Retrieves tables sorted by descending score. | Retrieves tables sorted by descending score. | [
"Retrieves",
"tables",
"sorted",
"by",
"descending",
"score",
"."
] | def retrieve(self, question):
"""Retrieves tables sorted by descending score."""
hits = collections.defaultdict(list)
num_tokens = 0
for token in _tokenize(question):
num_tokens += 1
index_entry = self.index_.get(token, None)
if index_entry is None:
continue
for table_count in index_entry.table_counts:
scores = hits[table_count.table_index]
scores.append(table_count.score)
scored_hits = []
for table_index, inv_document_freqs in hits.items():
score = sum(inv_document_freqs) / num_tokens
scored_hits.append((self.table_ids_[table_index], score))
scored_hits.sort(key=lambda name_score: name_score[1], reverse=True)
return scored_hits | [
"def",
"retrieve",
"(",
"self",
",",
"question",
")",
":",
"hits",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"num_tokens",
"=",
"0",
"for",
"token",
"in",
"_tokenize",
"(",
"question",
")",
":",
"num_tokens",
"+=",
"1",
"index_entry",
"="... | https://github.com/google-research/tapas/blob/a3e069b50c71f50b12a6e5bb3dad10fb51f6fe68/tapas/retrieval/tfidf_baseline_utils.py#L86-L107 | |
vlachoudis/bCNC | 67126b4894dabf6579baf47af8d0f9b7de35e6e3 | bCNC/lib/tkExtra.py | python | MultiListbox.focus_set | (self) | [] | def focus_set(self):
self._lists[0].focus_set() | [
"def",
"focus_set",
"(",
"self",
")",
":",
"self",
".",
"_lists",
"[",
"0",
"]",
".",
"focus_set",
"(",
")"
] | https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/lib/tkExtra.py#L1693-L1694 | ||||
open-mmlab/mmdetection3d | c7272063e818bcf33aebc498a017a95c8d065143 | mmdet3d/models/segmentors/base.py | python | Base3DSegmentor.with_regularization_loss | (self) | return hasattr(self, 'loss_regularization') and \
self.loss_regularization is not None | bool: whether the segmentor has regularization loss for weight | bool: whether the segmentor has regularization loss for weight | [
"bool",
":",
"whether",
"the",
"segmentor",
"has",
"regularization",
"loss",
"for",
"weight"
] | def with_regularization_loss(self):
"""bool: whether the segmentor has regularization loss for weight"""
return hasattr(self, 'loss_regularization') and \
self.loss_regularization is not None | [
"def",
"with_regularization_loss",
"(",
"self",
")",
":",
"return",
"hasattr",
"(",
"self",
",",
"'loss_regularization'",
")",
"and",
"self",
".",
"loss_regularization",
"is",
"not",
"None"
] | https://github.com/open-mmlab/mmdetection3d/blob/c7272063e818bcf33aebc498a017a95c8d065143/mmdet3d/models/segmentors/base.py#L21-L24 | |
guildai/guildai | 1665985a3d4d788efc1a3180ca51cc417f71ca78 | guild/external/pip/_vendor/pkg_resources/__init__.py | python | _is_egg_path | (path) | return path.lower().endswith('.egg') | Determine if given path appears to be an egg. | Determine if given path appears to be an egg. | [
"Determine",
"if",
"given",
"path",
"appears",
"to",
"be",
"an",
"egg",
"."
] | def _is_egg_path(path):
"""
Determine if given path appears to be an egg.
"""
return path.lower().endswith('.egg') | [
"def",
"_is_egg_path",
"(",
"path",
")",
":",
"return",
"path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.egg'",
")"
] | https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/pkg_resources/__init__.py#L2228-L2232 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/capirca_acl.py | python | _import_platform_generator | (platform) | Given a specific platform (under the Capirca conventions),
return the generator class.
The generator class is identified looking under the <platform> module
for a class inheriting the `ACLGenerator` class. | Given a specific platform (under the Capirca conventions),
return the generator class.
The generator class is identified looking under the <platform> module
for a class inheriting the `ACLGenerator` class. | [
"Given",
"a",
"specific",
"platform",
"(",
"under",
"the",
"Capirca",
"conventions",
")",
"return",
"the",
"generator",
"class",
".",
"The",
"generator",
"class",
"is",
"identified",
"looking",
"under",
"the",
"<platform",
">",
"module",
"for",
"a",
"class",
... | def _import_platform_generator(platform):
"""
Given a specific platform (under the Capirca conventions),
return the generator class.
The generator class is identified looking under the <platform> module
for a class inheriting the `ACLGenerator` class.
"""
log.debug("Using platform: %s", platform)
for mod_name, mod_obj in inspect.getmembers(capirca.aclgen):
if mod_name == platform and inspect.ismodule(mod_obj):
for plat_obj_name, plat_obj in inspect.getmembers(
mod_obj
): # pylint: disable=unused-variable
if inspect.isclass(plat_obj) and issubclass(
plat_obj, capirca.lib.aclgenerator.ACLGenerator
):
log.debug("Identified Capirca class %s for %s", plat_obj, platform)
return plat_obj
log.error("Unable to identify any Capirca plaform class for %s", platform) | [
"def",
"_import_platform_generator",
"(",
"platform",
")",
":",
"log",
".",
"debug",
"(",
"\"Using platform: %s\"",
",",
"platform",
")",
"for",
"mod_name",
",",
"mod_obj",
"in",
"inspect",
".",
"getmembers",
"(",
"capirca",
".",
"aclgen",
")",
":",
"if",
"m... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/capirca_acl.py#L197-L215 | ||
google/trax | d6cae2067dedd0490b78d831033607357e975015 | trax/models/research/rse.py | python | ResidualShuffleExchange | (vocab_size,
d_model,
input_dropout,
dropout,
mode='train',
n_blocks=2) | return tl.Serial(
tl.Embedding(vocab_size, d_model),
tl.Dropout(rate=input_dropout, mode=mode),
# Apply Benes Block n_blocks times.
*benes_blocks,
ResidualSwitchUnit(d_model, dropout, mode),
# Produce probabilities.
tl.Dense(vocab_size),
tl.LogSoftmax(),
) | Returns a Residual Shuffle Exchange Network model. | Returns a Residual Shuffle Exchange Network model. | [
"Returns",
"a",
"Residual",
"Shuffle",
"Exchange",
"Network",
"model",
"."
] | def ResidualShuffleExchange(vocab_size,
d_model,
input_dropout,
dropout,
mode='train',
n_blocks=2):
"""Returns a Residual Shuffle Exchange Network model."""
benes_blocks = [BenesBlock(d_model, dropout, mode) for _ in range(n_blocks)]
return tl.Serial(
tl.Embedding(vocab_size, d_model),
tl.Dropout(rate=input_dropout, mode=mode),
# Apply Benes Block n_blocks times.
*benes_blocks,
ResidualSwitchUnit(d_model, dropout, mode),
# Produce probabilities.
tl.Dense(vocab_size),
tl.LogSoftmax(),
) | [
"def",
"ResidualShuffleExchange",
"(",
"vocab_size",
",",
"d_model",
",",
"input_dropout",
",",
"dropout",
",",
"mode",
"=",
"'train'",
",",
"n_blocks",
"=",
"2",
")",
":",
"benes_blocks",
"=",
"[",
"BenesBlock",
"(",
"d_model",
",",
"dropout",
",",
"mode",
... | https://github.com/google/trax/blob/d6cae2067dedd0490b78d831033607357e975015/trax/models/research/rse.py#L203-L220 | |
pycontribs/pyrax | a0c022981f76a4cba96a22ecc19bb52843ac4fbe | pyrax/object_storage.py | python | Container.copy_object | (self, obj, new_container, new_obj_name=None,
content_type=None) | return self.manager.copy_object(self, obj, new_container,
new_obj_name=new_obj_name, content_type=content_type) | Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name. | Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name. | [
"Copies",
"the",
"object",
"to",
"the",
"new",
"container",
"optionally",
"giving",
"it",
"a",
"new",
"name",
".",
"If",
"you",
"copy",
"to",
"the",
"same",
"container",
"you",
"must",
"supply",
"a",
"different",
"name",
"."
] | def copy_object(self, obj, new_container, new_obj_name=None,
content_type=None):
"""
Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name.
"""
return self.manager.copy_object(self, obj, new_container,
new_obj_name=new_obj_name, content_type=content_type) | [
"def",
"copy_object",
"(",
"self",
",",
"obj",
",",
"new_container",
",",
"new_obj_name",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"return",
"self",
".",
"manager",
".",
"copy_object",
"(",
"self",
",",
"obj",
",",
"new_container",
",",
"... | https://github.com/pycontribs/pyrax/blob/a0c022981f76a4cba96a22ecc19bb52843ac4fbe/pyrax/object_storage.py#L599-L606 | |
sethmlarson/virtualbox-python | 984a6e2cb0e8996f4df40f4444c1528849f1c70d | virtualbox/library.py | python | IInternalSessionControl.reconfigure_medium_attachments | (self, attachments) | Reconfigure all specified medium attachments in one go, making sure
the current state corresponds to the specified medium.
in attachments of type :class:`IMediumAttachment`
Array containing the medium attachments which need to be
reconfigured.
raises :class:`VBoxErrorInvalidVmState`
Machine session is not open.
raises :class:`VBoxErrorInvalidObjectState`
Session type is not direct. | Reconfigure all specified medium attachments in one go, making sure
the current state corresponds to the specified medium. | [
"Reconfigure",
"all",
"specified",
"medium",
"attachments",
"in",
"one",
"go",
"making",
"sure",
"the",
"current",
"state",
"corresponds",
"to",
"the",
"specified",
"medium",
"."
] | def reconfigure_medium_attachments(self, attachments):
"""Reconfigure all specified medium attachments in one go, making sure
the current state corresponds to the specified medium.
in attachments of type :class:`IMediumAttachment`
Array containing the medium attachments which need to be
reconfigured.
raises :class:`VBoxErrorInvalidVmState`
Machine session is not open.
raises :class:`VBoxErrorInvalidObjectState`
Session type is not direct.
"""
if not isinstance(attachments, list):
raise TypeError("attachments can only be an instance of type list")
for a in attachments[:10]:
if not isinstance(a, IMediumAttachment):
raise TypeError(
"array can only contain objects of type IMediumAttachment"
)
self._call("reconfigureMediumAttachments", in_p=[attachments]) | [
"def",
"reconfigure_medium_attachments",
"(",
"self",
",",
"attachments",
")",
":",
"if",
"not",
"isinstance",
"(",
"attachments",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"attachments can only be an instance of type list\"",
")",
"for",
"a",
"in",
"attac... | https://github.com/sethmlarson/virtualbox-python/blob/984a6e2cb0e8996f4df40f4444c1528849f1c70d/virtualbox/library.py#L32403-L32425 | ||
cuhkrlcourse/RLexample | 17a74b0408fe6cbff4b725afe22d58a4cce1a1e9 | modelfree/cliffwalk.py | python | GridWorld._position_to_id | (self, pos) | return pos[0] * 12 + pos[1] | Maps a position in x,y coordinates to a unique ID | Maps a position in x,y coordinates to a unique ID | [
"Maps",
"a",
"position",
"in",
"x",
"y",
"coordinates",
"to",
"a",
"unique",
"ID"
] | def _position_to_id(self, pos):
''' Maps a position in x,y coordinates to a unique ID '''
return pos[0] * 12 + pos[1] | [
"def",
"_position_to_id",
"(",
"self",
",",
"pos",
")",
":",
"return",
"pos",
"[",
"0",
"]",
"*",
"12",
"+",
"pos",
"[",
"1",
"]"
] | https://github.com/cuhkrlcourse/RLexample/blob/17a74b0408fe6cbff4b725afe22d58a4cce1a1e9/modelfree/cliffwalk.py#L78-L80 | |
timonwong/OmniMarkupPreviewer | 21921ac7a99d2b5924a2219b33679a5b53621392 | OmniMarkupLib/Renderers/libs/python2/docutils/utils/math/math2html.py | python | FormulaProcessor.traversewhole | (self, formula) | Traverse over the contents to alter variables and space units. | Traverse over the contents to alter variables and space units. | [
"Traverse",
"over",
"the",
"contents",
"to",
"alter",
"variables",
"and",
"space",
"units",
"."
] | def traversewhole(self, formula):
"Traverse over the contents to alter variables and space units."
last = None
for bit, contents in self.traverse(formula):
if bit.type == 'alpha':
self.italicize(bit, contents)
elif bit.type == 'font' and last and last.type == 'number':
bit.contents.insert(0, FormulaConstant(u' '))
last = bit | [
"def",
"traversewhole",
"(",
"self",
",",
"formula",
")",
":",
"last",
"=",
"None",
"for",
"bit",
",",
"contents",
"in",
"self",
".",
"traverse",
"(",
"formula",
")",
":",
"if",
"bit",
".",
"type",
"==",
"'alpha'",
":",
"self",
".",
"italicize",
"(",... | https://github.com/timonwong/OmniMarkupPreviewer/blob/21921ac7a99d2b5924a2219b33679a5b53621392/OmniMarkupLib/Renderers/libs/python2/docutils/utils/math/math2html.py#L2775-L2783 | ||
OpenShot/openshot-qt | bbd2dd040a4e2a6120791e6c65ae0ddf212cb73d | src/windows/views/tutorial.py | python | TutorialManager.process | (self, parent_name=None) | Process and show the first non-completed tutorial | Process and show the first non-completed tutorial | [
"Process",
"and",
"show",
"the",
"first",
"non",
"-",
"completed",
"tutorial"
] | def process(self, parent_name=None):
""" Process and show the first non-completed tutorial """
# If a tutorial is already visible, just update it
if self.current_dialog:
# Respond to possible dock floats/moves
self.dock.raise_()
self.re_position_dialog()
return
# Loop through and add each tutorial dialog
for tutorial_details in self.tutorial_objects:
# Get details
tutorial_id = tutorial_details["id"]
# Get QWidget
tutorial_object = self.get_object(tutorial_details["object_id"])
# Skip completed tutorials (and invisible widgets)
if not self.tutorial_enabled or tutorial_id in self.tutorial_ids or tutorial_object.visibleRegion().isEmpty():
continue
# Create tutorial
self.position_widget = tutorial_object
self.offset = QPoint(
int(tutorial_details["x"]),
int(tutorial_details["y"]))
tutorial_dialog = TutorialDialog(tutorial_id, tutorial_details["text"], tutorial_details["arrow"], self)
# Connect signals
tutorial_dialog.btn_next_tip.clicked.connect(functools.partial(self.next_tip, tutorial_id))
tutorial_dialog.btn_close_tips.clicked.connect(functools.partial(self.hide_tips, tutorial_id, True))
# Get previous dock contents
old_widget = self.dock.widget()
# Insert into tutorial dock
self.dock.setWidget(tutorial_dialog)
self.current_dialog = tutorial_dialog
# Show dialog
self.dock.adjustSize()
self.dock.setEnabled(True)
self.re_position_dialog()
self.dock.show()
# Delete old widget
if old_widget:
old_widget.close()
break | [
"def",
"process",
"(",
"self",
",",
"parent_name",
"=",
"None",
")",
":",
"# If a tutorial is already visible, just update it",
"if",
"self",
".",
"current_dialog",
":",
"# Respond to possible dock floats/moves",
"self",
".",
"dock",
".",
"raise_",
"(",
")",
"self",
... | https://github.com/OpenShot/openshot-qt/blob/bbd2dd040a4e2a6120791e6c65ae0ddf212cb73d/src/windows/views/tutorial.py#L184-L234 | ||
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/ws_client.py | python | WSClient.peek_stdout | (self, timeout=0) | return self.peek_channel(STDOUT_CHANNEL, timeout=timeout) | Same as peek_channel with channel=1. | Same as peek_channel with channel=1. | [
"Same",
"as",
"peek_channel",
"with",
"channel",
"=",
"1",
"."
] | def peek_stdout(self, timeout=0):
"""Same as peek_channel with channel=1."""
return self.peek_channel(STDOUT_CHANNEL, timeout=timeout) | [
"def",
"peek_stdout",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"return",
"self",
".",
"peek_channel",
"(",
"STDOUT_CHANNEL",
",",
"timeout",
"=",
"timeout",
")"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/ws_client.py#L115-L117 | |
flexxui/flexx | 69b85b308b505a8621305458a5094f2a6addd720 | flexx/ui/layouts/_hv.py | python | HVLayout._query_min_max_size | (self) | return [max(mima1[0], mima0[0]),
min(mima1[1], mima0[1]),
max(mima1[2], mima0[2]),
min(mima1[3], mima0[3])] | Overload to also take child limits into account. | Overload to also take child limits into account. | [
"Overload",
"to",
"also",
"take",
"child",
"limits",
"into",
"account",
"."
] | def _query_min_max_size(self):
""" Overload to also take child limits into account.
"""
# This streams information about min and max sizes upward, for
# split and fix mode. Most flexbox implementations don't seem to
# look for min/max sizes of their children. We could set min-width and
# friends at the layout to help flexbox a bit, but that would possibly
# overwrite a user-set value. Hopefully flexbox will get fixed soon.
hori = 'h' in self.orientation
# Own limits
mima0 = super()._query_min_max_size()
# Init limits for children
if hori is True:
mima1 = [0, 0, 0, 1e9]
else:
mima1 = [0, 1e9, 0, 0]
# Collect contributions of child widgets?
if self.minsize_from_children:
for child in self.children:
mima2 = child._size_limits
if hori is True:
mima1[0] += mima2[0]
mima1[1] += mima2[1]
mima1[2] = max(mima1[2], mima2[2])
mima1[3] = min(mima1[3], mima2[3])
else:
mima1[0] = max(mima1[0], mima2[0])
mima1[1] = min(mima1[1], mima2[1])
mima1[2] += mima2[2]
mima1[3] += mima2[3]
# Set unset max sizes
if mima1[1] == 0:
mima1[1] = 1e9
if mima1[3] == 0:
mima1[3] = 1e9
# Add padding and spacing
if self.minsize_from_children:
extra_padding = self.padding * 2
extra_spacing = self.spacing * (len(self.children) - 1)
for i in range(4):
mima1[i] += extra_padding
if hori is True:
mima1[0] += extra_spacing
mima1[1] += extra_spacing
else:
mima1[2] += extra_spacing
mima1[3] += extra_spacing
# Combine own limits with limits of children
return [max(mima1[0], mima0[0]),
min(mima1[1], mima0[1]),
max(mima1[2], mima0[2]),
min(mima1[3], mima0[3])] | [
"def",
"_query_min_max_size",
"(",
"self",
")",
":",
"# This streams information about min and max sizes upward, for",
"# split and fix mode. Most flexbox implementations don't seem to",
"# look for min/max sizes of their children. We could set min-width and",
"# friends at the layout to help flex... | https://github.com/flexxui/flexx/blob/69b85b308b505a8621305458a5094f2a6addd720/flexx/ui/layouts/_hv.py#L396-L455 | |
ipfs-shipyard/py-ipfs-http-client | f04ff601556f8429837eb7d4851fe02913f72f63 | ipfshttpclient/encoding.py | python | get_encoding | (name: ty_ext.Literal["none"]) | [] | def get_encoding(name: ty_ext.Literal["none"]) -> Dummy:
... | [
"def",
"get_encoding",
"(",
"name",
":",
"ty_ext",
".",
"Literal",
"[",
"\"none\"",
"]",
")",
"->",
"Dummy",
":",
"..."
] | https://github.com/ipfs-shipyard/py-ipfs-http-client/blob/f04ff601556f8429837eb7d4851fe02913f72f63/ipfshttpclient/encoding.py#L256-L257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.