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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/pip/pip/_vendor/urllib3/contrib/_securetransport/low_level.py | python | _load_items_from_file | (keychain, path) | return (identities, certificates) | Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs. | Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs. | [
"Given",
"a",
"single",
"file",
"loads",
"all",
"the",
"trust",
"objects",
"from",
"it",
"into",
"arrays",
"and",
"the",
"keychain",
".",
"Returns",
"a",
"tuple",
"of",
"lists",
":",
"the",
"first",
"list",
"is",
"a",
"list",
"of",
"identities",
"the",
... | def _load_items_from_file(keychain, path):
"""
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
"""
certificates = []
identities = []
result_array = None
with open(path, "rb") as f:
raw_filedata = f.read()
try:
filedata = CoreFoundation.CFDataCreate(
CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata)
)
result_array = CoreFoundation.CFArrayRef()
result = Security.SecItemImport(
filedata, # cert data
None, # Filename, leaving it out for now
None, # What the type of the file is, we don't care
None, # what's in the file, we don't care
0, # import flags
None, # key params, can include passphrase in the future
keychain, # The keychain to insert into
ctypes.byref(result_array), # Results
)
_assert_no_error(result)
# A CFArray is not very useful to us as an intermediary
# representation, so we are going to extract the objects we want
# and then free the array. We don't need to keep hold of keys: the
# keychain already has them!
result_count = CoreFoundation.CFArrayGetCount(result_array)
for index in range(result_count):
item = CoreFoundation.CFArrayGetValueAtIndex(result_array, index)
item = ctypes.cast(item, CoreFoundation.CFTypeRef)
if _is_cert(item):
CoreFoundation.CFRetain(item)
certificates.append(item)
elif _is_identity(item):
CoreFoundation.CFRetain(item)
identities.append(item)
finally:
if result_array:
CoreFoundation.CFRelease(result_array)
CoreFoundation.CFRelease(filedata)
return (identities, certificates) | [
"def",
"_load_items_from_file",
"(",
"keychain",
",",
"path",
")",
":",
"certificates",
"=",
"[",
"]",
"identities",
"=",
"[",
"]",
"result_array",
"=",
"None",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"raw_filedata",
"=",
"f",
... | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/urllib3/contrib/_securetransport/low_level.py#L246-L298 | |
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/req/req_install.py | python | InstallRequirement.populate_link | (self, finder, upgrade, require_hashes) | Ensure that if a link can be found for this, that it is found.
Note that self.link may still be None - if Upgrade is False and the
requirement is already installed.
If require_hashes is True, don't use the wheel cache, because cached
wheels, always built locally, have different hashes than the files
downloaded from the index server and thus throw false hash mismatches.
Furthermore, cached wheels at present have undeterministic contents due
to file modification times. | Ensure that if a link can be found for this, that it is found. | [
"Ensure",
"that",
"if",
"a",
"link",
"can",
"be",
"found",
"for",
"this",
"that",
"it",
"is",
"found",
"."
] | def populate_link(self, finder, upgrade, require_hashes):
"""Ensure that if a link can be found for this, that it is found.
Note that self.link may still be None - if Upgrade is False and the
requirement is already installed.
If require_hashes is True, don't use the wheel cache, because cached
wheels, always built locally, have different hashes than the files
downloaded from the index server and thus throw false hash mismatches.
Furthermore, cached wheels at present have undeterministic contents due
to file modification times.
"""
if self.link is None:
self.link = finder.find_requirement(self, upgrade)
if self._wheel_cache is not None and not require_hashes:
old_link = self.link
self.link = self._wheel_cache.cached_wheel(self.link, self.name)
if old_link != self.link:
logger.debug('Using cached wheel link: %s', self.link) | [
"def",
"populate_link",
"(",
"self",
",",
"finder",
",",
"upgrade",
",",
"require_hashes",
")",
":",
"if",
"self",
".",
"link",
"is",
"None",
":",
"self",
".",
"link",
"=",
"finder",
".",
"find_requirement",
"(",
"self",
",",
"upgrade",
")",
"if",
"sel... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/req/req_install.py#L265-L283 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/flask/json/tag.py | python | TaggedJSONSerializer.register | (self, tag_class, force=False, index=None) | Register a new tag with this serializer.
:param tag_class: tag class to register. Will be instantiated with this
serializer instance.
:param force: overwrite an existing tag. If false (default), a
:exc:`KeyError` is raised.
:param index: index to insert the new tag in the tag order. Useful when
the new tag is a special case of an existing tag. If ``None``
(default), the tag is appended to the end of the order.
:raise KeyError: if the tag key is already registered and ``force`` is
not true. | Register a new tag with this serializer. | [
"Register",
"a",
"new",
"tag",
"with",
"this",
"serializer",
"."
] | def register(self, tag_class, force=False, index=None):
"""Register a new tag with this serializer.
:param tag_class: tag class to register. Will be instantiated with this
serializer instance.
:param force: overwrite an existing tag. If false (default), a
:exc:`KeyError` is raised.
:param index: index to insert the new tag in the tag order. Useful when
the new tag is a special case of an existing tag. If ``None``
(default), the tag is appended to the end of the order.
:raise KeyError: if the tag key is already registered and ``force`` is
not true.
"""
tag = tag_class(self)
key = tag.key
if key is not None:
if not force and key in self.tags:
raise KeyError("Tag '{0}' is already registered.".format(key))
self.tags[key] = tag
if index is None:
self.order.append(tag)
else:
self.order.insert(index, tag) | [
"def",
"register",
"(",
"self",
",",
"tag_class",
",",
"force",
"=",
"False",
",",
"index",
"=",
"None",
")",
":",
"tag",
"=",
"tag_class",
"(",
"self",
")",
"key",
"=",
"tag",
".",
"key",
"if",
"key",
"is",
"not",
"None",
":",
"if",
"not",
"forc... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/flask/json/tag.py#L246-L272 | ||
interrogator/corpkit | c54be1f8c83d960b630802f31c5b825a3e7e3a70 | corpkit/interrogation.py | python | Interrodict.edit | (self, *args, **kwargs) | return editor(self, *args, **kwargs) | Edit each value with :func:`~corpkit.interrogation.Interrogation.edit`.
See :func:`~corpkit.interrogation.Interrogation.edit` for possible arguments.
:returns: A :class:`corpkit.interrogation.Interrodict` | Edit each value with :func:`~corpkit.interrogation.Interrogation.edit`. | [
"Edit",
"each",
"value",
"with",
":",
"func",
":",
"~corpkit",
".",
"interrogation",
".",
"Interrogation",
".",
"edit",
"."
] | def edit(self, *args, **kwargs):
"""Edit each value with :func:`~corpkit.interrogation.Interrogation.edit`.
See :func:`~corpkit.interrogation.Interrogation.edit` for possible arguments.
:returns: A :class:`corpkit.interrogation.Interrodict`
"""
from corpkit.editor import editor
return editor(self, *args, **kwargs) | [
"def",
"edit",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"corpkit",
".",
"editor",
"import",
"editor",
"return",
"editor",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/interrogator/corpkit/blob/c54be1f8c83d960b630802f31c5b825a3e7e3a70/corpkit/interrogation.py#L741-L750 | |
FabriceSalvaire/PySpice | 1fb97dc21abcf04cfd78802671322eef5c0de00b | PySpice/Math/Calculus.py | python | simple_derivative | (x, values) | return x[:-1], np.diff(values)/np.diff(x) | Compute the derivative as a simple slope. | Compute the derivative as a simple slope. | [
"Compute",
"the",
"derivative",
"as",
"a",
"simple",
"slope",
"."
] | def simple_derivative(x, values):
""" Compute the derivative as a simple slope. """
return x[:-1], np.diff(values)/np.diff(x) | [
"def",
"simple_derivative",
"(",
"x",
",",
"values",
")",
":",
"return",
"x",
"[",
":",
"-",
"1",
"]",
",",
"np",
".",
"diff",
"(",
"values",
")",
"/",
"np",
".",
"diff",
"(",
"x",
")"
] | https://github.com/FabriceSalvaire/PySpice/blob/1fb97dc21abcf04cfd78802671322eef5c0de00b/PySpice/Math/Calculus.py#L110-L112 | |
dropbox/PyHive | b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0 | TCLIService/ttypes.py | python | TRenewDelegationTokenReq.__repr__ | (self) | return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) | [] | def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"L",
"=",
"[",
"'%s=%r'",
"%",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"]",
"return",
"'%s(%s)'",
"%",
"(",
"self",
".",
"__class_... | https://github.com/dropbox/PyHive/blob/b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0/TCLIService/ttypes.py#L6999-L7002 | |||
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/tornado/gen.py | python | WaitIterator.done | (self) | return True | Returns True if this iterator has no more results. | Returns True if this iterator has no more results. | [
"Returns",
"True",
"if",
"this",
"iterator",
"has",
"no",
"more",
"results",
"."
] | def done(self) -> bool:
"""Returns True if this iterator has no more results."""
if self._finished or self._unfinished:
return False
# Clear the 'current' values when iteration is done.
self.current_index = self.current_future = None
return True | [
"def",
"done",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_finished",
"or",
"self",
".",
"_unfinished",
":",
"return",
"False",
"# Clear the 'current' values when iteration is done.",
"self",
".",
"current_index",
"=",
"self",
".",
"current_future",
... | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/tornado/gen.py#L386-L392 | |
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/packaging/specifiers.py | python | _is_not_suffix | (segment: str) | return not any(
segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
) | [] | def _is_not_suffix(segment: str) -> bool:
return not any(
segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
) | [
"def",
"_is_not_suffix",
"(",
"segment",
":",
"str",
")",
"->",
"bool",
":",
"return",
"not",
"any",
"(",
"segment",
".",
"startswith",
"(",
"prefix",
")",
"for",
"prefix",
"in",
"(",
"\"dev\"",
",",
"\"a\"",
",",
"\"b\"",
",",
"\"rc\"",
",",
"\"post\"... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/packaging/specifiers.py#L614-L617 | |||
theeluwin/pytorch-sgns | 2d007c700545ae2a3e44b1f4bf37fa1b034a7d27 | model.py | python | Word2Vec.forward_o | (self, data) | return self.ovectors(v) | [] | def forward_o(self, data):
v = LT(data)
v = v.cuda() if self.ovectors.weight.is_cuda else v
return self.ovectors(v) | [
"def",
"forward_o",
"(",
"self",
",",
"data",
")",
":",
"v",
"=",
"LT",
"(",
"data",
")",
"v",
"=",
"v",
".",
"cuda",
"(",
")",
"if",
"self",
".",
"ovectors",
".",
"weight",
".",
"is_cuda",
"else",
"v",
"return",
"self",
".",
"ovectors",
"(",
"... | https://github.com/theeluwin/pytorch-sgns/blob/2d007c700545ae2a3e44b1f4bf37fa1b034a7d27/model.py#L44-L47 | |||
phantomcyber/playbooks | 9e850ecc44cb98c5dde53784744213a1ed5799bd | risk_notable_merge_events.py | python | add_note_4 | (action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs) | return | [] | def add_note_4(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug("add_note_4() called")
merge_individual_format = phantom.get_format_data(name="merge_individual_format")
################################################################################
## Custom Code Start
################################################################################
# Write your custom code here...
################################################################################
## Custom Code End
################################################################################
phantom.add_note(container=container, content=merge_individual_format, note_format="markdown", note_type="general", title="[Auto-Generated] Related Events Merged")
return | [
"def",
"add_note_4",
"(",
"action",
"=",
"None",
",",
"success",
"=",
"None",
",",
"container",
"=",
"None",
",",
"results",
"=",
"None",
",",
"handle",
"=",
"None",
",",
"filtered_artifacts",
"=",
"None",
",",
"filtered_results",
"=",
"None",
",",
"cust... | https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/risk_notable_merge_events.py#L915-L932 | |||
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | jboss_wildfly/datadog_checks/jboss_wildfly/config_models/defaults.py | python | instance_service | (field, value) | return get_default_field_value(field, value) | [] | def instance_service(field, value):
return get_default_field_value(field, value) | [
"def",
"instance_service",
"(",
"field",
",",
"value",
")",
":",
"return",
"get_default_field_value",
"(",
"field",
",",
"value",
")"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/jboss_wildfly/datadog_checks/jboss_wildfly/config_models/defaults.py#L101-L102 | |||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/boto-2.46.1/boto/endpoints.py | python | StaticEndpointBuilder.__init__ | (self, resolver) | :type resolver: BotoEndpointResolver
:param resolver: An endpoint resolver. | :type resolver: BotoEndpointResolver
:param resolver: An endpoint resolver. | [
":",
"type",
"resolver",
":",
"BotoEndpointResolver",
":",
"param",
"resolver",
":",
"An",
"endpoint",
"resolver",
"."
] | def __init__(self, resolver):
"""
:type resolver: BotoEndpointResolver
:param resolver: An endpoint resolver.
"""
self._resolver = resolver | [
"def",
"__init__",
"(",
"self",
",",
"resolver",
")",
":",
"self",
".",
"_resolver",
"=",
"resolver"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/endpoints.py#L192-L197 | ||
inkandswitch/livebook | 93c8d467734787366ad084fc3566bf5cbe249c51 | public/pypyjs/modules/stackless.py | python | schedule_remove | (retval=None) | return r | schedule(retval=stackless.current) -- switch to the next runnable tasklet.
The return value for this call is retval, with the current
tasklet as default.
schedule_remove(retval=stackless.current) -- ditto, and remove self. | schedule(retval=stackless.current) -- switch to the next runnable tasklet.
The return value for this call is retval, with the current
tasklet as default.
schedule_remove(retval=stackless.current) -- ditto, and remove self. | [
"schedule",
"(",
"retval",
"=",
"stackless",
".",
"current",
")",
"--",
"switch",
"to",
"the",
"next",
"runnable",
"tasklet",
".",
"The",
"return",
"value",
"for",
"this",
"call",
"is",
"retval",
"with",
"the",
"current",
"tasklet",
"as",
"default",
".",
... | def schedule_remove(retval=None):
"""
schedule(retval=stackless.current) -- switch to the next runnable tasklet.
The return value for this call is retval, with the current
tasklet as default.
schedule_remove(retval=stackless.current) -- ditto, and remove self.
"""
_scheduler_remove(getcurrent())
r = schedule(retval)
return r | [
"def",
"schedule_remove",
"(",
"retval",
"=",
"None",
")",
":",
"_scheduler_remove",
"(",
"getcurrent",
"(",
")",
")",
"r",
"=",
"schedule",
"(",
"retval",
")",
"return",
"r"
] | https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/stackless.py#L489-L498 | |
googlearchive/pywebsocket | c459a5f9a04714e596726e876fcb46951c61a5f7 | mod_pywebsocket/_stream_hybi.py | python | Stream.receive_filtered_frame | (self) | return frame | Receives a frame and applies frame filters and message filters.
The frame to be received must satisfy following conditions:
- The frame is not fragmented.
- The opcode of the frame is TEXT or BINARY.
DO NOT USE this method except for testing purpose. | Receives a frame and applies frame filters and message filters.
The frame to be received must satisfy following conditions:
- The frame is not fragmented.
- The opcode of the frame is TEXT or BINARY. | [
"Receives",
"a",
"frame",
"and",
"applies",
"frame",
"filters",
"and",
"message",
"filters",
".",
"The",
"frame",
"to",
"be",
"received",
"must",
"satisfy",
"following",
"conditions",
":",
"-",
"The",
"frame",
"is",
"not",
"fragmented",
".",
"-",
"The",
"o... | def receive_filtered_frame(self):
"""Receives a frame and applies frame filters and message filters.
The frame to be received must satisfy following conditions:
- The frame is not fragmented.
- The opcode of the frame is TEXT or BINARY.
DO NOT USE this method except for testing purpose.
"""
frame = self._receive_frame_as_frame_object()
if not frame.fin:
raise InvalidFrameException(
'Segmented frames must not be received via '
'receive_filtered_frame()')
if (frame.opcode != common.OPCODE_TEXT and
frame.opcode != common.OPCODE_BINARY):
raise InvalidFrameException(
'Control frames must not be received via '
'receive_filtered_frame()')
for frame_filter in self._options.incoming_frame_filters:
frame_filter.filter(frame)
for message_filter in self._options.incoming_message_filters:
frame.payload = message_filter.filter(frame.payload)
return frame | [
"def",
"receive_filtered_frame",
"(",
"self",
")",
":",
"frame",
"=",
"self",
".",
"_receive_frame_as_frame_object",
"(",
")",
"if",
"not",
"frame",
".",
"fin",
":",
"raise",
"InvalidFrameException",
"(",
"'Segmented frames must not be received via '",
"'receive_filtere... | https://github.com/googlearchive/pywebsocket/blob/c459a5f9a04714e596726e876fcb46951c61a5f7/mod_pywebsocket/_stream_hybi.py#L461-L485 | |
facelessuser/ColorHelper | cfed17c35dbae4db49a14165ef222407c48a3014 | lib/coloraide/spaces/okhsv.py | python | Okhsv.s | (self, value: float) | Saturate or unsaturate the color by the given factor. | Saturate or unsaturate the color by the given factor. | [
"Saturate",
"or",
"unsaturate",
"the",
"color",
"by",
"the",
"given",
"factor",
"."
] | def s(self, value: float) -> None:
"""Saturate or unsaturate the color by the given factor."""
self._coords[1] = self._handle_input(value) | [
"def",
"s",
"(",
"self",
",",
"value",
":",
"float",
")",
"->",
"None",
":",
"self",
".",
"_coords",
"[",
"1",
"]",
"=",
"self",
".",
"_handle_input",
"(",
"value",
")"
] | https://github.com/facelessuser/ColorHelper/blob/cfed17c35dbae4db49a14165ef222407c48a3014/lib/coloraide/spaces/okhsv.py#L176-L179 | ||
ambujraj/hacktoberfest2018 | 53df2cac8b3404261131a873352ec4f2ffa3544d | MAC_changer/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/pyparsing.py | python | ParserElement.parseWithTabs | ( self ) | return self | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | [
"Overrides",
"default",
"behavior",
"to",
"expand",
"C",
"{",
"<TAB",
">",
"}",
"s",
"to",
"spaces",
"before",
"parsing",
"the",
"input",
"string",
".",
"Must",
"be",
"called",
"before",
"C",
"{",
"parseString",
"}",
"when",
"the",
"input",
"grammar",
"c... | def parseWithTabs( self ):
"""
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
"""
self.keepTabs = True
return self | [
"def",
"parseWithTabs",
"(",
"self",
")",
":",
"self",
".",
"keepTabs",
"=",
"True",
"return",
"self"
] | https://github.com/ambujraj/hacktoberfest2018/blob/53df2cac8b3404261131a873352ec4f2ffa3544d/MAC_changer/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/pyparsing.py#L2048-L2055 | |
ehmatthes/pcc | f555082df0f8268b8f269e59a99da8ed5013f749 | chapter_13/alien.py | python | Alien.update | (self) | Move the alien right or left. | Move the alien right or left. | [
"Move",
"the",
"alien",
"right",
"or",
"left",
"."
] | def update(self):
"""Move the alien right or left."""
self.x += (self.ai_settings.alien_speed_factor *
self.ai_settings.fleet_direction)
self.rect.x = self.x | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"x",
"+=",
"(",
"self",
".",
"ai_settings",
".",
"alien_speed_factor",
"*",
"self",
".",
"ai_settings",
".",
"fleet_direction",
")",
"self",
".",
"rect",
".",
"x",
"=",
"self",
".",
"x"
] | https://github.com/ehmatthes/pcc/blob/f555082df0f8268b8f269e59a99da8ed5013f749/chapter_13/alien.py#L32-L36 | ||
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | reviewboard/reviews/fields.py | python | BaseReviewRequestField.propagate_data | (self, review_request_details) | Propagate data in from source review request or draft.
By default, this loads only the field's value from a source review
request or draft and saves it as-is into the review request or draft
associated with the field. This can be overridden if you need to
propagate additional data elements.
This method is preferable to explicitly calling :py:meth:`load_value`
and :py:meth:`save_value` in series to propagate data from a source
into a field, because it allows for copying additional data elements
beyond only the field's value.
This function must use the ``review_request_details`` parameter instead
of the :py:attr:`review_request_details` attribute on the field.
Args:
review_request_details (reviewboard.reviews.models.base_review_request_details.BaseReviewRequestDetails):
The source review request or draft whose data is to be
propagated. | Propagate data in from source review request or draft. | [
"Propagate",
"data",
"in",
"from",
"source",
"review",
"request",
"or",
"draft",
"."
] | def propagate_data(self, review_request_details):
"""Propagate data in from source review request or draft.
By default, this loads only the field's value from a source review
request or draft and saves it as-is into the review request or draft
associated with the field. This can be overridden if you need to
propagate additional data elements.
This method is preferable to explicitly calling :py:meth:`load_value`
and :py:meth:`save_value` in series to propagate data from a source
into a field, because it allows for copying additional data elements
beyond only the field's value.
This function must use the ``review_request_details`` parameter instead
of the :py:attr:`review_request_details` attribute on the field.
Args:
review_request_details (reviewboard.reviews.models.base_review_request_details.BaseReviewRequestDetails):
The source review request or draft whose data is to be
propagated.
"""
self.save_value(self.load_value(review_request_details)) | [
"def",
"propagate_data",
"(",
"self",
",",
"review_request_details",
")",
":",
"self",
".",
"save_value",
"(",
"self",
".",
"load_value",
"(",
"review_request_details",
")",
")"
] | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/reviews/fields.py#L614-L635 | ||
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.py | python | HTMLTokenizer.afterDoctypePublicIdentifierState | (self) | return True | [] | def afterDoctypePublicIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.betweenDoctypePublicAndSystemIdentifiersState
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == '"':
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierDoubleQuotedState
elif data == "'":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierSingleQuotedState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True | [
"def",
"afterDoctypePublicIdentifierState",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"stream",
".",
"char",
"(",
")",
"if",
"data",
"in",
"spaceCharacters",
":",
"self",
".",
"state",
"=",
"self",
".",
"betweenDoctypePublicAndSystemIdentifiersState",
"el... | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.py#L1507-L1535 | |||
kaz-Anova/ensemble_amazon | 9019d8dcdfa3651b374e0216cc310255c2d660aa | amazon_main_xgboost.py | python | main | () | Fit models and make predictions.
We'll use one-hot encoding to transform our categorical features
into binary features.
y and X will be numpy array objects. | Fit models and make predictions.
We'll use one-hot encoding to transform our categorical features
into binary features.
y and X will be numpy array objects. | [
"Fit",
"models",
"and",
"make",
"predictions",
".",
"We",
"ll",
"use",
"one",
"-",
"hot",
"encoding",
"to",
"transform",
"our",
"categorical",
"features",
"into",
"binary",
"features",
".",
"y",
"and",
"X",
"will",
"be",
"numpy",
"array",
"objects",
"."
] | def main():
"""
Fit models and make predictions.
We'll use one-hot encoding to transform our categorical features
into binary features.
y and X will be numpy array objects.
"""
filename="main_xgboost" # nam prefix
#model = linear_model.LogisticRegression(C=3) # the classifier we'll use
model=xg.XGBoostClassifier(num_round=1000 ,nthread=25, eta=0.12, gamma=0.01,max_depth=12, min_child_weight=0.01, subsample=0.6,
colsample_bytree=0.7,objective='binary:logistic',seed=1)
# === load data in memory === #
print "loading data"
y, X = load_data('train.csv')
y_test, X_test = load_data('test.csv', use_labels=False)
# === one-hot encoding === #
# we want to encode the category IDs encountered both in
# the training and the test set, so we fit the encoder on both
encoder = preprocessing.OneHotEncoder()
encoder.fit(np.vstack((X, X_test)))
X = encoder.transform(X) # Returns a sparse matrix (see numpy.sparse)
X_test = encoder.transform(X_test)
# if you want to create new features, you'll need to compute them
# before the encoding, and append them to your dataset after
#create arrays to hold cv an dtest predictions
train_stacker=[ 0.0 for k in range (0,(X.shape[0])) ]
# === training & metrics === #
mean_auc = 0.0
bagging=20 # number of models trained with different seeds
n = 5 # number of folds in strattified cv
kfolder=StratifiedKFold(y, n_folds= n,shuffle=True, random_state=SEED)
i=0
for train_index, test_index in kfolder: # for each train and test pair of indices in the kfolder object
# creaning and validation sets
X_train, X_cv = X[train_index], X[test_index]
y_train, y_cv = np.array(y)[train_index], np.array(y)[test_index]
#print (" train size: %d. test size: %d, cols: %d " % ((X_train.shape[0]) ,(X_cv.shape[0]) ,(X_train.shape[1]) ))
# if you want to perform feature selection / hyperparameter
# optimization, this is where you want to do it
# train model and make predictions
preds=bagged_set(X_train,y_train,model, SEED , bagging, X_cv, update_seed=True)
# compute AUC metric for this CV fold
roc_auc = roc_auc_score(y_cv, preds)
print "AUC (fold %d/%d): %f" % (i + 1, n, roc_auc)
mean_auc += roc_auc
no=0
for real_index in test_index:
train_stacker[real_index]=(preds[no])
no+=1
i+=1
mean_auc/=n
print (" Average AUC: %f" % (mean_auc) )
print (" printing train datasets ")
printfilcsve(np.array(train_stacker), filename + ".train.csv")
# === Predictions === #
# When making predictions, retrain the model on the whole training set
preds=bagged_set(X, y,model, SEED, bagging, X_test, update_seed=True)
#create submission file
printfilcsve(np.array(preds), filename+ ".test.csv") | [
"def",
"main",
"(",
")",
":",
"filename",
"=",
"\"main_xgboost\"",
"# nam prefix",
"#model = linear_model.LogisticRegression(C=3) # the classifier we'll use",
"model",
"=",
"xg",
".",
"XGBoostClassifier",
"(",
"num_round",
"=",
"1000",
",",
"nthread",
"=",
"25",
",",
... | https://github.com/kaz-Anova/ensemble_amazon/blob/9019d8dcdfa3651b374e0216cc310255c2d660aa/amazon_main_xgboost.py#L77-L152 | ||
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v1_node_list.py | python | V1NodeList.items | (self, items) | Sets the items of this V1NodeList.
List of nodes # noqa: E501
:param items: The items of this V1NodeList. # noqa: E501
:type: list[V1Node] | Sets the items of this V1NodeList. | [
"Sets",
"the",
"items",
"of",
"this",
"V1NodeList",
"."
] | def items(self, items):
"""Sets the items of this V1NodeList.
List of nodes # noqa: E501
:param items: The items of this V1NodeList. # noqa: E501
:type: list[V1Node]
"""
if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501
raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501
self._items = items | [
"def",
"items",
"(",
"self",
",",
"items",
")",
":",
"if",
"self",
".",
"local_vars_configuration",
".",
"client_side_validation",
"and",
"items",
"is",
"None",
":",
"# noqa: E501",
"raise",
"ValueError",
"(",
"\"Invalid value for `items`, must not be `None`\"",
")",
... | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_node_list.py#L104-L115 | ||
markj3d/Red9_StudioPack | 1d40a8bf84c45ce7eaefdd9ccfa3cdbeb1471919 | core/Red9_Meta.py | python | MetaHUDNode.__compute__ | (self, attr, *args) | return getattr(self, attr) | The monitored attrs passs through this compute block before being draw. This
allows us to modify the data being draw when over-loading this class. | The monitored attrs passs through this compute block before being draw. This
allows us to modify the data being draw when over-loading this class. | [
"The",
"monitored",
"attrs",
"passs",
"through",
"this",
"compute",
"block",
"before",
"being",
"draw",
".",
"This",
"allows",
"us",
"to",
"modify",
"the",
"data",
"being",
"draw",
"when",
"over",
"-",
"loading",
"this",
"class",
"."
] | def __compute__(self, attr, *args):
'''
The monitored attrs passs through this compute block before being draw. This
allows us to modify the data being draw when over-loading this class.
'''
return getattr(self, attr) | [
"def",
"__compute__",
"(",
"self",
",",
"attr",
",",
"*",
"args",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"attr",
")"
] | https://github.com/markj3d/Red9_StudioPack/blob/1d40a8bf84c45ce7eaefdd9ccfa3cdbeb1471919/core/Red9_Meta.py#L5401-L5406 | |
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/gprof2dot/gprof2dot.py | python | XPerfParser.__init__ | (self, stream) | [] | def __init__(self, stream):
Parser.__init__(self)
self.stream = stream
self.profile = Profile()
self.profile[SAMPLES] = 0
self.column = {} | [
"def",
"__init__",
"(",
"self",
",",
"stream",
")",
":",
"Parser",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"stream",
"=",
"stream",
"self",
".",
"profile",
"=",
"Profile",
"(",
")",
"self",
".",
"profile",
"[",
"SAMPLES",
"]",
"=",
"0",
"se... | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/gprof2dot/gprof2dot.py#L1703-L1708 | ||||
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/fft/fftpack.py | python | irfft2 | (a, s=None, axes=(-2, -1)) | return irfftn(a, s, axes) | Compute the 2-dimensional inverse FFT of a real array.
Parameters
----------
a : array_like
The input array
s : sequence of ints, optional
Shape of the inverse FFT.
axes : sequence of ints, optional
The axes over which to compute the inverse fft.
Default is the last two axes.
Returns
-------
out : ndarray
The result of the inverse real 2-D FFT.
See Also
--------
irfftn : Compute the inverse of the N-dimensional FFT of real input.
Notes
-----
This is really `irfftn` with different defaults.
For more details see `irfftn`. | Compute the 2-dimensional inverse FFT of a real array. | [
"Compute",
"the",
"2",
"-",
"dimensional",
"inverse",
"FFT",
"of",
"a",
"real",
"array",
"."
] | def irfft2(a, s=None, axes=(-2, -1)):
"""
Compute the 2-dimensional inverse FFT of a real array.
Parameters
----------
a : array_like
The input array
s : sequence of ints, optional
Shape of the inverse FFT.
axes : sequence of ints, optional
The axes over which to compute the inverse fft.
Default is the last two axes.
Returns
-------
out : ndarray
The result of the inverse real 2-D FFT.
See Also
--------
irfftn : Compute the inverse of the N-dimensional FFT of real input.
Notes
-----
This is really `irfftn` with different defaults.
For more details see `irfftn`.
"""
return irfftn(a, s, axes) | [
"def",
"irfft2",
"(",
"a",
",",
"s",
"=",
"None",
",",
"axes",
"=",
"(",
"-",
"2",
",",
"-",
"1",
")",
")",
":",
"return",
"irfftn",
"(",
"a",
",",
"s",
",",
"axes",
")"
] | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/fft/fftpack.py#L1139-L1169 | |
google/budou | d45791a244e00d84f87da2a4678da2b63a9c232f | budou/nlapisegmenter.py | python | NLAPISegmenter._get_entities | (self, text, language='') | return result | Returns the list of entities retrieved from the given text.
Args:
text (str): Input text.
language (str, optional): Language code.
Returns:
List of entities. | Returns the list of entities retrieved from the given text. | [
"Returns",
"the",
"list",
"of",
"entities",
"retrieved",
"from",
"the",
"given",
"text",
"."
] | def _get_entities(self, text, language=''):
"""Returns the list of entities retrieved from the given text.
Args:
text (str): Input text.
language (str, optional): Language code.
Returns:
List of entities.
"""
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text,
},
'encodingType': 'UTF32',
}
if language:
body['document']['language'] = language
request = self.service.documents().analyzeEntities(body=body)
response = request.execute()
result = []
for entity in response.get('entities', []):
mentions = entity.get('mentions', [])
if not mentions:
continue
entity_text = mentions[0]['text']
offset = entity_text['beginOffset']
for word in entity_text['content'].split():
result.append({'content': word, 'beginOffset': offset})
offset += len(word)
return result | [
"def",
"_get_entities",
"(",
"self",
",",
"text",
",",
"language",
"=",
"''",
")",
":",
"body",
"=",
"{",
"'document'",
":",
"{",
"'type'",
":",
"'PLAIN_TEXT'",
",",
"'content'",
":",
"text",
",",
"}",
",",
"'encodingType'",
":",
"'UTF32'",
",",
"}",
... | https://github.com/google/budou/blob/d45791a244e00d84f87da2a4678da2b63a9c232f/budou/nlapisegmenter.py#L271-L303 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/physics/quantum/circuitplot.py | python | CreateCGate | (name, latexname=None) | return ControlledGate | Use a lexical closure to make a controlled gate. | Use a lexical closure to make a controlled gate. | [
"Use",
"a",
"lexical",
"closure",
"to",
"make",
"a",
"controlled",
"gate",
"."
] | def CreateCGate(name, latexname=None):
"""Use a lexical closure to make a controlled gate.
"""
if not latexname:
latexname = name
onequbitgate = CreateOneQubitGate(name, latexname)
def ControlledGate(ctrls,target):
return CGate(tuple(ctrls),onequbitgate(target))
return ControlledGate | [
"def",
"CreateCGate",
"(",
"name",
",",
"latexname",
"=",
"None",
")",
":",
"if",
"not",
"latexname",
":",
"latexname",
"=",
"name",
"onequbitgate",
"=",
"CreateOneQubitGate",
"(",
"name",
",",
"latexname",
")",
"def",
"ControlledGate",
"(",
"ctrls",
",",
... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/physics/quantum/circuitplot.py#L364-L372 | |
roclark/sportsipy | c19f545d3376d62ded6304b137dc69238ac620a9 | sportsipy/fb/roster.py | python | SquadPlayer.penalty_area_crosses | (self) | return self._penalty_area_crosses | Returns an ``int`` of the number of non-set piece crosses the player
made into the penalty area. | Returns an ``int`` of the number of non-set piece crosses the player
made into the penalty area. | [
"Returns",
"an",
"int",
"of",
"the",
"number",
"of",
"non",
"-",
"set",
"piece",
"crosses",
"the",
"player",
"made",
"into",
"the",
"penalty",
"area",
"."
] | def penalty_area_crosses(self):
"""
Returns an ``int`` of the number of non-set piece crosses the player
made into the penalty area.
"""
return self._penalty_area_crosses | [
"def",
"penalty_area_crosses",
"(",
"self",
")",
":",
"return",
"self",
".",
"_penalty_area_crosses"
] | https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/fb/roster.py#L1177-L1182 | |
OpenDroneMap/ODM | 4e2e4a6878d293103d4b9060421dac4db31b8b9e | opendm/tiles/gdal2tiles.py | python | GlobalGeodetic.ZoomForPixelSize | (self, pixelSize) | Maximal scaledown zoom of the pyramid closest to the pixelSize. | Maximal scaledown zoom of the pyramid closest to the pixelSize. | [
"Maximal",
"scaledown",
"zoom",
"of",
"the",
"pyramid",
"closest",
"to",
"the",
"pixelSize",
"."
] | def ZoomForPixelSize(self, pixelSize):
"Maximal scaledown zoom of the pyramid closest to the pixelSize."
for i in range(MAXZOOMLEVEL):
if pixelSize > self.Resolution(i):
if i != 0:
return i-1
else:
return 0 | [
"def",
"ZoomForPixelSize",
"(",
"self",
",",
"pixelSize",
")",
":",
"for",
"i",
"in",
"range",
"(",
"MAXZOOMLEVEL",
")",
":",
"if",
"pixelSize",
">",
"self",
".",
"Resolution",
"(",
"i",
")",
":",
"if",
"i",
"!=",
"0",
":",
"return",
"i",
"-",
"1",... | https://github.com/OpenDroneMap/ODM/blob/4e2e4a6878d293103d4b9060421dac4db31b8b9e/opendm/tiles/gdal2tiles.py#L395-L403 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-0.96/django/utils/translation/trans_real.py | python | check_for_language | (lang_code) | Checks whether there is a global language file for the given language code.
This is used to decide whether a user-provided language is available. This is
only used for language codes from either the cookies or session. | Checks whether there is a global language file for the given language code.
This is used to decide whether a user-provided language is available. This is
only used for language codes from either the cookies or session. | [
"Checks",
"whether",
"there",
"is",
"a",
"global",
"language",
"file",
"for",
"the",
"given",
"language",
"code",
".",
"This",
"is",
"used",
"to",
"decide",
"whether",
"a",
"user",
"-",
"provided",
"language",
"is",
"available",
".",
"This",
"is",
"only",
... | def check_for_language(lang_code):
"""
Checks whether there is a global language file for the given language code.
This is used to decide whether a user-provided language is available. This is
only used for language codes from either the cookies or session.
"""
from django.conf import settings
globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
if gettext_module.find('django', globalpath, [to_locale(lang_code)]) is not None:
return True
else:
return False | [
"def",
"check_for_language",
"(",
"lang_code",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"globalpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"sys",
".",
"modules",
"[",
"settings",
".",
"... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/utils/translation/trans_real.py#L296-L307 | ||
metabrainz/picard | 535bf8c7d9363ffc7abb3f69418ec11823c38118 | picard/ui/infodialog.py | python | TrackInfoDialog.__init__ | (self, track, parent=None) | [] | def __init__(self, track, parent=None):
super().__init__(track, parent)
self.setWindowTitle(_("Track Info")) | [
"def",
"__init__",
"(",
"self",
",",
"track",
",",
"parent",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"track",
",",
"parent",
")",
"self",
".",
"setWindowTitle",
"(",
"_",
"(",
"\"Track Info\"",
")",
")"
] | https://github.com/metabrainz/picard/blob/535bf8c7d9363ffc7abb3f69418ec11823c38118/picard/ui/infodialog.py#L382-L384 | ||||
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-modules/twisted/twisted/internet/_posixstdio.py | python | StandardIO.startReading | (self) | Compatibility only, don't use. Call resumeProducing. | Compatibility only, don't use. Call resumeProducing. | [
"Compatibility",
"only",
"don",
"t",
"use",
".",
"Call",
"resumeProducing",
"."
] | def startReading(self):
"""Compatibility only, don't use. Call resumeProducing."""
self.resumeProducing() | [
"def",
"startReading",
"(",
"self",
")",
":",
"self",
".",
"resumeProducing",
"(",
")"
] | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/internet/_posixstdio.py#L184-L186 | ||
sidewalklabs/s2sphere | d1d067e8c06e5fbaf0cc0158bade947b4a03a438 | s2sphere/sphere.py | python | LatLngRect.lo | (self) | return LatLng.from_angles(self.lat_lo(), self.lng_lo()) | [] | def lo(self):
return LatLng.from_angles(self.lat_lo(), self.lng_lo()) | [
"def",
"lo",
"(",
"self",
")",
":",
"return",
"LatLng",
".",
"from_angles",
"(",
"self",
".",
"lat_lo",
"(",
")",
",",
"self",
".",
"lng_lo",
"(",
")",
")"
] | https://github.com/sidewalklabs/s2sphere/blob/d1d067e8c06e5fbaf0cc0158bade947b4a03a438/s2sphere/sphere.py#L550-L551 | |||
cisco/mindmeld | 809c36112e9ea8019fe29d54d136ca14eb4fd8db | mindmeld/models/helpers.py | python | get_ngram | (tokens, start, length) | return " ".join(ngram_tokens) | Gets a ngram from a list of tokens.
Handles out-of-bounds token positions with a special character.
Args:
tokens (list of str): Word tokens.
start (int): The index of the desired ngram's start position.
length (int): The length of the n-gram, e.g. 1 for unigram, etc.
Returns:
(str) An n-gram in the input token list. | Gets a ngram from a list of tokens. | [
"Gets",
"a",
"ngram",
"from",
"a",
"list",
"of",
"tokens",
"."
] | def get_ngram(tokens, start, length):
"""Gets a ngram from a list of tokens.
Handles out-of-bounds token positions with a special character.
Args:
tokens (list of str): Word tokens.
start (int): The index of the desired ngram's start position.
length (int): The length of the n-gram, e.g. 1 for unigram, etc.
Returns:
(str) An n-gram in the input token list.
"""
ngram_tokens = []
for index in range(start, start + length):
token = (
OUT_OF_BOUNDS_TOKEN if index < 0 or index >= len(tokens) else tokens[index]
)
ngram_tokens.append(token)
return " ".join(ngram_tokens) | [
"def",
"get_ngram",
"(",
"tokens",
",",
"start",
",",
"length",
")",
":",
"ngram_tokens",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"start",
",",
"start",
"+",
"length",
")",
":",
"token",
"=",
"(",
"OUT_OF_BOUNDS_TOKEN",
"if",
"index",
"<",
... | https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/models/helpers.py#L310-L330 | |
kedro-org/kedro | e78990c6b606a27830f0d502afa0f639c0830950 | kedro/framework/context/context.py | python | load_context | (project_path: Union[str, Path], **kwargs) | return context | Loads the KedroContext object of a Kedro Project.
This is the default way to load the KedroContext object for normal workflows such as
CLI, Jupyter Notebook, Plugins, etc. It assumes the following project structure
under the given project_path::
<project_path>
|__ <src_dir>
|__ pyproject.toml
The name of the <scr_dir> is `src` by default. The `pyproject.toml` file is used
for project metadata. Kedro configuration should be under `[tool.kedro]` section.
Args:
project_path: Path to the Kedro project.
**kwargs: Optional kwargs for ``KedroContext`` class.
Returns:
Instance of ``KedroContext`` class defined in Kedro project.
Raises:
KedroContextError: `pyproject.toml` was not found or the `[tool.kedro]` section
is missing, or loaded context has package conflict. | Loads the KedroContext object of a Kedro Project.
This is the default way to load the KedroContext object for normal workflows such as
CLI, Jupyter Notebook, Plugins, etc. It assumes the following project structure
under the given project_path:: | [
"Loads",
"the",
"KedroContext",
"object",
"of",
"a",
"Kedro",
"Project",
".",
"This",
"is",
"the",
"default",
"way",
"to",
"load",
"the",
"KedroContext",
"object",
"for",
"normal",
"workflows",
"such",
"as",
"CLI",
"Jupyter",
"Notebook",
"Plugins",
"etc",
".... | def load_context(project_path: Union[str, Path], **kwargs) -> KedroContext:
"""Loads the KedroContext object of a Kedro Project.
This is the default way to load the KedroContext object for normal workflows such as
CLI, Jupyter Notebook, Plugins, etc. It assumes the following project structure
under the given project_path::
<project_path>
|__ <src_dir>
|__ pyproject.toml
The name of the <scr_dir> is `src` by default. The `pyproject.toml` file is used
for project metadata. Kedro configuration should be under `[tool.kedro]` section.
Args:
project_path: Path to the Kedro project.
**kwargs: Optional kwargs for ``KedroContext`` class.
Returns:
Instance of ``KedroContext`` class defined in Kedro project.
Raises:
KedroContextError: `pyproject.toml` was not found or the `[tool.kedro]` section
is missing, or loaded context has package conflict.
"""
warn(
"`kedro.framework.context.load_context` is now deprecated in favour of "
"`KedroSession.load_context` and will be removed in Kedro 0.18.0.",
DeprecationWarning,
)
project_path = Path(project_path).expanduser().resolve()
metadata = _get_project_metadata(project_path)
context_class = settings.CONTEXT_CLASS
# update kwargs with env from the environment variable
# (defaults to None if not set)
# need to do this because some CLI command (e.g `kedro run`) defaults to
# passing in `env=None`
kwargs["env"] = kwargs.get("env") or os.getenv("KEDRO_ENV")
context = context_class(
package_name=metadata.package_name, project_path=project_path, **kwargs
)
return context | [
"def",
"load_context",
"(",
"project_path",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"*",
"*",
"kwargs",
")",
"->",
"KedroContext",
":",
"warn",
"(",
"\"`kedro.framework.context.load_context` is now deprecated in favour of \"",
"\"`KedroSession.load_context` and w... | https://github.com/kedro-org/kedro/blob/e78990c6b606a27830f0d502afa0f639c0830950/kedro/framework/context/context.py#L680-L722 | |
qiucheng025/zao- | 3a5edf3607b3a523f95746bc69b688090c76d89a | lib/gpu_stats.py | python | GPUStats.get_active_devices | (self) | Return list of active Nvidia devices | Return list of active Nvidia devices | [
"Return",
"list",
"of",
"active",
"Nvidia",
"devices"
] | def get_active_devices(self):
""" Return list of active Nvidia devices """
if self.plaid is not None:
self.active_devices = self.plaid.active_devices
else:
devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
if self.device_count == 0:
self.active_devices = list()
elif devices is not None:
self.active_devices = [int(i) for i in devices.split(",") if devices]
else:
self.active_devices = list(range(self.device_count))
if self.logger:
self.logger.debug("Active GPU Devices: %s", self.active_devices) | [
"def",
"get_active_devices",
"(",
"self",
")",
":",
"if",
"self",
".",
"plaid",
"is",
"not",
"None",
":",
"self",
".",
"active_devices",
"=",
"self",
".",
"plaid",
".",
"active_devices",
"else",
":",
"devices",
"=",
"os",
".",
"environ",
".",
"get",
"(... | https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/lib/gpu_stats.py#L138-L151 | ||
pventuzelo/octopus | e8b8c5a9d5f6d9c63605afe9ef1528ab481ec983 | octopus/platforms/ETH/explorer.py | python | EthereumExplorerRPC.db_getHex | (self, db_name, key) | return self.call('db_getHex', [db_name, key]) | https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex
TESTED | https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"ethereum",
"/",
"wiki",
"/",
"wiki",
"/",
"JSON",
"-",
"RPC#db_gethex"
] | def db_getHex(self, db_name, key):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex
TESTED
"""
warnings.warn('deprecated', DeprecationWarning)
return self.call('db_getHex', [db_name, key]) | [
"def",
"db_getHex",
"(",
"self",
",",
"db_name",
",",
"key",
")",
":",
"warnings",
".",
"warn",
"(",
"'deprecated'",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"call",
"(",
"'db_getHex'",
",",
"[",
"db_name",
",",
"key",
"]",
")"
] | https://github.com/pventuzelo/octopus/blob/e8b8c5a9d5f6d9c63605afe9ef1528ab481ec983/octopus/platforms/ETH/explorer.py#L1116-L1123 | |
qutip/qutip | 52d01da181a21b810c3407812c670f35fdc647e8 | qutip/random_objects.py | python | rand_kraus_map | (N, dims=None, seed=None) | return list(map(lambda x: Qobj(inpt=x, dims=dims), oper_list)) | Creates a random CPTP map on an N-dimensional Hilbert space in Kraus
form.
Parameters
----------
N : int
Length of input/output density matrix.
dims : list
Dimensions of quantum object. Used for specifying
tensor structure. Default is dims=[[N],[N]].
Returns
-------
oper_list : list of qobj
N^2 x N x N qobj operators. | Creates a random CPTP map on an N-dimensional Hilbert space in Kraus
form. | [
"Creates",
"a",
"random",
"CPTP",
"map",
"on",
"an",
"N",
"-",
"dimensional",
"Hilbert",
"space",
"in",
"Kraus",
"form",
"."
] | def rand_kraus_map(N, dims=None, seed=None):
"""
Creates a random CPTP map on an N-dimensional Hilbert space in Kraus
form.
Parameters
----------
N : int
Length of input/output density matrix.
dims : list
Dimensions of quantum object. Used for specifying
tensor structure. Default is dims=[[N],[N]].
Returns
-------
oper_list : list of qobj
N^2 x N x N qobj operators.
"""
if dims:
_check_dims(dims, N, N)
# Random unitary (Stinespring Dilation)
orthog_cols = rand_unitary(N ** 3, seed=seed).full()[:, :N]
oper_list = np.reshape(orthog_cols, (N ** 2, N, N))
return list(map(lambda x: Qobj(inpt=x, dims=dims), oper_list)) | [
"def",
"rand_kraus_map",
"(",
"N",
",",
"dims",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"if",
"dims",
":",
"_check_dims",
"(",
"dims",
",",
"N",
",",
"N",
")",
"# Random unitary (Stinespring Dilation)",
"orthog_cols",
"=",
"rand_unitary",
"(",
"N"... | https://github.com/qutip/qutip/blob/52d01da181a21b810c3407812c670f35fdc647e8/qutip/random_objects.py#L485-L512 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/webapp2-2.5.2/webapp2_extras/sessions.py | python | get_store | (factory=SessionStore, key=_registry_key, request=None) | return store | Returns an instance of :class:`SessionStore` from the request registry.
It'll try to get it from the current request registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`SessionStore` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param request:
A :class:`webapp2.Request` instance used to store the instance. The
active request is used if it is not set. | Returns an instance of :class:`SessionStore` from the request registry. | [
"Returns",
"an",
"instance",
"of",
":",
"class",
":",
"SessionStore",
"from",
"the",
"request",
"registry",
"."
] | def get_store(factory=SessionStore, key=_registry_key, request=None):
"""Returns an instance of :class:`SessionStore` from the request registry.
It'll try to get it from the current request registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`SessionStore` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param request:
A :class:`webapp2.Request` instance used to store the instance. The
active request is used if it is not set.
"""
request = request or webapp2.get_request()
store = request.registry.get(key)
if not store:
store = request.registry[key] = factory(request)
return store | [
"def",
"get_store",
"(",
"factory",
"=",
"SessionStore",
",",
"key",
"=",
"_registry_key",
",",
"request",
"=",
"None",
")",
":",
"request",
"=",
"request",
"or",
"webapp2",
".",
"get_request",
"(",
")",
"store",
"=",
"request",
".",
"registry",
".",
"ge... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/webapp2-2.5.2/webapp2_extras/sessions.py#L434-L456 | |
joschabach/micropsi2 | 74a2642d20da9da1d64acc5e4c11aeabee192a27 | micropsi_core/runtime.py | python | set_node_state | (nodenet_uid, node_uid, state) | return True | Sets the state of the given node to the given state | Sets the state of the given node to the given state | [
"Sets",
"the",
"state",
"of",
"the",
"given",
"node",
"to",
"the",
"given",
"state"
] | def set_node_state(nodenet_uid, node_uid, state):
""" Sets the state of the given node to the given state"""
node = get_nodenet(nodenet_uid).get_node(node_uid)
for key in state:
node.set_state(key, state[key])
return True | [
"def",
"set_node_state",
"(",
"nodenet_uid",
",",
"node_uid",
",",
"state",
")",
":",
"node",
"=",
"get_nodenet",
"(",
"nodenet_uid",
")",
".",
"get_node",
"(",
"node_uid",
")",
"for",
"key",
"in",
"state",
":",
"node",
".",
"set_state",
"(",
"key",
",",... | https://github.com/joschabach/micropsi2/blob/74a2642d20da9da1d64acc5e4c11aeabee192a27/micropsi_core/runtime.py#L1069-L1074 | |
treeio/treeio | bae3115f4015aad2cbc5ab45572232ceec990495 | treeio/projects/views.py | python | task_edit | (request, task_id, response_format='html') | return render_to_response('projects/task_edit', context,
context_instance=RequestContext(request), response_format=response_format) | Task edit page | Task edit page | [
"Task",
"edit",
"page"
] | def task_edit(request, task_id, response_format='html'):
"""Task edit page"""
task = get_object_or_404(Task, pk=task_id)
if not request.user.profile.has_permission(task, mode='w'):
return user_denied(request, message="You don't have access to this Task")
if request.POST:
if 'cancel' not in request.POST:
form = TaskForm(
request.user.profile, None, None, None, request.POST, instance=task)
if form.is_valid():
task = form.save()
return HttpResponseRedirect(reverse('projects_task_view', args=[task.id]))
else:
return HttpResponseRedirect(reverse('projects_task_view', args=[task.id]))
else:
form = TaskForm(
request.user.profile, None, None, None, instance=task)
context = _get_default_context(request)
context.update({'form': form,
'task': task})
return render_to_response('projects/task_edit', context,
context_instance=RequestContext(request), response_format=response_format) | [
"def",
"task_edit",
"(",
"request",
",",
"task_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"task",
"=",
"get_object_or_404",
"(",
"Task",
",",
"pk",
"=",
"task_id",
")",
"if",
"not",
"request",
".",
"user",
".",
"profile",
".",
"has_permission",
... | https://github.com/treeio/treeio/blob/bae3115f4015aad2cbc5ab45572232ceec990495/treeio/projects/views.py#L806-L831 | |
open-cogsci/OpenSesame | c4a3641b097a80a76937edbd8c365f036bcc9705 | libqtopensesame/widgets/pool_widget.py | python | pool_widget.set_view | (self) | desc:
Sets the viewmode (list/ icons) based on the gui control. | desc:
Sets the viewmode (list/ icons) based on the gui control. | [
"desc",
":",
"Sets",
"the",
"viewmode",
"(",
"list",
"/",
"icons",
")",
"based",
"on",
"the",
"gui",
"control",
"."
] | def set_view(self):
"""
desc:
Sets the viewmode (list/ icons) based on the gui control.
"""
if self.ui.combobox_view.currentIndex() == 0:
self.ui.list_pool.setViewMode(QtWidgets.QListView.ListMode)
else:
self.ui.list_pool.setViewMode(QtWidgets.QListView.IconMode) | [
"def",
"set_view",
"(",
"self",
")",
":",
"if",
"self",
".",
"ui",
".",
"combobox_view",
".",
"currentIndex",
"(",
")",
"==",
"0",
":",
"self",
".",
"ui",
".",
"list_pool",
".",
"setViewMode",
"(",
"QtWidgets",
".",
"QListView",
".",
"ListMode",
")",
... | https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libqtopensesame/widgets/pool_widget.py#L75-L85 | ||
mypaint/mypaint | 90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33 | lib/fill_common.py | python | adjacent | (tile_coord) | return nine_grid(tile_coord)[1:] | Return the coordinates adjacent to the input coordinate.
Return coordinates of the neighbourhood
of the input coordinate, in the following order:
7 0 4
3 1
6 2 5 | Return the coordinates adjacent to the input coordinate. | [
"Return",
"the",
"coordinates",
"adjacent",
"to",
"the",
"input",
"coordinate",
"."
] | def adjacent(tile_coord):
""" Return the coordinates adjacent to the input coordinate.
Return coordinates of the neighbourhood
of the input coordinate, in the following order:
7 0 4
3 1
6 2 5
"""
return nine_grid(tile_coord)[1:] | [
"def",
"adjacent",
"(",
"tile_coord",
")",
":",
"return",
"nine_grid",
"(",
"tile_coord",
")",
"[",
"1",
":",
"]"
] | https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/lib/fill_common.py#L59-L69 | |
DHI-GRAS/terracotta | 04f1019ee47c565dbf068ee2a6d49f05080da698 | terracotta/drivers/__init__.py | python | get_driver | (url_or_path: URLOrPathType, provider: str = None) | return _DRIVER_CACHE[cache_key] | Retrieve Terracotta driver instance for the given path.
This function always returns the same instance for identical inputs.
Warning:
Always retrieve Driver instances through this function instead of
instantiating them directly to prevent caching issues.
Arguments:
url_or_path: A path identifying the database to connect to.
The expected format depends on the driver provider.
provider: Driver provider to use (one of sqlite, sqlite-remote, mysql;
default: auto-detect).
Example:
>>> import terracotta as tc
>>> tc.get_driver('tc.sqlite')
SQLiteDriver('/home/terracotta/tc.sqlite')
>>> tc.get_driver('mysql://root@localhost/tc')
MySQLDriver('mysql://root@localhost:3306/tc')
>>> # pass provider if path is given in a non-standard way
>>> tc.get_driver('root@localhost/tc', provider='mysql')
MySQLDriver('mysql://root@localhost:3306/tc') | Retrieve Terracotta driver instance for the given path. | [
"Retrieve",
"Terracotta",
"driver",
"instance",
"for",
"the",
"given",
"path",
"."
] | def get_driver(url_or_path: URLOrPathType, provider: str = None) -> Driver:
"""Retrieve Terracotta driver instance for the given path.
This function always returns the same instance for identical inputs.
Warning:
Always retrieve Driver instances through this function instead of
instantiating them directly to prevent caching issues.
Arguments:
url_or_path: A path identifying the database to connect to.
The expected format depends on the driver provider.
provider: Driver provider to use (one of sqlite, sqlite-remote, mysql;
default: auto-detect).
Example:
>>> import terracotta as tc
>>> tc.get_driver('tc.sqlite')
SQLiteDriver('/home/terracotta/tc.sqlite')
>>> tc.get_driver('mysql://root@localhost/tc')
MySQLDriver('mysql://root@localhost:3306/tc')
>>> # pass provider if path is given in a non-standard way
>>> tc.get_driver('root@localhost/tc', provider='mysql')
MySQLDriver('mysql://root@localhost:3306/tc')
"""
if provider is None: # try and auto-detect
provider = auto_detect_provider(url_or_path)
if isinstance(url_or_path, Path) or provider == 'sqlite':
url_or_path = str(Path(url_or_path).resolve())
DriverClass = load_driver(provider)
normalized_path = DriverClass._normalize_path(url_or_path)
cache_key = (normalized_path, provider)
if cache_key not in _DRIVER_CACHE:
_DRIVER_CACHE[cache_key] = DriverClass(url_or_path)
return _DRIVER_CACHE[cache_key] | [
"def",
"get_driver",
"(",
"url_or_path",
":",
"URLOrPathType",
",",
"provider",
":",
"str",
"=",
"None",
")",
"->",
"Driver",
":",
"if",
"provider",
"is",
"None",
":",
"# try and auto-detect",
"provider",
"=",
"auto_detect_provider",
"(",
"url_or_path",
")",
"... | https://github.com/DHI-GRAS/terracotta/blob/04f1019ee47c565dbf068ee2a6d49f05080da698/terracotta/drivers/__init__.py#L47-L89 | |
JacquesLucke/animation_nodes | b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1 | animation_nodes/nodes/gpencil/gp_stroke_from_points.py | python | GPStrokeFromPointsNode.execute | (self, vertices, strengths, pressures, uvRotations, vertexColors, lineWidth, hardness,
useCyclic, startCapMode, endCapMode, vertexColorFill, materialIndex, displayMode) | return GPStroke(vertices, strengths, pressures, uvRotations, vertexColors, lineWidth, hardness,
useCyclic, startCapMode, endCapMode, vertexColorFill, materialIndex, displayMode) | [] | def execute(self, vertices, strengths, pressures, uvRotations, vertexColors, lineWidth, hardness,
useCyclic, startCapMode, endCapMode, vertexColorFill, materialIndex, displayMode):
amount = len(vertices)
strengths = FloatList.fromValues(VirtualDoubleList.create(strengths, 1).materialize(amount))
pressures = FloatList.fromValues(VirtualDoubleList.create(pressures, 1).materialize(amount))
uvRotations = FloatList.fromValues(VirtualDoubleList.create(uvRotations, 0).materialize(amount))
vertexColors = VirtualColorList.create(vertexColors, Color((0, 0, 0, 0))).materialize(amount)
if startCapMode not in ['ROUND', 'FLAT']:
self.raiseErrorMessage("The Start Cap Mode is invalid. \n\nPossible values for 'Start Cap Mode' are: 'ROUND', 'FLAT'")
if endCapMode not in ['ROUND', 'FLAT']:
self.raiseErrorMessage("The End Cap Mode is invalid. \n\nPossible values for 'End Cap Mode' are: 'ROUND', 'FLAT'")
if displayMode not in ['SCREEN', '3DSPACE', '2DSPACE', '2DIMAGE']:
self.raiseErrorMessage("The Display Mode is invalid. \n\nPossible values for 'Display Mode' are: 'SCREEN', '3DSPACE', '2DSPACE', '2DIMAGE'")
return GPStroke(vertices, strengths, pressures, uvRotations, vertexColors, lineWidth, hardness,
useCyclic, startCapMode, endCapMode, vertexColorFill, materialIndex, displayMode) | [
"def",
"execute",
"(",
"self",
",",
"vertices",
",",
"strengths",
",",
"pressures",
",",
"uvRotations",
",",
"vertexColors",
",",
"lineWidth",
",",
"hardness",
",",
"useCyclic",
",",
"startCapMode",
",",
"endCapMode",
",",
"vertexColorFill",
",",
"materialIndex"... | https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/gpencil/gp_stroke_from_points.py#L35-L52 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/celery/events/snapshot.py | python | Polaroid.__init__ | (self, state, freq=1.0, maxrate=None,
cleanup_freq=3600.0, timer=None, app=None) | [] | def __init__(self, state, freq=1.0, maxrate=None,
cleanup_freq=3600.0, timer=None, app=None):
self.app = app_or_default(app)
self.state = state
self.freq = freq
self.cleanup_freq = cleanup_freq
self.timer = timer or self.timer or Timer()
self.logger = logger
self.maxrate = maxrate and TokenBucket(rate(maxrate)) | [
"def",
"__init__",
"(",
"self",
",",
"state",
",",
"freq",
"=",
"1.0",
",",
"maxrate",
"=",
"None",
",",
"cleanup_freq",
"=",
"3600.0",
",",
"timer",
"=",
"None",
",",
"app",
"=",
"None",
")",
":",
"self",
".",
"app",
"=",
"app_or_default",
"(",
"a... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/events/snapshot.py#L36-L44 | ||||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/antlr3/antlr3/recognizers.py | python | BaseRecognizer.getNumberOfSyntaxErrors | (self) | return self._state.syntaxErrors | Get number of recognition errors (lexer, parser, tree parser). Each
recognizer tracks its own number. So parser and lexer each have
separate count. Does not count the spurious errors found between
an error and next valid token match
See also reportError() | Get number of recognition errors (lexer, parser, tree parser). Each
recognizer tracks its own number. So parser and lexer each have
separate count. Does not count the spurious errors found between
an error and next valid token match | [
"Get",
"number",
"of",
"recognition",
"errors",
"(",
"lexer",
"parser",
"tree",
"parser",
")",
".",
"Each",
"recognizer",
"tracks",
"its",
"own",
"number",
".",
"So",
"parser",
"and",
"lexer",
"each",
"have",
"separate",
"count",
".",
"Does",
"not",
"count... | def getNumberOfSyntaxErrors(self):
"""
Get number of recognition errors (lexer, parser, tree parser). Each
recognizer tracks its own number. So parser and lexer each have
separate count. Does not count the spurious errors found between
an error and next valid token match
See also reportError()
"""
return self._state.syntaxErrors | [
"def",
"getNumberOfSyntaxErrors",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state",
".",
"syntaxErrors"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/antlr3/antlr3/recognizers.py#L446-L455 | |
gwastro/pycbc | 1e1c85534b9dba8488ce42df693230317ca63dea | pycbc/population/rates_functions.py | python | prob_imf | (m1, m2, s1z, s2z, **kwargs) | return p_m1_m2/2. | Return probability density for power-law
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1(Not in use currently)
s2z:
Aligned spin 2(Not in use currently)
**kwargs: string
Keyword arguments as model parameters
Returns
-------
p_m1_m2: array
the probability density for m1, m2 pair | Return probability density for power-law
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1(Not in use currently)
s2z:
Aligned spin 2(Not in use currently)
**kwargs: string
Keyword arguments as model parameters | [
"Return",
"probability",
"density",
"for",
"power",
"-",
"law",
"Parameters",
"----------",
"m1",
":",
"array",
"Component",
"masses",
"1",
"m2",
":",
"array",
"Component",
"masses",
"2",
"s1z",
":",
"array",
"Aligned",
"spin",
"1",
"(",
"Not",
"in",
"use"... | def prob_imf(m1, m2, s1z, s2z, **kwargs):
''' Return probability density for power-law
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1(Not in use currently)
s2z:
Aligned spin 2(Not in use currently)
**kwargs: string
Keyword arguments as model parameters
Returns
-------
p_m1_m2: array
the probability density for m1, m2 pair
'''
min_mass = kwargs.get('min_mass', 5.)
max_mass = kwargs.get('max_mass', 95.)
alpha = kwargs.get('alpha', -2.35)
max_mtotal = min_mass + max_mass
m1, m2 = np.array(m1), np.array(m2)
C_imf = max_mass**(alpha + 1)/(alpha + 1)
C_imf -= min_mass**(alpha + 1)/(alpha + 1)
xx = np.minimum(m1, m2)
m1 = np.maximum(m1, m2)
m2 = xx
bound = np.sign(max_mtotal - m1 - m2)
bound += np.sign(max_mass - m1) * np.sign(m2 - min_mass)
idx = np.where(bound != 2)
p_m1_m2 = np.zeros_like(m1)
idx = np.where(m1 <= max_mtotal/2.)
p_m1_m2[idx] = (1./C_imf) * m1[idx]**alpha /(m1[idx] - min_mass)
idx = np.where(m1 > max_mtotal/2.)
p_m1_m2[idx] = (1./C_imf) * m1[idx]**alpha /(max_mass - m1[idx])
p_m1_m2[idx] = 0
return p_m1_m2/2. | [
"def",
"prob_imf",
"(",
"m1",
",",
"m2",
",",
"s1z",
",",
"s2z",
",",
"*",
"*",
"kwargs",
")",
":",
"min_mass",
"=",
"kwargs",
".",
"get",
"(",
"'min_mass'",
",",
"5.",
")",
"max_mass",
"=",
"kwargs",
".",
"get",
"(",
"'max_mass'",
",",
"95.",
")... | https://github.com/gwastro/pycbc/blob/1e1c85534b9dba8488ce42df693230317ca63dea/pycbc/population/rates_functions.py#L260-L305 | |
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/chat/__init__.py | python | Chat.v1 | (self) | return self._v1 | :returns: Version v1 of chat
:rtype: twilio.rest.chat.v1.V1 | :returns: Version v1 of chat
:rtype: twilio.rest.chat.v1.V1 | [
":",
"returns",
":",
"Version",
"v1",
"of",
"chat",
":",
"rtype",
":",
"twilio",
".",
"rest",
".",
"chat",
".",
"v1",
".",
"V1"
] | def v1(self):
"""
:returns: Version v1 of chat
:rtype: twilio.rest.chat.v1.V1
"""
if self._v1 is None:
self._v1 = V1(self)
return self._v1 | [
"def",
"v1",
"(",
"self",
")",
":",
"if",
"self",
".",
"_v1",
"is",
"None",
":",
"self",
".",
"_v1",
"=",
"V1",
"(",
"self",
")",
"return",
"self",
".",
"_v1"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/chat/__init__.py#L32-L39 | |
donnemartin/gitsome | d7c57abc7cb66e9c910a844f15d4536866da3310 | xonsh/proc.py | python | CommandPipeline._prev_procs_done | (self) | return False if any_running else (len(self) > 1) | Boolean for if all previous processes have completed. If there
is only a single process in the pipeline, this returns False. | Boolean for if all previous processes have completed. If there
is only a single process in the pipeline, this returns False. | [
"Boolean",
"for",
"if",
"all",
"previous",
"processes",
"have",
"completed",
".",
"If",
"there",
"is",
"only",
"a",
"single",
"process",
"in",
"the",
"pipeline",
"this",
"returns",
"False",
"."
] | def _prev_procs_done(self):
"""Boolean for if all previous processes have completed. If there
is only a single process in the pipeline, this returns False.
"""
any_running = False
for s, p in zip(self.specs[:-1], self.procs[:-1]):
if p.poll() is None:
any_running = True
continue
self._safe_close(s.stdin)
self._safe_close(s.stdout)
self._safe_close(s.stderr)
if p is None:
continue
self._safe_close(p.stdin)
self._safe_close(p.stdout)
self._safe_close(p.stderr)
return False if any_running else (len(self) > 1) | [
"def",
"_prev_procs_done",
"(",
"self",
")",
":",
"any_running",
"=",
"False",
"for",
"s",
",",
"p",
"in",
"zip",
"(",
"self",
".",
"specs",
"[",
":",
"-",
"1",
"]",
",",
"self",
".",
"procs",
"[",
":",
"-",
"1",
"]",
")",
":",
"if",
"p",
"."... | https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/proc.py#L2168-L2185 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/setuptools/extern/__init__.py | python | VendorImporter.install | (self) | Install this importer into sys.meta_path if not already present. | Install this importer into sys.meta_path if not already present. | [
"Install",
"this",
"importer",
"into",
"sys",
".",
"meta_path",
"if",
"not",
"already",
"present",
"."
] | def install(self):
"""
Install this importer into sys.meta_path if not already present.
"""
if self not in sys.meta_path:
sys.meta_path.append(self) | [
"def",
"install",
"(",
"self",
")",
":",
"if",
"self",
"not",
"in",
"sys",
".",
"meta_path",
":",
"sys",
".",
"meta_path",
".",
"append",
"(",
"self",
")"
] | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/setuptools/extern/__init__.py#L64-L69 | ||
wxWidgets/Phoenix | b2199e299a6ca6d866aa6f3d0888499136ead9d6 | wx/lib/agw/shortcuteditor.py | python | ListShortcut.SetFilter | (self, filter='') | Sets the `filter` string against all the shortcuts in the :class:`ListShortcut` are matched.
:param string `filter`: a string to match. | Sets the `filter` string against all the shortcuts in the :class:`ListShortcut` are matched. | [
"Sets",
"the",
"filter",
"string",
"against",
"all",
"the",
"shortcuts",
"in",
"the",
":",
"class",
":",
"ListShortcut",
"are",
"matched",
"."
] | def SetFilter(self, filter=''):
"""
Sets the `filter` string against all the shortcuts in the :class:`ListShortcut` are matched.
:param string `filter`: a string to match.
"""
self.filter = filter
self.manager.ResetVisibility()
self.manager.Match(filter)
self.RecreateTree() | [
"def",
"SetFilter",
"(",
"self",
",",
"filter",
"=",
"''",
")",
":",
"self",
".",
"filter",
"=",
"filter",
"self",
".",
"manager",
".",
"ResetVisibility",
"(",
")",
"self",
".",
"manager",
".",
"Match",
"(",
"filter",
")",
"self",
".",
"RecreateTree",
... | https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/shortcuteditor.py#L2135-L2146 | ||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/proxy/esxdatacenter.py | python | init | (opts) | return True | This function gets called when the proxy starts up.
All login details are cached. | This function gets called when the proxy starts up.
All login details are cached. | [
"This",
"function",
"gets",
"called",
"when",
"the",
"proxy",
"starts",
"up",
".",
"All",
"login",
"details",
"are",
"cached",
"."
] | def init(opts):
"""
This function gets called when the proxy starts up.
All login details are cached.
"""
log.debug("Initting esxdatacenter proxy module in process %s", os.getpid())
log.trace("Validating esxdatacenter proxy input")
schema = EsxdatacenterProxySchema.serialize()
log.trace("schema = %s", schema)
proxy_conf = merge(opts.get("proxy", {}), __pillar__.get("proxy", {}))
log.trace("proxy_conf = %s", proxy_conf)
try:
jsonschema.validate(proxy_conf, schema)
except jsonschema.exceptions.ValidationError as exc:
raise salt.exceptions.InvalidConfigError(exc)
# Save mandatory fields in cache
for key in ("vcenter", "datacenter", "mechanism"):
DETAILS[key] = proxy_conf[key]
# Additional validation
if DETAILS["mechanism"] == "userpass":
if "username" not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
"Mechanism is set to 'userpass', but no "
"'username' key found in proxy config."
)
if "passwords" not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
"Mechanism is set to 'userpass', but no "
"'passwords' key found in proxy config."
)
for key in ("username", "passwords"):
DETAILS[key] = proxy_conf[key]
else:
if "domain" not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
"Mechanism is set to 'sspi', but no 'domain' key found in proxy config."
)
if "principal" not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
"Mechanism is set to 'sspi', but no "
"'principal' key found in proxy config."
)
for key in ("domain", "principal"):
DETAILS[key] = proxy_conf[key]
# Save optional
DETAILS["protocol"] = proxy_conf.get("protocol")
DETAILS["port"] = proxy_conf.get("port")
# Test connection
if DETAILS["mechanism"] == "userpass":
# Get the correct login details
log.debug(
"Retrieving credentials and testing vCenter connection for "
"mehchanism 'userpass'"
)
try:
username, password = find_credentials()
DETAILS["password"] = password
except salt.exceptions.SaltSystemExit as err:
log.critical("Error: %s", err)
return False
return True | [
"def",
"init",
"(",
"opts",
")",
":",
"log",
".",
"debug",
"(",
"\"Initting esxdatacenter proxy module in process %s\"",
",",
"os",
".",
"getpid",
"(",
")",
")",
"log",
".",
"trace",
"(",
"\"Validating esxdatacenter proxy input\"",
")",
"schema",
"=",
"Esxdatacent... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/proxy/esxdatacenter.py#L187-L251 | |
xtiankisutsa/MARA_Framework | ac4ac88bfd38f33ae8780a606ed09ab97177c562 | tools/qark/qark/lib/pubsub/core/topicobj.py | python | Topic._publish | (self, data) | This sends message to listeners of parent topics as well.
If an exception is raised in a listener, the publish is
aborted, except if there is a handler (see
pub.setListenerExcHandler). | This sends message to listeners of parent topics as well.
If an exception is raised in a listener, the publish is
aborted, except if there is a handler (see
pub.setListenerExcHandler). | [
"This",
"sends",
"message",
"to",
"listeners",
"of",
"parent",
"topics",
"as",
"well",
".",
"If",
"an",
"exception",
"is",
"raised",
"in",
"a",
"listener",
"the",
"publish",
"is",
"aborted",
"except",
"if",
"there",
"is",
"a",
"handler",
"(",
"see",
"pub... | def _publish(self, data):
"""This sends message to listeners of parent topics as well.
If an exception is raised in a listener, the publish is
aborted, except if there is a handler (see
pub.setListenerExcHandler)."""
self._treeConfig.notificationMgr.notifySend('pre', self)
# send to ourself
iterState = self._mix_prePublish(data)
self.__sendMessage(data, self, iterState)
# send up the chain
topicObj = self.getParent()
while topicObj is not None:
if topicObj.hasListeners():
iterState = self._mix_prePublish(data, topicObj, iterState)
self.__sendMessage(data, topicObj, iterState)
# done for this topic, continue up branch to parent towards root
topicObj = topicObj.getParent()
self._treeConfig.notificationMgr.notifySend('post', self) | [
"def",
"_publish",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_treeConfig",
".",
"notificationMgr",
".",
"notifySend",
"(",
"'pre'",
",",
"self",
")",
"# send to ourself",
"iterState",
"=",
"self",
".",
"_mix_prePublish",
"(",
"data",
")",
"self",
"... | https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/qark/qark/lib/pubsub/core/topicobj.py#L367-L388 | ||
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | reviewboard/reviews/default_actions.py | python | EditReviewAction.should_render | (self, context) | return (user.is_authenticated() and
not is_site_read_only_for(user)) | Return whether the action should render.
Args:
context (dict):
The current render context.
Returns:
bool:
Whether the action should render. | Return whether the action should render. | [
"Return",
"whether",
"the",
"action",
"should",
"render",
"."
] | def should_render(self, context):
"""Return whether the action should render.
Args:
context (dict):
The current render context.
Returns:
bool:
Whether the action should render.
"""
user = context['request'].user
return (user.is_authenticated() and
not is_site_read_only_for(user)) | [
"def",
"should_render",
"(",
"self",
",",
"context",
")",
":",
"user",
"=",
"context",
"[",
"'request'",
"]",
".",
"user",
"return",
"(",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"not",
"is_site_read_only_for",
"(",
"user",
")",
")"
] | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/reviews/default_actions.py#L240-L254 | |
RonnyPfannschmidt/prance | 86b3bf8a73a474be87498ba8909a8a821fd61d1e | prance/util/formats.py | python | serialize_spec | (specs, filename=None, **kwargs) | return serializer(specs) | Return a serialized version of the given spec.
The default format is assumed to be JSON, but if you provide a filename,
its extension is used to determine whether YAML or JSON should be
parsed.
:param dict specs: The specifications as dict.
:param str filename: [optional] Filename to determine the format from.
:param str content_type: [optional] Content type to determine the format
from.
:return: The serialized specifications.
:rtype: str | Return a serialized version of the given spec. | [
"Return",
"a",
"serialized",
"version",
"of",
"the",
"given",
"spec",
"."
] | def serialize_spec(specs, filename=None, **kwargs):
"""
Return a serialized version of the given spec.
The default format is assumed to be JSON, but if you provide a filename,
its extension is used to determine whether YAML or JSON should be
parsed.
:param dict specs: The specifications as dict.
:param str filename: [optional] Filename to determine the format from.
:param str content_type: [optional] Content type to determine the format
from.
:return: The serialized specifications.
:rtype: str
"""
# Fetch optional content type & determine formats
content_type = kwargs.get("content_type", None)
formats = __format_preferences(filename, content_type)
# Instead of trying to parse various formats, we only serialize to the first
# one in the list - nothing else makes much sense.
serializer = __FORMAT_TO_SERIALIZER[formats[0]]
return serializer(specs) | [
"def",
"serialize_spec",
"(",
"specs",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Fetch optional content type & determine formats",
"content_type",
"=",
"kwargs",
".",
"get",
"(",
"\"content_type\"",
",",
"None",
")",
"formats",
"=",
"__... | https://github.com/RonnyPfannschmidt/prance/blob/86b3bf8a73a474be87498ba8909a8a821fd61d1e/prance/util/formats.py#L208-L230 | |
cackharot/suds-py3 | 1d92cc6297efee31bfd94b50b99c431505d7de21 | suds/xsd/sxbase.py | python | SchemaObject.enum | (self) | return False | Get whether this is a simple-type containing an enumeration.
@return: True if any, else False
@rtype: boolean | Get whether this is a simple-type containing an enumeration. | [
"Get",
"whether",
"this",
"is",
"a",
"simple",
"-",
"type",
"containing",
"an",
"enumeration",
"."
] | def enum(self):
"""
Get whether this is a simple-type containing an enumeration.
@return: True if any, else False
@rtype: boolean
"""
return False | [
"def",
"enum",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/cackharot/suds-py3/blob/1d92cc6297efee31bfd94b50b99c431505d7de21/suds/xsd/sxbase.py#L269-L275 | |
unkn0wnh4ckr/hackers-tool-kit | 34dbabf3e94825684fd1a684f522d3dc3565eb2d | plugins/lib/markup.py | python | escape | (text, newline=False) | return text | Escape special html characters. | Escape special html characters. | [
"Escape",
"special",
"html",
"characters",
"."
] | def escape(text, newline=False):
"""Escape special html characters."""
if isinstance(text, basestring):
if '&' in text:
text = text.replace('&', '&')
if '>' in text:
text = text.replace('>', '>')
if '<' in text:
text = text.replace('<', '<')
if '\"' in text:
text = text.replace('\"', '"')
if '\'' in text:
text = text.replace('\'', '"')
if newline:
if '\n' in text:
text = text.replace('\n', '<br>')
return text | [
"def",
"escape",
"(",
"text",
",",
"newline",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"basestring",
")",
":",
"if",
"'&'",
"in",
"text",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
"if",
"'>'",
... | https://github.com/unkn0wnh4ckr/hackers-tool-kit/blob/34dbabf3e94825684fd1a684f522d3dc3565eb2d/plugins/lib/markup.py#L452-L470 | |
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/django/contrib/databrowse/plugins/calendars.py | python | CalendarPlugin.calendar_view | (self, request, field, year=None, month=None, day=None) | [] | def calendar_view(self, request, field, year=None, month=None, day=None):
easy_model = EasyModel(self.site, self.model)
root_url = self.site.root_url
if day is not None:
return DayView.as_view(
year=year, month=month, day=day,
date_field=field.name,
queryset=easy_model.get_query_set(),
root_url=root_url,
model=easy_model,
field=field
)(request)
elif month is not None:
return MonthView.as_view(
year=year, month=month,
date_field=field.name,
queryset=easy_model.get_query_set(),
root_url=root_url,
model=easy_model,
field=field
)(request)
elif year is not None:
return YearView.as_view(
year=year,
date_field=field.name,
queryset=easy_model.get_query_set(),
root_url=root_url,
model=easy_model,
field=field
)(request)
else:
return IndexView.as_view(
date_field=field.name,
queryset=easy_model.get_query_set(),
root_url=root_url,
model=easy_model,
field=field
)(request)
assert False, ('%s, %s, %s, %s' % (field, year, month, day)) | [
"def",
"calendar_view",
"(",
"self",
",",
"request",
",",
"field",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
")",
":",
"easy_model",
"=",
"EasyModel",
"(",
"self",
".",
"site",
",",
"self",
".",
"model",
")",
"ro... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/databrowse/plugins/calendars.py#L107-L147 | ||||
yongzhuo/Keras-TextClassification | 640e3f44f90d9d8046546f7e1a93a29ebe5c8d30 | keras_textclassification/m06_TextDCNN/graph.py | python | dynamic_k_max_pooling.__init__ | (self, top_k=3, **kwargs) | [] | def __init__(self, top_k=3, **kwargs):
self.top_k = top_k
super().__init__(**kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"top_k",
"=",
"3",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"top_k",
"=",
"top_k",
"super",
"(",
")",
".",
"__init__",
"(",
"*",
"*",
"kwargs",
")"
] | https://github.com/yongzhuo/Keras-TextClassification/blob/640e3f44f90d9d8046546f7e1a93a29ebe5c8d30/keras_textclassification/m06_TextDCNN/graph.py#L141-L143 | ||||
mwouts/jupytext | f8e8352859cc22e17b11154d0770fd946c4a430a | jupytext/formats.py | python | long_form_multiple_formats | (
jupytext_formats, metadata=None, auto_ext_requires_language_info=True
) | return jupytext_formats | Convert a concise encoding of jupytext.formats to a list of formats, encoded as dictionaries | Convert a concise encoding of jupytext.formats to a list of formats, encoded as dictionaries | [
"Convert",
"a",
"concise",
"encoding",
"of",
"jupytext",
".",
"formats",
"to",
"a",
"list",
"of",
"formats",
"encoded",
"as",
"dictionaries"
] | def long_form_multiple_formats(
jupytext_formats, metadata=None, auto_ext_requires_language_info=True
):
"""Convert a concise encoding of jupytext.formats to a list of formats, encoded as dictionaries"""
if not jupytext_formats:
return []
if not isinstance(jupytext_formats, list):
jupytext_formats = [fmt for fmt in jupytext_formats.split(",") if fmt]
jupytext_formats = [
long_form_one_format(
fmt,
metadata,
auto_ext_requires_language_info=auto_ext_requires_language_info,
)
for fmt in jupytext_formats
]
if not auto_ext_requires_language_info:
jupytext_formats = [
fmt for fmt in jupytext_formats if fmt["extension"] != ".auto"
]
return jupytext_formats | [
"def",
"long_form_multiple_formats",
"(",
"jupytext_formats",
",",
"metadata",
"=",
"None",
",",
"auto_ext_requires_language_info",
"=",
"True",
")",
":",
"if",
"not",
"jupytext_formats",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"jupytext_formats",
... | https://github.com/mwouts/jupytext/blob/f8e8352859cc22e17b11154d0770fd946c4a430a/jupytext/formats.py#L655-L679 | |
samuelclay/NewsBlur | 2c45209df01a1566ea105e04d499367f32ac9ad2 | apps/rss_feeds/text_importer.py | python | TextImporter.__init__ | (self, story=None, feed=None, story_url=None, request=None, debug=False) | [] | def __init__(self, story=None, feed=None, story_url=None, request=None, debug=False):
self.story = story
self.story_url = story_url
if self.story and not self.story_url:
self.story_url = self.story.story_permalink
self.feed = feed
self.request = request
self.debug = debug | [
"def",
"__init__",
"(",
"self",
",",
"story",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"story_url",
"=",
"None",
",",
"request",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"self",
".",
"story",
"=",
"story",
"self",
".",
"story_url",
"="... | https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/apps/rss_feeds/text_importer.py#L29-L36 | ||||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/logging/config.py | python | BaseConfigurator.cfg_convert | (self, value) | return d | Default converter for the cfg:// protocol. | Default converter for the cfg:// protocol. | [
"Default",
"converter",
"for",
"the",
"cfg",
":",
"//",
"protocol",
"."
] | def cfg_convert(self, value):
"""Default converter for the cfg:// protocol."""
rest = value
m = self.WORD_PATTERN.match(rest)
if m is None:
raise ValueError("Unable to convert %r" % value)
else:
rest = rest[m.end():]
d = self.config[m.groups()[0]]
#print d, rest
while rest:
m = self.DOT_PATTERN.match(rest)
if m:
d = d[m.groups()[0]]
else:
m = self.INDEX_PATTERN.match(rest)
if m:
idx = m.groups()[0]
if not self.DIGIT_PATTERN.match(idx):
d = d[idx]
else:
try:
n = int(idx) # try as number first (most likely)
d = d[n]
except TypeError:
d = d[idx]
if m:
rest = rest[m.end():]
else:
raise ValueError('Unable to convert '
'%r at %r' % (value, rest))
#rest should be empty
return d | [
"def",
"cfg_convert",
"(",
"self",
",",
"value",
")",
":",
"rest",
"=",
"value",
"m",
"=",
"self",
".",
"WORD_PATTERN",
".",
"match",
"(",
"rest",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unable to convert %r\"",
"%",
"value",
... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/logging/config.py#L405-L437 | |
robinhood/faust | 01b4c0ad8390221db71751d80001b0fd879291e2 | faust/sensors/base.py | python | SensorDelegate.on_table_del | (self, table: CollectionT, key: Any) | Call when key in a table is deleted. | Call when key in a table is deleted. | [
"Call",
"when",
"key",
"in",
"a",
"table",
"is",
"deleted",
"."
] | def on_table_del(self, table: CollectionT, key: Any) -> None:
"""Call when key in a table is deleted."""
for sensor in self._sensors:
sensor.on_table_del(table, key) | [
"def",
"on_table_del",
"(",
"self",
",",
"table",
":",
"CollectionT",
",",
"key",
":",
"Any",
")",
"->",
"None",
":",
"for",
"sensor",
"in",
"self",
".",
"_sensors",
":",
"sensor",
".",
"on_table_del",
"(",
"table",
",",
"key",
")"
] | https://github.com/robinhood/faust/blob/01b4c0ad8390221db71751d80001b0fd879291e2/faust/sensors/base.py#L214-L217 | ||
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/converters/panair/panair_grid_patch.py | python | elements_from_quad | (nx, ny) | return elements | creates quad elements for the gui | creates quad elements for the gui | [
"creates",
"quad",
"elements",
"for",
"the",
"gui"
] | def elements_from_quad(nx, ny):
"""creates quad elements for the gui"""
assert nx > 1
assert ny > 1
nelements = (nx - 1) * (ny - 1)
npoints = nx * ny
# create a matrix with the point counter
ipoints = np.arange(npoints, dtype='int32').reshape((nx, ny))
# move around the CAERO quad and apply ipoints
elements = np.zeros((nelements, 4), dtype='int32')
elements[:, 0] = ipoints[:-1, :-1].ravel() # (i, j )
elements[:, 1] = ipoints[1:, :-1].ravel() # (i+1,j )
elements[:, 2] = ipoints[1:, 1:].ravel() # (i+1,j+1)
elements[:, 3] = ipoints[:-1, 1:].ravel() # (i,j+1 )
return elements | [
"def",
"elements_from_quad",
"(",
"nx",
",",
"ny",
")",
":",
"assert",
"nx",
">",
"1",
"assert",
"ny",
">",
"1",
"nelements",
"=",
"(",
"nx",
"-",
"1",
")",
"*",
"(",
"ny",
"-",
"1",
")",
"npoints",
"=",
"nx",
"*",
"ny",
"# create a matrix with the... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/converters/panair/panair_grid_patch.py#L337-L354 | |
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pip/pep425tags.py | python | get_impl_version_info | () | Return sys.version_info-like tuple for use in decrementing the minor
version. | Return sys.version_info-like tuple for use in decrementing the minor
version. | [
"Return",
"sys",
".",
"version_info",
"-",
"like",
"tuple",
"for",
"use",
"in",
"decrementing",
"the",
"minor",
"version",
"."
] | def get_impl_version_info():
"""Return sys.version_info-like tuple for use in decrementing the minor
version."""
if get_abbr_impl() == 'pp':
# as per https://github.com/pypa/pip/issues/2882
return (sys.version_info[0], sys.pypy_version_info.major,
sys.pypy_version_info.minor)
else:
return sys.version_info[0], sys.version_info[1] | [
"def",
"get_impl_version_info",
"(",
")",
":",
"if",
"get_abbr_impl",
"(",
")",
"==",
"'pp'",
":",
"# as per https://github.com/pypa/pip/issues/2882",
"return",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
",",
"sys",
".",
"pypy_version_info",
".",
"major",
"... | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/pep425tags.py#L55-L63 | ||
zedshaw/lamson | 8a8ad546ea746b129fa5f069bf9278f87d01473a | lamson/routing.py | python | ShelveStorage.set | (self, key, sender, state) | Acquires the self.lock and then sets the requested state in the shelf. | Acquires the self.lock and then sets the requested state in the shelf. | [
"Acquires",
"the",
"self",
".",
"lock",
"and",
"then",
"sets",
"the",
"requested",
"state",
"in",
"the",
"shelf",
"."
] | def set(self, key, sender, state):
"""
Acquires the self.lock and then sets the requested state in the shelf.
"""
with self.lock:
self.states = shelve.open(self.database_path)
super(ShelveStorage, self).set(key.encode('ascii'), sender, state)
self.states.close() | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"sender",
",",
"state",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"states",
"=",
"shelve",
".",
"open",
"(",
"self",
".",
"database_path",
")",
"super",
"(",
"ShelveStorage",
",",
"self",
"... | https://github.com/zedshaw/lamson/blob/8a8ad546ea746b129fa5f069bf9278f87d01473a/lamson/routing.py#L155-L162 | ||
magic-wormhole/magic-wormhole | e522a3992217b433ac2c36543bf85c27a7226ed9 | src/wormhole/_version.py | python | render_git_describe | (pieces) | return rendered | TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | TAG[-DISTANCE-gHEX][-dirty]. | [
"TAG",
"[",
"-",
"DISTANCE",
"-",
"gHEX",
"]",
"[",
"-",
"dirty",
"]",
"."
] | def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered | [
"def",
"render_git_describe",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
":",
"rendered",
"+=",
"\"-%d-g%s\"",
"%",
"(",
"pieces... | https://github.com/magic-wormhole/magic-wormhole/blob/e522a3992217b433ac2c36543bf85c27a7226ed9/src/wormhole/_version.py#L405-L422 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/cloud/libcloudfuncs.py | python | reboot | (name, conn=None) | return False | Reboot a single VM | Reboot a single VM | [
"Reboot",
"a",
"single",
"VM"
] | def reboot(name, conn=None):
"""
Reboot a single VM
"""
if not conn:
conn = get_conn() # pylint: disable=E0602
node = get_node(conn, name)
if node is None:
log.error("Unable to find the VM %s", name)
log.info("Rebooting VM: %s", name)
ret = conn.reboot_node(node)
if ret:
log.info("Rebooted VM: %s", name)
# Fire reboot action
__utils__["cloud.fire_event"](
"event",
"{} has been rebooted".format(name),
"salt/cloud/{}/rebooting".format(name),
args={"name": name},
sock_dir=__opts__["sock_dir"],
transport=__opts__["transport"],
)
return True
log.error("Failed to reboot VM: %s", name)
return False | [
"def",
"reboot",
"(",
"name",
",",
"conn",
"=",
"None",
")",
":",
"if",
"not",
"conn",
":",
"conn",
"=",
"get_conn",
"(",
")",
"# pylint: disable=E0602",
"node",
"=",
"get_node",
"(",
"conn",
",",
"name",
")",
"if",
"node",
"is",
"None",
":",
"log",
... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/libcloudfuncs.py#L326-L352 | |
bitcraze/crazyflie-lib-python | 876f0dc003b91ba5e4de05daae9d0b79cf600f81 | examples/parameters/persistent_params.py | python | get_all_persistent_param_names | (cf) | return persistent_params | [] | def get_all_persistent_param_names(cf):
persistent_params = []
for group_name, params in cf.param.toc.toc.items():
for param_name, element in params.items():
if element.is_persistent():
complete_name = group_name + '.' + param_name
persistent_params.append(complete_name)
return persistent_params | [
"def",
"get_all_persistent_param_names",
"(",
"cf",
")",
":",
"persistent_params",
"=",
"[",
"]",
"for",
"group_name",
",",
"params",
"in",
"cf",
".",
"param",
".",
"toc",
".",
"toc",
".",
"items",
"(",
")",
":",
"for",
"param_name",
",",
"element",
"in"... | https://github.com/bitcraze/crazyflie-lib-python/blob/876f0dc003b91ba5e4de05daae9d0b79cf600f81/examples/parameters/persistent_params.py#L86-L94 | |||
hasegaw/IkaLog | bd476da541fcc296f792d4db76a6b9174c4777ad | ikalog/scenes/game/dead.py | python | GameDead._state_tracking | (self, context) | return False | [] | def _state_tracking(self, context):
frame = context['engine']['frame']
if frame is None:
return False
matched = self.mask_dead.match(context['engine']['frame'])
# 画面が続いているならそのまま
if matched:
self.recoginize_and_vote_death_reason(context)
return True
# 1000ms 以内の非マッチはチャタリングとみなす
if not matched and self.matched_in(context, 1000):
return False
# それ以上マッチングしなかった場合 -> シーンを抜けている
if not self.matched_in(context, 5 * 1000, attr='_last_event_msec'):
self.count_death_reason_votes(context)
if 'last_death_reason' in context['game']:
self._call_plugins('on_game_death_reason_identified')
self._call_plugins('on_game_respawn')
self._last_event_msec = context['engine']['msec']
self._switch_state(self._state_default)
context['game']['dead'] = False
self._cause_of_death_votes = {}
return False | [
"def",
"_state_tracking",
"(",
"self",
",",
"context",
")",
":",
"frame",
"=",
"context",
"[",
"'engine'",
"]",
"[",
"'frame'",
"]",
"if",
"frame",
"is",
"None",
":",
"return",
"False",
"matched",
"=",
"self",
".",
"mask_dead",
".",
"match",
"(",
"cont... | https://github.com/hasegaw/IkaLog/blob/bd476da541fcc296f792d4db76a6b9174c4777ad/ikalog/scenes/game/dead.py#L128-L159 | |||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/tkinter/__init__.py | python | Text.mark_set | (self, markName, index) | Set mark MARKNAME before the character at INDEX. | Set mark MARKNAME before the character at INDEX. | [
"Set",
"mark",
"MARKNAME",
"before",
"the",
"character",
"at",
"INDEX",
"."
] | def mark_set(self, markName, index):
"""Set mark MARKNAME before the character at INDEX."""
self.tk.call(self._w, 'mark', 'set', markName, index) | [
"def",
"mark_set",
"(",
"self",
",",
"markName",
",",
"index",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'mark'",
",",
"'set'",
",",
"markName",
",",
"index",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tkinter/__init__.py#L3155-L3157 | ||
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/pillow/PIL/Image.py | python | register_open | (id, factory, accept=None) | Register an image file plugin. This function should not be used
in application code.
:param id: An image format identifier.
:param factory: An image file factory method.
:param accept: An optional function that can be used to quickly
reject images having another format. | Register an image file plugin. This function should not be used
in application code. | [
"Register",
"an",
"image",
"file",
"plugin",
".",
"This",
"function",
"should",
"not",
"be",
"used",
"in",
"application",
"code",
"."
] | def register_open(id, factory, accept=None):
"""
Register an image file plugin. This function should not be used
in application code.
:param id: An image format identifier.
:param factory: An image file factory method.
:param accept: An optional function that can be used to quickly
reject images having another format.
"""
id = id.upper()
ID.append(id)
OPEN[id] = factory, accept | [
"def",
"register_open",
"(",
"id",
",",
"factory",
",",
"accept",
"=",
"None",
")",
":",
"id",
"=",
"id",
".",
"upper",
"(",
")",
"ID",
".",
"append",
"(",
"id",
")",
"OPEN",
"[",
"id",
"]",
"=",
"factory",
",",
"accept"
] | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pillow/PIL/Image.py#L2436-L2448 | ||
PaddlePaddle/PaddleHub | 107ee7e1a49d15e9c94da3956475d88a53fc165f | modules/text/language_model/lda_news/vose_alias.py | python | VoseAlias.initialize | (self, distribution) | Initialize the alias table according to the input distribution
Arg:
distribution: the input distribution. | Initialize the alias table according to the input distribution
Arg:
distribution: the input distribution. | [
"Initialize",
"the",
"alias",
"table",
"according",
"to",
"the",
"input",
"distribution",
"Arg",
":",
"distribution",
":",
"the",
"input",
"distribution",
"."
] | def initialize(self, distribution):
"""Initialize the alias table according to the input distribution
Arg:
distribution: the input distribution.
"""
size = distribution.shape[0]
self.__alias = np.zeros(size, dtype=np.int64)
self.__prob = np.zeros(size)
sum_ = np.sum(distribution)
p = distribution / sum_ * size # Scale up probability.
large, small = [], []
for i, p_ in enumerate(p):
if p_ < 1.0:
small.append(i)
else:
large.append(i)
while large and small:
l = small[0]
g = large[0]
small.pop(0)
large.pop(0)
self.__prob[l] = p[l]
self.__alias[l] = g
p[g] = p[g] + p[l] - 1 # A more numerically stable option.
if p[g] < 1.0:
small.append(g)
else:
large.append(g)
while large:
g = large[0]
large.pop(0)
self.__prob[g] = 1.0
while small:
l = small[0]
small.pop(0)
self.__prob[l] = 1.0 | [
"def",
"initialize",
"(",
"self",
",",
"distribution",
")",
":",
"size",
"=",
"distribution",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"__alias",
"=",
"np",
".",
"zeros",
"(",
"size",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"self",
".",
"__pro... | https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/modules/text/language_model/lda_news/vose_alias.py#L14-L52 | ||
0xHJK/music-dl | 14bb55eae35ebfc633e0ee96469dc9b235ac2a99 | music_dl/addons/kugou.py | python | kugou_playlist | (url) | return songs_list | [] | def kugou_playlist(url) -> list:
songs_list = []
res = KugouApi.requestInstance(
url,
method="GET",
)
url = urlparse(res.url)
query = parse_qs(url.query)
query["page"] = 1
query["pagesize"] = 100 # 最大100
res_list = (
KugouApi.request("https://m3ws.kugou.com/zlist/list", method="GET", data=query).get('list', {})
)
res_data = res_list.get('info', [])
res_count = res_list.get('count', 0)
repeat_count = math.floor(res_count / (query["page"] * query["pagesize"]))
while repeat_count > 0:
repeat_count -= 1
query["page"] += 1
for item in repeat_get_resource(query):
res_data.append(item)
for item in res_data:
song = KugouSong()
song.source = "kugou"
song.id = item.get("fileid", "")
singer_title = item.get("name", "").split(' - ')
song.title = singer_title[1]
song.singer = singer_title[0]
song.duration = int(item.get("timelen", 0) / 1000)
song.album = item.get("album_id", "")
song.size = round(item.get("size", 0) / 1048576, 2)
song.hash = item.get("hash", "")
songs_list.append(song)
return songs_list | [
"def",
"kugou_playlist",
"(",
"url",
")",
"->",
"list",
":",
"songs_list",
"=",
"[",
"]",
"res",
"=",
"KugouApi",
".",
"requestInstance",
"(",
"url",
",",
"method",
"=",
"\"GET\"",
",",
")",
"url",
"=",
"urlparse",
"(",
"res",
".",
"url",
")",
"query... | https://github.com/0xHJK/music-dl/blob/14bb55eae35ebfc633e0ee96469dc9b235ac2a99/music_dl/addons/kugou.py#L87-L123 | |||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/pandas/core/indexes/datetimes.py | python | _dt_index_cmp | (opname, nat_result=False) | return wrapper | Wrap comparison operations to convert datetime-like to datetime64 | Wrap comparison operations to convert datetime-like to datetime64 | [
"Wrap",
"comparison",
"operations",
"to",
"convert",
"datetime",
"-",
"like",
"to",
"datetime64"
] | def _dt_index_cmp(opname, nat_result=False):
"""
Wrap comparison operations to convert datetime-like to datetime64
"""
def wrapper(self, other):
func = getattr(super(DatetimeIndex, self), opname)
if (isinstance(other, datetime) or
isinstance(other, compat.string_types)):
other = _to_m8(other, tz=self.tz)
result = func(other)
if isnull(other):
result.fill(nat_result)
else:
if isinstance(other, list):
other = DatetimeIndex(other)
elif not isinstance(other, (np.ndarray, Index, ABCSeries)):
other = _ensure_datetime64(other)
result = func(np.asarray(other))
result = _values_from_object(result)
if isinstance(other, Index):
o_mask = other.values.view('i8') == libts.iNaT
else:
o_mask = other.view('i8') == libts.iNaT
if o_mask.any():
result[o_mask] = nat_result
if self.hasnans:
result[self._isnan] = nat_result
# support of bool dtype indexers
if is_bool_dtype(result):
return result
return Index(result)
return wrapper | [
"def",
"_dt_index_cmp",
"(",
"opname",
",",
"nat_result",
"=",
"False",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
"func",
"=",
"getattr",
"(",
"super",
"(",
"DatetimeIndex",
",",
"self",
")",
",",
"opname",
")",
"if",
"(",
"isi... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/indexes/datetimes.py#L101-L138 | |
GNS3/gns3-gui | da8adbaa18ab60e053af2a619efd468f4c8950f3 | gns3/modules/virtualbox/pages/virtualbox_preferences_page.py | python | VirtualBoxPreferencesPage._checkVBoxManagePath | (self, path) | return True | Checks that the VBoxManage path is valid.
:param path: VBoxManage path
:returns: boolean | Checks that the VBoxManage path is valid. | [
"Checks",
"that",
"the",
"VBoxManage",
"path",
"is",
"valid",
"."
] | def _checkVBoxManagePath(self, path):
"""
Checks that the VBoxManage path is valid.
:param path: VBoxManage path
:returns: boolean
"""
if not os.path.exists(path):
QtWidgets.QMessageBox.critical(self, "VBoxManage", '"{}" does not exist'.format(path))
return False
if not os.access(path, os.X_OK):
QtWidgets.QMessageBox.critical(self, "VBoxManage", "{} is not an executable".format(os.path.basename(path)))
return False
if sys.platform.startswith("win") and "virtualbox.exe" in path.lower():
QtWidgets.QMessageBox.critical(self, "VBoxManage", "VBoxManage.exe must be selected instead of VirtualBox.exe")
return False
return True | [
"def",
"_checkVBoxManagePath",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"QtWidgets",
".",
"QMessageBox",
".",
"critical",
"(",
"self",
",",
"\"VBoxManage\"",
",",
"'\"{}\" does not exist'",
"... | https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/modules/virtualbox/pages/virtualbox_preferences_page.py#L59-L79 | |
crits/crits_services | c7abf91f1865d913cffad4b966599da204f8ae43 | office_meta_service/forms.py | python | OfficeMetaRunForm.__init__ | (self, *args, **kwargs) | [] | def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', ':')
super(OfficeMetaRunForm, self).__init__(*args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'label_suffix'",
",",
"':'",
")",
"super",
"(",
"OfficeMetaRunForm",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*"... | https://github.com/crits/crits_services/blob/c7abf91f1865d913cffad4b966599da204f8ae43/office_meta_service/forms.py#L11-L13 | ||||
got-10k/toolkit | 956e7286fdf209cbb125adac9a46376bd8297ffb | got10k/utils/ioutils.py | python | compress | (dirname, save_file) | Compress a folder to a zip file.
Arguments:
dirname {string} -- Directory of all files to be compressed.
save_file {string} -- Path to store the zip file. | Compress a folder to a zip file.
Arguments:
dirname {string} -- Directory of all files to be compressed.
save_file {string} -- Path to store the zip file. | [
"Compress",
"a",
"folder",
"to",
"a",
"zip",
"file",
".",
"Arguments",
":",
"dirname",
"{",
"string",
"}",
"--",
"Directory",
"of",
"all",
"files",
"to",
"be",
"compressed",
".",
"save_file",
"{",
"string",
"}",
"--",
"Path",
"to",
"store",
"the",
"zip... | def compress(dirname, save_file):
"""Compress a folder to a zip file.
Arguments:
dirname {string} -- Directory of all files to be compressed.
save_file {string} -- Path to store the zip file.
"""
shutil.make_archive(save_file, 'zip', dirname) | [
"def",
"compress",
"(",
"dirname",
",",
"save_file",
")",
":",
"shutil",
".",
"make_archive",
"(",
"save_file",
",",
"'zip'",
",",
"dirname",
")"
] | https://github.com/got-10k/toolkit/blob/956e7286fdf209cbb125adac9a46376bd8297ffb/got10k/utils/ioutils.py#L37-L44 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/kombu-4.3.0/kombu/pools.py | python | get_limit | () | return _limit[0] | Get current connection pool limit. | Get current connection pool limit. | [
"Get",
"current",
"connection",
"pool",
"limit",
"."
] | def get_limit():
"""Get current connection pool limit."""
return _limit[0] | [
"def",
"get_limit",
"(",
")",
":",
"return",
"_limit",
"[",
"0",
"]"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/kombu-4.3.0/kombu/pools.py#L125-L127 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/matrices/densetools.py | python | col | (matlist, i) | return [[l] for l in matcol[i]] | Returns the ith column of a matrix
Note: Currently very expensive
Examples
========
>>> from sympy.matrices.densetools import col
>>> from sympy import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> col(a, 1)
[[7], [4], [2]] | Returns the ith column of a matrix
Note: Currently very expensive | [
"Returns",
"the",
"ith",
"column",
"of",
"a",
"matrix",
"Note",
":",
"Currently",
"very",
"expensive"
] | def col(matlist, i):
"""
Returns the ith column of a matrix
Note: Currently very expensive
Examples
========
>>> from sympy.matrices.densetools import col
>>> from sympy import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> col(a, 1)
[[7], [4], [2]]
"""
matcol = [list(l) for l in zip(*matlist)]
return [[l] for l in matcol[i]] | [
"def",
"col",
"(",
"matlist",
",",
"i",
")",
":",
"matcol",
"=",
"[",
"list",
"(",
"l",
")",
"for",
"l",
"in",
"zip",
"(",
"*",
"matlist",
")",
"]",
"return",
"[",
"[",
"l",
"]",
"for",
"l",
"in",
"matcol",
"[",
"i",
"]",
"]"
] | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/matrices/densetools.py#L193-L211 | |
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/config.py | python | ConfigHandler.__init__ | (self, target_obj, options, ignore_option_errors=False) | [] | def __init__(self, target_obj, options, ignore_option_errors=False):
sections = {}
section_prefix = self.section_prefix
for section_name, section_options in options.items():
if not section_name.startswith(section_prefix):
continue
section_name = section_name.replace(section_prefix, '').strip('.')
sections[section_name] = section_options
self.ignore_option_errors = ignore_option_errors
self.target_obj = target_obj
self.sections = sections
self.set_options = [] | [
"def",
"__init__",
"(",
"self",
",",
"target_obj",
",",
"options",
",",
"ignore_option_errors",
"=",
"False",
")",
":",
"sections",
"=",
"{",
"}",
"section_prefix",
"=",
"self",
".",
"section_prefix",
"for",
"section_name",
",",
"section_options",
"in",
"optio... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/config.py#L131-L145 | ||||
GNS3/gns3-gui | da8adbaa18ab60e053af2a619efd468f4c8950f3 | gns3/utils/wait_for_runas_worker.py | python | WaitForRunAsWorker.cancel | (self) | Cancel this worker. | Cancel this worker. | [
"Cancel",
"this",
"worker",
"."
] | def cancel(self):
"""
Cancel this worker.
"""
if not self:
return
self._is_running = False | [
"def",
"cancel",
"(",
"self",
")",
":",
"if",
"not",
"self",
":",
"return",
"self",
".",
"_is_running",
"=",
"False"
] | https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/utils/wait_for_runas_worker.py#L84-L91 | ||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/gdata/gauth.py | python | ae_delete | (token_key) | Removes the token object from the App Engine datastore. | Removes the token object from the App Engine datastore. | [
"Removes",
"the",
"token",
"object",
"from",
"the",
"App",
"Engine",
"datastore",
"."
] | def ae_delete(token_key):
"""Removes the token object from the App Engine datastore."""
import gdata.alt.app_engine
key_name = ''.join(('gd_auth_token', token_key))
gdata.alt.app_engine.delete_token(key_name) | [
"def",
"ae_delete",
"(",
"token_key",
")",
":",
"import",
"gdata",
".",
"alt",
".",
"app_engine",
"key_name",
"=",
"''",
".",
"join",
"(",
"(",
"'gd_auth_token'",
",",
"token_key",
")",
")",
"gdata",
".",
"alt",
".",
"app_engine",
".",
"delete_token",
"(... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/gauth.py#L1625-L1629 | ||
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/linalg/_matfuncs_sqrtm.py | python | sqrtm | (A, disp=True, blocksize=64) | Matrix square root.
Parameters
----------
A : (N, N) array_like
Matrix whose square root to evaluate
disp : bool, optional
Print warning if error in the result is estimated large
instead of returning estimated error. (Default: True)
blocksize : integer, optional
If the blocksize is not degenerate with respect to the
size of the input array, then use a blocked algorithm. (Default: 64)
Returns
-------
sqrtm : (N, N) ndarray
Value of the sqrt function at `A`
errest : float
(if disp == False)
Frobenius norm of the estimated error, ||err||_F / ||A||_F
References
----------
.. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
"Blocked Schur Algorithms for Computing the Matrix Square Root,
Lecture Notes in Computer Science, 7782. pp. 171-182.
Examples
--------
>>> from scipy.linalg import sqrtm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> r = sqrtm(a)
>>> r
array([[ 0.75592895, 1.13389342],
[ 0.37796447, 1.88982237]])
>>> r.dot(r)
array([[ 1., 3.],
[ 1., 4.]]) | Matrix square root. | [
"Matrix",
"square",
"root",
"."
] | def sqrtm(A, disp=True, blocksize=64):
"""
Matrix square root.
Parameters
----------
A : (N, N) array_like
Matrix whose square root to evaluate
disp : bool, optional
Print warning if error in the result is estimated large
instead of returning estimated error. (Default: True)
blocksize : integer, optional
If the blocksize is not degenerate with respect to the
size of the input array, then use a blocked algorithm. (Default: 64)
Returns
-------
sqrtm : (N, N) ndarray
Value of the sqrt function at `A`
errest : float
(if disp == False)
Frobenius norm of the estimated error, ||err||_F / ||A||_F
References
----------
.. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
"Blocked Schur Algorithms for Computing the Matrix Square Root,
Lecture Notes in Computer Science, 7782. pp. 171-182.
Examples
--------
>>> from scipy.linalg import sqrtm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> r = sqrtm(a)
>>> r
array([[ 0.75592895, 1.13389342],
[ 0.37796447, 1.88982237]])
>>> r.dot(r)
array([[ 1., 3.],
[ 1., 4.]])
"""
A = _asarray_validated(A, check_finite=True, as_inexact=True)
if len(A.shape) != 2:
raise ValueError("Non-matrix input to matrix function.")
if blocksize < 1:
raise ValueError("The blocksize should be at least 1.")
keep_it_real = np.isrealobj(A)
if keep_it_real:
T, Z = schur(A)
if not np.array_equal(T, np.triu(T)):
T, Z = rsf2csf(T, Z)
else:
T, Z = schur(A, output='complex')
failflag = False
try:
R = _sqrtm_triu(T, blocksize=blocksize)
ZH = np.conjugate(Z).T
X = Z.dot(R).dot(ZH)
except SqrtmError:
failflag = True
X = np.empty_like(A)
X.fill(np.nan)
if disp:
if failflag:
print("Failed to find a square root.")
return X
else:
try:
arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro')
except ValueError:
# NaNs in matrix
arg2 = np.inf
return X, arg2 | [
"def",
"sqrtm",
"(",
"A",
",",
"disp",
"=",
"True",
",",
"blocksize",
"=",
"64",
")",
":",
"A",
"=",
"_asarray_validated",
"(",
"A",
",",
"check_finite",
"=",
"True",
",",
"as_inexact",
"=",
"True",
")",
"if",
"len",
"(",
"A",
".",
"shape",
")",
... | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/linalg/_matfuncs_sqrtm.py#L119-L196 | ||
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txdav/caldav/datastore/sql.py | python | Calendar.moveObjectResourceAway | (self, rid, child=None) | Remove the child as the result of a move operation. This needs to be split out because
behavior differs for sub-classes and cross-pod operations.
@param rid: the child resource-id to move
@type rid: C{int}
@param child: the child resource to move - might be C{None} for cross-pod
@type child: L{CommonObjectResource} | Remove the child as the result of a move operation. This needs to be split out because
behavior differs for sub-classes and cross-pod operations. | [
"Remove",
"the",
"child",
"as",
"the",
"result",
"of",
"a",
"move",
"operation",
".",
"This",
"needs",
"to",
"be",
"split",
"out",
"because",
"behavior",
"differs",
"for",
"sub",
"-",
"classes",
"and",
"cross",
"-",
"pod",
"operations",
"."
] | def moveObjectResourceAway(self, rid, child=None):
"""
Remove the child as the result of a move operation. This needs to be split out because
behavior differs for sub-classes and cross-pod operations.
@param rid: the child resource-id to move
@type rid: C{int}
@param child: the child resource to move - might be C{None} for cross-pod
@type child: L{CommonObjectResource}
"""
if child is None:
child = yield self.objectResourceWithID(rid)
yield child._removeInternal(internal_state=ComponentRemoveState.INTERNAL, useTrash=False) | [
"def",
"moveObjectResourceAway",
"(",
"self",
",",
"rid",
",",
"child",
"=",
"None",
")",
":",
"if",
"child",
"is",
"None",
":",
"child",
"=",
"yield",
"self",
".",
"objectResourceWithID",
"(",
"rid",
")",
"yield",
"child",
".",
"_removeInternal",
"(",
"... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/caldav/datastore/sql.py#L1392-L1405 | ||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/pip/_vendor/distlib/database.py | python | DistributionPath.provides_distribution | (self, name, version=None) | Iterates over all distributions to find which distributions provide *name*.
If a *version* is provided, it will be used to filter the results.
This function only returns the first result found, since no more than
one values are expected. If the directory is not found, returns ``None``.
:parameter version: a version specifier that indicates the version
required, conforming to the format in ``PEP-345``
:type name: string
:type version: string | Iterates over all distributions to find which distributions provide *name*.
If a *version* is provided, it will be used to filter the results. | [
"Iterates",
"over",
"all",
"distributions",
"to",
"find",
"which",
"distributions",
"provide",
"*",
"name",
"*",
".",
"If",
"a",
"*",
"version",
"*",
"is",
"provided",
"it",
"will",
"be",
"used",
"to",
"filter",
"the",
"results",
"."
] | def provides_distribution(self, name, version=None):
"""
Iterates over all distributions to find which distributions provide *name*.
If a *version* is provided, it will be used to filter the results.
This function only returns the first result found, since no more than
one values are expected. If the directory is not found, returns ``None``.
:parameter version: a version specifier that indicates the version
required, conforming to the format in ``PEP-345``
:type name: string
:type version: string
"""
matcher = None
if not version is None:
try:
matcher = self._scheme.matcher('%s (%s)' % (name, version))
except ValueError:
raise DistlibException('invalid name or version: %r, %r' %
(name, version))
for dist in self.get_distributions():
provided = dist.provides
for p in provided:
p_name, p_ver = parse_name_and_version(p)
if matcher is None:
if p_name == name:
yield dist
break
else:
if p_name == name and matcher.match(p_ver):
yield dist
break | [
"def",
"provides_distribution",
"(",
"self",
",",
"name",
",",
"version",
"=",
"None",
")",
":",
"matcher",
"=",
"None",
"if",
"not",
"version",
"is",
"None",
":",
"try",
":",
"matcher",
"=",
"self",
".",
"_scheme",
".",
"matcher",
"(",
"'%s (%s)'",
"%... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/_vendor/distlib/database.py#L245-L279 | ||
tdamdouni/Pythonista | 3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad | _2017/external_screen.py | python | unregister_disconnected_handler | (handler) | Removes previously registered screen disconnection handler. | Removes previously registered screen disconnection handler. | [
"Removes",
"previously",
"registered",
"screen",
"disconnection",
"handler",
"."
] | def unregister_disconnected_handler(handler):
'''Removes previously registered screen disconnection handler.
'''
_disconnected_handlers.remove(handler) | [
"def",
"unregister_disconnected_handler",
"(",
"handler",
")",
":",
"_disconnected_handlers",
".",
"remove",
"(",
"handler",
")"
] | https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/_2017/external_screen.py#L50-L53 | ||
amzn/metalearn-leap | 9d6fa0c1c27fa7812cb9510ab0b23d5f25f575f0 | src/omniglot/utils.py | python | convert_arg | (arg) | return arg | Convert string to type | Convert string to type | [
"Convert",
"string",
"to",
"type"
] | def convert_arg(arg):
"""Convert string to type"""
# pylint: disable=broad-except
if arg.lower() == 'none':
arg = None
elif arg.lower() == 'false':
arg = False
elif arg.lower() == 'true':
arg = True
elif '.' in arg:
try:
arg = float(arg)
except Exception:
pass
else:
try:
arg = int(arg)
except Exception:
pass
return arg | [
"def",
"convert_arg",
"(",
"arg",
")",
":",
"# pylint: disable=broad-except",
"if",
"arg",
".",
"lower",
"(",
")",
"==",
"'none'",
":",
"arg",
"=",
"None",
"elif",
"arg",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"arg",
"=",
"False",
"elif",
"arg",... | https://github.com/amzn/metalearn-leap/blob/9d6fa0c1c27fa7812cb9510ab0b23d5f25f575f0/src/omniglot/utils.py#L22-L41 | |
annoviko/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | pyclustering/core/som_wrapper.py | python | som_get_neighbors | (som_pointer) | return result | !
@brief Returns list of indexes of neighbors of each neuron.
@param[in] som_pointer (c_pointer): pointer to object of self-organized map. | ! | [
"!"
] | def som_get_neighbors(som_pointer):
"""!
@brief Returns list of indexes of neighbors of each neuron.
@param[in] som_pointer (c_pointer): pointer to object of self-organized map.
"""
ccore = ccore_library.get()
ccore.som_get_neighbors.restype = POINTER(pyclustering_package)
package = ccore.som_get_neighbors(som_pointer)
result = package_extractor(package).extract()
return result | [
"def",
"som_get_neighbors",
"(",
"som_pointer",
")",
":",
"ccore",
"=",
"ccore_library",
".",
"get",
"(",
")",
"ccore",
".",
"som_get_neighbors",
".",
"restype",
"=",
"POINTER",
"(",
"pyclustering_package",
")",
"package",
"=",
"ccore",
".",
"som_get_neighbors",... | https://github.com/annoviko/pyclustering/blob/bf4f51a472622292627ec8c294eb205585e50f52/pyclustering/core/som_wrapper.py#L221-L235 | |
larryhastings/gilectomy | 4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a | Lib/code.py | python | InteractiveConsole.push | (self, line) | return more | Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()). | Push a line to the interpreter. | [
"Push",
"a",
"line",
"to",
"the",
"interpreter",
"."
] | def push(self, line):
"""Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetbuffer()
return more | [
"def",
"push",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"buffer",
".",
"append",
"(",
"line",
")",
"source",
"=",
"\"\\n\"",
".",
"join",
"(",
"self",
".",
"buffer",
")",
"more",
"=",
"self",
".",
"runsource",
"(",
"source",
",",
"self",
... | https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/code.py#L234-L253 | |
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/fractions.py | python | Fraction._sub | (a, b) | return Fraction(a.numerator * b.denominator -
b.numerator * a.denominator,
a.denominator * b.denominator) | a - b | a - b | [
"a",
"-",
"b"
] | def _sub(a, b):
"""a - b"""
return Fraction(a.numerator * b.denominator -
b.numerator * a.denominator,
a.denominator * b.denominator) | [
"def",
"_sub",
"(",
"a",
",",
"b",
")",
":",
"return",
"Fraction",
"(",
"a",
".",
"numerator",
"*",
"b",
".",
"denominator",
"-",
"b",
".",
"numerator",
"*",
"a",
".",
"denominator",
",",
"a",
".",
"denominator",
"*",
"b",
".",
"denominator",
")"
] | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/fractions.py#L395-L399 | |
pyqt/examples | 843bb982917cecb2350b5f6d7f42c9b7fb142ec1 | src/pyqt-official/dialogs/trivialwizard.py | python | createRegistrationPage | () | return page | [] | def createRegistrationPage():
page = QWizardPage()
page.setTitle("Registration")
page.setSubTitle("Please fill both fields.")
nameLabel = QLabel("Name:")
nameLineEdit = QLineEdit()
emailLabel = QLabel("Email address:")
emailLineEdit = QLineEdit()
layout = QGridLayout()
layout.addWidget(nameLabel, 0, 0)
layout.addWidget(nameLineEdit, 0, 1)
layout.addWidget(emailLabel, 1, 0)
layout.addWidget(emailLineEdit, 1, 1)
page.setLayout(layout)
return page | [
"def",
"createRegistrationPage",
"(",
")",
":",
"page",
"=",
"QWizardPage",
"(",
")",
"page",
".",
"setTitle",
"(",
"\"Registration\"",
")",
"page",
".",
"setSubTitle",
"(",
"\"Please fill both fields.\"",
")",
"nameLabel",
"=",
"QLabel",
"(",
"\"Name:\"",
")",
... | https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/dialogs/trivialwizard.py#L65-L83 | |||
ethz-asl/hierarchical_loc | 3c9e32e9e01e5f4694fb796fd1db276f88f361fb | retrievalnet/retrievalnet/utils/stdout_capturing.py | python | flush | () | Try to flush all stdio buffers, both from python and from C. | Try to flush all stdio buffers, both from python and from C. | [
"Try",
"to",
"flush",
"all",
"stdio",
"buffers",
"both",
"from",
"python",
"and",
"from",
"C",
"."
] | def flush():
"""Try to flush all stdio buffers, both from python and from C."""
try:
sys.stdout.flush()
sys.stderr.flush()
except (AttributeError, ValueError, IOError):
pass | [
"def",
"flush",
"(",
")",
":",
"try",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"except",
"(",
"AttributeError",
",",
"ValueError",
",",
"IOError",
")",
":",
"pass"
] | https://github.com/ethz-asl/hierarchical_loc/blob/3c9e32e9e01e5f4694fb796fd1db276f88f361fb/retrievalnet/retrievalnet/utils/stdout_capturing.py#L16-L22 | ||
google/pytype | fa43edc95dd42ade6e3147d6580d63e778c9d506 | pytype/vm.py | python | VirtualMachine.byte_END_FINALLY | (self, state, op) | Implementation of the END_FINALLY opcode. | Implementation of the END_FINALLY opcode. | [
"Implementation",
"of",
"the",
"END_FINALLY",
"opcode",
"."
] | def byte_END_FINALLY(self, state, op):
"""Implementation of the END_FINALLY opcode."""
state, exc = state.pop()
if self._var_is_none(exc):
return state
else:
log.info("Popping exception %r", exc)
state = state.pop_and_discard()
state = state.pop_and_discard()
# If a pending exception makes it all the way out of an "except" block,
# no handler matched, hence Python re-raises the exception.
return state.set_why("reraise") | [
"def",
"byte_END_FINALLY",
"(",
"self",
",",
"state",
",",
"op",
")",
":",
"state",
",",
"exc",
"=",
"state",
".",
"pop",
"(",
")",
"if",
"self",
".",
"_var_is_none",
"(",
"exc",
")",
":",
"return",
"state",
"else",
":",
"log",
".",
"info",
"(",
... | https://github.com/google/pytype/blob/fa43edc95dd42ade6e3147d6580d63e778c9d506/pytype/vm.py#L2332-L2343 | ||
marshmallow-code/marshmallow | 58c2045b8f272c2f1842458aa79f5c079a01429f | src/marshmallow/decorators.py | python | pre_load | (
fn: Callable[..., Any] | None = None, pass_many: bool = False
) | return set_hook(fn, (PRE_LOAD, pass_many)) | Register a method to invoke before deserializing an object. The method
receives the data to be deserialized and returns the processed data.
By default it receives a single object at a time, transparently handling the ``many``
argument passed to the `Schema`'s :func:`~marshmallow.Schema.load` call.
If ``pass_many=True``, the raw data (which may be a collection) is passed.
.. versionchanged:: 3.0.0
``partial`` and ``many`` are always passed as keyword arguments to
the decorated method. | Register a method to invoke before deserializing an object. The method
receives the data to be deserialized and returns the processed data. | [
"Register",
"a",
"method",
"to",
"invoke",
"before",
"deserializing",
"an",
"object",
".",
"The",
"method",
"receives",
"the",
"data",
"to",
"be",
"deserialized",
"and",
"returns",
"the",
"processed",
"data",
"."
] | def pre_load(
fn: Callable[..., Any] | None = None, pass_many: bool = False
) -> Callable[..., Any]:
"""Register a method to invoke before deserializing an object. The method
receives the data to be deserialized and returns the processed data.
By default it receives a single object at a time, transparently handling the ``many``
argument passed to the `Schema`'s :func:`~marshmallow.Schema.load` call.
If ``pass_many=True``, the raw data (which may be a collection) is passed.
.. versionchanged:: 3.0.0
``partial`` and ``many`` are always passed as keyword arguments to
the decorated method.
"""
return set_hook(fn, (PRE_LOAD, pass_many)) | [
"def",
"pre_load",
"(",
"fn",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
"|",
"None",
"=",
"None",
",",
"pass_many",
":",
"bool",
"=",
"False",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"return",
"set_hook",
"(",
"fn",
",",
"(",... | https://github.com/marshmallow-code/marshmallow/blob/58c2045b8f272c2f1842458aa79f5c079a01429f/src/marshmallow/decorators.py#L158-L172 | |
princewen/leetcode_python | 79e6e760e4d81824c96903e6c996630c24d01932 | sort_by_myself/meidum/树/508. Most Frequent Subtree Sum.py | python | Solution.findFrequentTreeSum | (self, root) | return res | :type root: TreeNode
:rtype: List[int] | :type root: TreeNode
:rtype: List[int] | [
":",
"type",
"root",
":",
"TreeNode",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.postOrder(root)
res = []
for i in self.count:
if self.count[i] == self.maxCount:
res.append(i)
return res | [
"def",
"findFrequentTreeSum",
"(",
"self",
",",
"root",
")",
":",
"self",
".",
"postOrder",
"(",
"root",
")",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"count",
":",
"if",
"self",
".",
"count",
"[",
"i",
"]",
"==",
"self",
".",
"maxCou... | https://github.com/princewen/leetcode_python/blob/79e6e760e4d81824c96903e6c996630c24d01932/sort_by_myself/meidum/树/508. Most Frequent Subtree Sum.py#L38-L48 | |
earhian/Humpback-Whale-Identification-1st- | 2bcb126fb255670b0da57b8a104e47267a8c3a17 | models/triplet_loss.py | python | batch_euclidean_dist | (x, y) | return dist | Args:
x: pytorch Variable, with shape [N, m, d]
y: pytorch Variable, with shape [N, n, d]
Returns:
dist: pytorch Variable, with shape [N, m, n] | Args:
x: pytorch Variable, with shape [N, m, d]
y: pytorch Variable, with shape [N, n, d]
Returns:
dist: pytorch Variable, with shape [N, m, n] | [
"Args",
":",
"x",
":",
"pytorch",
"Variable",
"with",
"shape",
"[",
"N",
"m",
"d",
"]",
"y",
":",
"pytorch",
"Variable",
"with",
"shape",
"[",
"N",
"n",
"d",
"]",
"Returns",
":",
"dist",
":",
"pytorch",
"Variable",
"with",
"shape",
"[",
"N",
"m",
... | def batch_euclidean_dist(x, y):
"""
Args:
x: pytorch Variable, with shape [N, m, d]
y: pytorch Variable, with shape [N, n, d]
Returns:
dist: pytorch Variable, with shape [N, m, n]
"""
assert len(x.size()) == 3
assert len(y.size()) == 3
assert x.size(0) == y.size(0)
assert x.size(-1) == y.size(-1)
N, m, d = x.size()
N, n, d = y.size()
# shape [N, m, n]
xx = torch.pow(x, 2).sum(-1, keepdim=True).expand(N, m, n)
yy = torch.pow(y, 2).sum(-1, keepdim=True).expand(N, n, m).permute(0, 2, 1)
dist = xx + yy
dist.baddbmm_(1, -2, x, y.permute(0, 2, 1))
dist = dist.clamp(min=1e-12).sqrt() # for numerical stability
return dist | [
"def",
"batch_euclidean_dist",
"(",
"x",
",",
"y",
")",
":",
"assert",
"len",
"(",
"x",
".",
"size",
"(",
")",
")",
"==",
"3",
"assert",
"len",
"(",
"y",
".",
"size",
"(",
")",
")",
"==",
"3",
"assert",
"x",
".",
"size",
"(",
"0",
")",
"==",
... | https://github.com/earhian/Humpback-Whale-Identification-1st-/blob/2bcb126fb255670b0da57b8a104e47267a8c3a17/models/triplet_loss.py#L236-L258 | |
gnes-ai/gnes | b4d2c8cf863664a9322f866a72eab8246175ebef | gnes/preprocessor/audio/vggish_example.py | python | VggishPreprocessor.waveform_to_examples | (self, data, sample_rate) | return log_mel_examples | Converts audio waveform into an array of examples for VGGish.
Args:
data: np.array of either one dimension (mono) or two dimensions
(multi-channel, with the outer dimension representing channels).
Each sample is generally expected to lie in the range [-1.0, +1.0],
although this is not required.
sample_rate: Sample rate of data.
Returns:
3-D np.array of shape [num_examples, num_frames, num_bands] which represents
a sequence of examples, each of which contains a patch of log mel
spectrogram, covering num_frames frames of audio and num_bands mel frequency
bands, where the frame length is vggish_params.STFT_HOP_LENGTH_SECONDS. | Converts audio waveform into an array of examples for VGGish. | [
"Converts",
"audio",
"waveform",
"into",
"an",
"array",
"of",
"examples",
"for",
"VGGish",
"."
] | def waveform_to_examples(self, data, sample_rate):
"""Converts audio waveform into an array of examples for VGGish.
Args:
data: np.array of either one dimension (mono) or two dimensions
(multi-channel, with the outer dimension representing channels).
Each sample is generally expected to lie in the range [-1.0, +1.0],
although this is not required.
sample_rate: Sample rate of data.
Returns:
3-D np.array of shape [num_examples, num_frames, num_bands] which represents
a sequence of examples, each of which contains a patch of log mel
spectrogram, covering num_frames frames of audio and num_bands mel frequency
bands, where the frame length is vggish_params.STFT_HOP_LENGTH_SECONDS.
"""
from .vggish_example_helper import mel_features
import resampy
# Convert to mono.
print(type(data))
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != self.sample_rate:
data = resampy.resample(data, sample_rate, self.sample_rate)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram(
data,
audio_sample_rate=self.sample_rate,
log_offset=self.log_offset,
window_length_secs=self.stft_window_length_seconds,
hop_length_secs=self.stft_hop_length_seconds,
num_mel_bins=self.num_mel_binds,
lower_edge_hertz=self.mel_min_hz,
upper_edge_hertz=self.mel_max_hz)
# Frame features into examples.
features_sample_rate = 1.0 / self.stft_hop_length_seconds
example_window_length = int(round(
self.example_window_seconds * features_sample_rate))
example_hop_length = int(round(
self.example_hop_seconds * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples | [
"def",
"waveform_to_examples",
"(",
"self",
",",
"data",
",",
"sample_rate",
")",
":",
"from",
".",
"vggish_example_helper",
"import",
"mel_features",
"import",
"resampy",
"# Convert to mono.",
"print",
"(",
"type",
"(",
"data",
")",
")",
"if",
"len",
"(",
"da... | https://github.com/gnes-ai/gnes/blob/b4d2c8cf863664a9322f866a72eab8246175ebef/gnes/preprocessor/audio/vggish_example.py#L58-L106 | |
quantopian/zipline | 014f1fc339dc8b7671d29be2d85ce57d3daec343 | zipline/pipeline/mixins.py | python | DownsampledMixin._compute | (self, inputs, dates, assets, mask) | return vstack(results) | Compute by delegating to self._wrapped_term._compute on sample dates.
On non-sample dates, forward-fill from previously-computed samples. | Compute by delegating to self._wrapped_term._compute on sample dates. | [
"Compute",
"by",
"delegating",
"to",
"self",
".",
"_wrapped_term",
".",
"_compute",
"on",
"sample",
"dates",
"."
] | def _compute(self, inputs, dates, assets, mask):
"""
Compute by delegating to self._wrapped_term._compute on sample dates.
On non-sample dates, forward-fill from previously-computed samples.
"""
to_sample = dates[select_sampling_indices(dates, self._frequency)]
assert to_sample[0] == dates[0], \
"Misaligned sampling dates in %s." % type(self).__name__
real_compute = self._wrapped_term._compute
# Inputs will contain different kinds of values depending on whether or
# not we're a windowed computation.
# If we're windowed, then `inputs` is a list of iterators of ndarrays.
# If we're not windowed, then `inputs` is just a list of ndarrays.
# There are two things we care about doing with the input:
# 1. Preparing an input to be passed to our wrapped term.
# 2. Skipping an input if we're going to use an already-computed row.
# We perform these actions differently based on the expected kind of
# input, and we encapsulate these actions with closures so that we
# don't clutter the code below with lots of branching.
if self.windowed:
# If we're windowed, inputs are stateful AdjustedArrays. We don't
# need to do any preparation before forwarding to real_compute, but
# we need to call `next` on them if we want to skip an iteration.
def prepare_inputs():
return inputs
def skip_this_input():
for w in inputs:
next(w)
else:
# If we're not windowed, inputs are just ndarrays. We need to
# slice out a single row when forwarding to real_compute, but we
# don't need to do anything to skip an input.
def prepare_inputs():
# i is the loop iteration variable below.
return [a[[i]] for a in inputs]
def skip_this_input():
pass
results = []
samples = iter(to_sample)
next_sample = next(samples)
for i, compute_date in enumerate(dates):
if next_sample == compute_date:
results.append(
real_compute(
prepare_inputs(),
dates[i:i + 1],
assets,
mask[i:i + 1],
)
)
try:
next_sample = next(samples)
except StopIteration:
# No more samples to take. Set next_sample to Nat, which
# compares False with any other datetime.
next_sample = pd_NaT
else:
skip_this_input()
# Copy results from previous sample period.
results.append(results[-1])
# We should have exhausted our sample dates.
try:
next_sample = next(samples)
except StopIteration:
pass
else:
raise AssertionError("Unconsumed sample date: %s" % next_sample)
# Concatenate stored results.
return vstack(results) | [
"def",
"_compute",
"(",
"self",
",",
"inputs",
",",
"dates",
",",
"assets",
",",
"mask",
")",
":",
"to_sample",
"=",
"dates",
"[",
"select_sampling_indices",
"(",
"dates",
",",
"self",
".",
"_frequency",
")",
"]",
"assert",
"to_sample",
"[",
"0",
"]",
... | https://github.com/quantopian/zipline/blob/014f1fc339dc8b7671d29be2d85ce57d3daec343/zipline/pipeline/mixins.py#L491-L568 | |
andresriancho/w3af | cd22e5252243a87aaa6d0ddea47cf58dacfe00a9 | w3af/core/ui/gui/common/searchable.py | python | Searchable._matchCase | (self, widg) | Toggles self._matchCaseValue and searches again | Toggles self._matchCaseValue and searches again | [
"Toggles",
"self",
".",
"_matchCaseValue",
"and",
"searches",
"again"
] | def _matchCase(self, widg):
"""
Toggles self._matchCaseValue and searches again
"""
self._matchCaseValue = not self._matchCaseValue
self._find(None, 'find') | [
"def",
"_matchCase",
"(",
"self",
",",
"widg",
")",
":",
"self",
".",
"_matchCaseValue",
"=",
"not",
"self",
".",
"_matchCaseValue",
"self",
".",
"_find",
"(",
"None",
",",
"'find'",
")"
] | https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/ui/gui/common/searchable.py#L155-L160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.