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
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/docutils/transforms/parts.py
python
Contents.copy_and_filter
(self, node)
return visitor.get_entry_text()
Return a copy of a title, with references, images, etc. removed.
Return a copy of a title, with references, images, etc. removed.
[ "Return", "a", "copy", "of", "a", "title", "with", "references", "images", "etc", ".", "removed", "." ]
def copy_and_filter(self, node): """Return a copy of a title, with references, images, etc. removed.""" visitor = ContentsFilter(self.document) node.walkabout(visitor) return visitor.get_entry_text()
[ "def", "copy_and_filter", "(", "self", ",", "node", ")", ":", "visitor", "=", "ContentsFilter", "(", "self", ".", "document", ")", "node", ".", "walkabout", "(", "visitor", ")", "return", "visitor", ".", "get_entry_text", "(", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/docutils/transforms/parts.py#L151-L155
veusz/veusz
5a1e2af5f24df0eb2a2842be51f2997c4999c7fb
veusz/utils/extbrushfilling.py
python
_hatcher
(painter, pen, painterpath, spacing, hatchlist)
Draw hatching on painter path given.
Draw hatching on painter path given.
[ "Draw", "hatching", "on", "painter", "path", "given", "." ]
def _hatcher(painter, pen, painterpath, spacing, hatchlist): """Draw hatching on painter path given.""" painter.save() painter.setPen(pen) # debugging # dumppath(painterpath) painter.setClipPath(painterpath, qt.Qt.IntersectClip) # this is the bounding box of the path bb = painter.clipPath().boundingRect() for params in hatchlist: # scale values offsetx, offsety, deltax, deltay = [x*spacing for x in params] # compute max number of steps numsteps = 0 if deltax != 0: numsteps += int(bb.width() / abs(deltax)) + 4 if deltay != 0: numsteps += int(bb.height() / abs(deltay)) + 4 # calculate repeat position in x and y # we start the positions of lines at multiples of these distances # to ensure the pattern doesn't shift if the area does # distances between lines mag = math.sqrt(deltax**2 + deltay**2) # angle to x of perpendicular lines theta = math.atan2(deltay, deltax) s, c = math.sin(theta), math.cos(theta) intervalx = intervaly = 1. if abs(c) > 1e-4: intervalx = abs(mag / c) if abs(s) > 1e-4: intervaly = abs(mag / s) startx = int(bb.left() / intervalx) * intervalx + offsetx starty = int(bb.top() / intervaly) * intervaly + offsety # normalise line vector linedx, linedy = -deltay/mag, deltax/mag # scale of lines from start position scale = max( bb.width(), bb.height() ) * 4 # construct points along lines # this is scales to ensure the lines are bigger than the box idx = N.arange(-numsteps, numsteps) x = idx*deltax + startx y = idx*deltay + starty x1 = x - scale*linedx x2 = x + scale*linedx y1 = y - scale*linedy y2 = y + scale*linedy # plot lines, clipping to bb plotLinesToPainter(painter, x1, y1, x2, y2, bb) painter.restore()
[ "def", "_hatcher", "(", "painter", ",", "pen", ",", "painterpath", ",", "spacing", ",", "hatchlist", ")", ":", "painter", ".", "save", "(", ")", "painter", ".", "setPen", "(", "pen", ")", "# debugging", "# dumppath(painterpath)", "painter", ".", "setClipPath...
https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/utils/extbrushfilling.py#L46-L105
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/boto_iot.py
python
delete_thing_type
(thingTypeName, region=None, key=None, keyid=None, profile=None)
Given a thing type name, delete it. Returns {deleted: true} if the thing type was deleted and returns {deleted: false} if the thing type was not deleted. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.delete_thing_type mythingtype
Given a thing type name, delete it.
[ "Given", "a", "thing", "type", "name", "delete", "it", "." ]
def delete_thing_type(thingTypeName, region=None, key=None, keyid=None, profile=None): """ Given a thing type name, delete it. Returns {deleted: true} if the thing type was deleted and returns {deleted: false} if the thing type was not deleted. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_iot.delete_thing_type mythingtype """ try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_thing_type(thingTypeName=thingTypeName) return {"deleted": True} except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "ResourceNotFoundException": return {"deleted": True} return {"deleted": False, "error": err}
[ "def", "delete_thing_type", "(", "thingTypeName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/boto_iot.py#L242-L267
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Utils/ElementTreeUtils.py
python
iterparse
(file, elementName, callback, limit = -1)
Parse iteratively xml-files This function offers a simple way to use the cElementTree iterparse-function the way it is often used. Keyword arguments: file -- (file) file or file-like object to parse elementName -- (string) matching elements are passed to the callback callback -- (function) called when parser has parsed an element of name elementName limit -- (int) stop after reading "limit" elements. If -1, read until end of file. This is mostly useful when debugging programs that parse large files.
Parse iteratively xml-files This function offers a simple way to use the cElementTree iterparse-function the way it is often used. Keyword arguments: file -- (file) file or file-like object to parse elementName -- (string) matching elements are passed to the callback callback -- (function) called when parser has parsed an element of name elementName limit -- (int) stop after reading "limit" elements. If -1, read until end of file. This is mostly useful when debugging programs that parse large files.
[ "Parse", "iteratively", "xml", "-", "files", "This", "function", "offers", "a", "simple", "way", "to", "use", "the", "cElementTree", "iterparse", "-", "function", "the", "way", "it", "is", "often", "used", ".", "Keyword", "arguments", ":", "file", "--", "(...
def iterparse(file, elementName, callback, limit = -1): """ Parse iteratively xml-files This function offers a simple way to use the cElementTree iterparse-function the way it is often used. Keyword arguments: file -- (file) file or file-like object to parse elementName -- (string) matching elements are passed to the callback callback -- (function) called when parser has parsed an element of name elementName limit -- (int) stop after reading "limit" elements. If -1, read until end of file. This is mostly useful when debugging programs that parse large files. """ context = ElementTree.iterparse(file, events=("start", "end")) root = None for event, elem in context: if limit == 0: return if event == "start" and root is None: root = elem # the first element is root if event == "end" and elem.tag == elementName: #elem.tag == "record": #... process record elements ... callback(elem) root.clear() if limit != -1: limit -= 1
[ "def", "iterparse", "(", "file", ",", "elementName", ",", "callback", ",", "limit", "=", "-", "1", ")", ":", "context", "=", "ElementTree", ".", "iterparse", "(", "file", ",", "events", "=", "(", "\"start\"", ",", "\"end\"", ")", ")", "root", "=", "N...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/ElementTreeUtils.py#L28-L57
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/mailbox.py
python
Mailbox.keys
(self)
return list(self.iterkeys())
Return a list of keys.
Return a list of keys.
[ "Return", "a", "list", "of", "keys", "." ]
def keys(self): """Return a list of keys.""" return list(self.iterkeys())
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ".", "iterkeys", "(", ")", ")" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/mailbox.py#L100-L102
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/converters/nastran/gui/menus/element_menu.py
python
ElementWindow.__init__
(self, data, controls, win_parent=None)
create a cONTROL surface
create a cONTROL surface
[ "create", "a", "cONTROL", "surface" ]
def __init__(self, data, controls, win_parent=None): """create a cONTROL surface""" PyDialog.__init__(self, data, win_parent) self._updated_menu = False self.controls = controls self.comment_label = QLabel('Comment') self.comment_edit = QLineEdit() self.eid_label = QLabel('Element ID') self.eid_edit = QElementEdit(self, str(''), pick_style='single', tab_to_next=False) self.pid_label = QLabel('Property ID') self.pid_edit = QLineEdit() self.mid_label = QLabel('Material ID') self.mid_edit = QLineEdit() self.n1_label = QLabel('Node 1') self.n2_label = QLabel('Node 2') self.n3_label = QLabel('Node 3') self.n4_label = QLabel('Node 4') self.n5_label = QLabel('Node 5') self.n6_label = QLabel('Node 6') self.n7_label = QLabel('Node 7') self.n8_label = QLabel('Node 8') self.n9_label = QLabel('Node 9') self.n10_label = QLabel('Node 10') self.n1_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n2_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n3_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n4_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n5_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n6_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n7_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n8_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n9_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) self.n10_edit = QNodeEdit(self, str(''), pick_style='single', tab_to_next=True) for inode in range(3, 10+1): # 3-10 inode_label = 'n%i_label' % inode inode_edit = 'n%i_edit' % inode getattr(self, inode_label).setVisible(False) getattr(self, inode_edit).setVisible(False) self.mcsid_label = QLabel('Material Coord') self.mcsid_pulldown = QComboBox() self.element_type_label = QLabel('Element Type') self.element_type_pulldown = QComboBox() ELEMENT_TYPES = ['CROD', 'CONROD', 'CTRIA3', 'CQUAD4'] self.element_types = ELEMENT_TYPES for element_type in ELEMENT_TYPES: self.element_type_pulldown.addItem(element_type) self.element_type = ELEMENT_TYPES[0] self.method_type_label = QLabel('Method Type') self.method_type_pulldown = QComboBox() self.method_types = ['Create', 'Edit', 'Delete'] METHOD_TYPES = ['Create', 'Edit', 'Delete'] for method_type in METHOD_TYPES: self.method_type_pulldown.addItem(method_type) self.method_type = METHOD_TYPES[0] #cases = get_cases_from_tree(self.controls) #parent = self #name = 'main' #data = self.controls #choices = cases #self.results_widget_label = QLabel('Results:') #self.results_widget = ResultsWindow( #parent, name, data, choices, #include_clear=False, include_delete=True, #include_results=False) self.add_button = QPushButton('Create') self.delete_button = QPushButton('Delete') self.apply_button = QPushButton('Apply') self.setup_layout() self.setup_connections()
[ "def", "__init__", "(", "self", ",", "data", ",", "controls", ",", "win_parent", "=", "None", ")", ":", "PyDialog", ".", "__init__", "(", "self", ",", "data", ",", "win_parent", ")", "self", ".", "_updated_menu", "=", "False", "self", ".", "controls", ...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/converters/nastran/gui/menus/element_menu.py#L58-L142
AwesomeTTS/awesometts-anki-addon
c7c2c94479b610b9767ec44cdbb825002bc0c2b7
awesometts/player.py
python
Player.menu_click
(self, path)
Play path with no delay, from context menu.
Play path with no delay, from context menu.
[ "Play", "path", "with", "no", "delay", "from", "context", "menu", "." ]
def menu_click(self, path): """Play path with no delay, from context menu.""" self._anki.native(path)
[ "def", "menu_click", "(", "self", ",", "path", ")", ":", "self", ".", "_anki", ".", "native", "(", "path", ")" ]
https://github.com/AwesomeTTS/awesometts-anki-addon/blob/c7c2c94479b610b9767ec44cdbb825002bc0c2b7/awesometts/player.py#L51-L54
HuberTRoy/MusicBox
82fdf21809b7f018c616c4d1c78cfbf04cd5d9e3
MusicPlayer/apis/netEaseApi.py
python
NetEaseWebApi.httpRequest
(self, *args, **kwargs)
return False
[]
def httpRequest(self, *args, **kwargs): data = kwargs.get('data') if data: kwargs['data'] = encrypted_request(data) logger.info("进行网易云Url请求, args: {0}, kwargs: {1}".format(args, kwargs)) html = super(NetEaseWebApi, self).httpRequest(*args, **kwargs) with ignored(): return json.loads(html.text) logger.info("url: {0} 请求失败. Header: {1}".format( args[0], kwargs.get('headers'))) return False
[ "def", "httpRequest", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "kwargs", ".", "get", "(", "'data'", ")", "if", "data", ":", "kwargs", "[", "'data'", "]", "=", "encrypted_request", "(", "data", ")", "logger", "....
https://github.com/HuberTRoy/MusicBox/blob/82fdf21809b7f018c616c4d1c78cfbf04cd5d9e3/MusicPlayer/apis/netEaseApi.py#L51-L64
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/posixpath.py
python
normcase
(s)
return s
Normalize case of pathname. Has no effect under Posix
Normalize case of pathname. Has no effect under Posix
[ "Normalize", "case", "of", "pathname", ".", "Has", "no", "effect", "under", "Posix" ]
def normcase(s): """Normalize case of pathname. Has no effect under Posix""" s = os.fspath(s) if not isinstance(s, (bytes, str)): raise TypeError("normcase() argument must be str or bytes, " "not '{}'".format(s.__class__.__name__)) return s
[ "def", "normcase", "(", "s", ")", ":", "s", "=", "os", ".", "fspath", "(", "s", ")", "if", "not", "isinstance", "(", "s", ",", "(", "bytes", ",", "str", ")", ")", ":", "raise", "TypeError", "(", "\"normcase() argument must be str or bytes, \"", "\"not '{...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/posixpath.py#L52-L58
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/NVDAObjects/__init__.py
python
NVDAObject._get_controllerFor
(self)
return []
Retrieves the object/s that this object controls.
Retrieves the object/s that this object controls.
[ "Retrieves", "the", "object", "/", "s", "that", "this", "object", "controls", "." ]
def _get_controllerFor(self): """Retrieves the object/s that this object controls.""" return []
[ "def", "_get_controllerFor", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/NVDAObjects/__init__.py#L495-L497
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/lib2to3/pytree.py
python
BasePattern.optimize
(self)
return self
A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect.
A subclass can define this as a hook for optimizations.
[ "A", "subclass", "can", "define", "this", "as", "a", "hook", "for", "optimizations", "." ]
def optimize(self): """ A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect. """ return self
[ "def", "optimize", "(", "self", ")", ":", "return", "self" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/lib2to3/pytree.py#L480-L486
puke3615/SceneClassify
96268082e5c07a06db647bb90d9b976d42bf852f
generator.py
python
Iterator._get_batches_of_transformed_samples
(self, index_array)
Gets a batch of transformed samples. # Arguments index_array: array of sample indices to include in batch. # Returns A batch of transformed samples.
Gets a batch of transformed samples.
[ "Gets", "a", "batch", "of", "transformed", "samples", "." ]
def _get_batches_of_transformed_samples(self, index_array): """Gets a batch of transformed samples. # Arguments index_array: array of sample indices to include in batch. # Returns A batch of transformed samples. """ raise NotImplementedError
[ "def", "_get_batches_of_transformed_samples", "(", "self", ",", "index_array", ")", ":", "raise", "NotImplementedError" ]
https://github.com/puke3615/SceneClassify/blob/96268082e5c07a06db647bb90d9b976d42bf852f/generator.py#L845-L854
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/venv/lib/python3.7/site-packages/setuptools/sandbox.py
python
save_modules
()
Context in which imported modules are saved. Translates exceptions internal to the context into the equivalent exception outside the context.
Context in which imported modules are saved.
[ "Context", "in", "which", "imported", "modules", "are", "saved", "." ]
def save_modules(): """ Context in which imported modules are saved. Translates exceptions internal to the context into the equivalent exception outside the context. """ saved = sys.modules.copy() with ExceptionSaver() as saved_exc: yield saved sys.modules.update(saved) # remove any modules imported since del_modules = ( mod_name for mod_name in sys.modules if mod_name not in saved # exclude any encodings modules. See #285 and not mod_name.startswith('encodings.') ) _clear_modules(del_modules) saved_exc.resume()
[ "def", "save_modules", "(", ")", ":", "saved", "=", "sys", ".", "modules", ".", "copy", "(", ")", "with", "ExceptionSaver", "(", ")", "as", "saved_exc", ":", "yield", "saved", "sys", ".", "modules", ".", "update", "(", "saved", ")", "# remove any modules...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/venv/lib/python3.7/site-packages/setuptools/sandbox.py#L145-L166
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/lms_xblock/runtime.py
python
LmsModuleSystem.handler_url
(self, *args, **kwargs)
return handler_url(*args, **kwargs)
Implement the XBlock runtime handler_url interface. This is mostly just proxying to the module level `handler_url` function defined higher up in this file. We're doing this indirection because the module level `handler_url` logic is also needed by the `DescriptorSystem`. The particular `handler_url` that a `DescriptorSystem` needs will be different when running an LMS process or a CMS/Studio process. That's accomplished by monkey-patching a global. It's a long story, but please know that you can't just refactor and fold that logic into here without breaking things. https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes See :method:`xblock.runtime:Runtime.handler_url`
Implement the XBlock runtime handler_url interface.
[ "Implement", "the", "XBlock", "runtime", "handler_url", "interface", "." ]
def handler_url(self, *args, **kwargs): # lint-amnesty, pylint: disable=signature-differs """ Implement the XBlock runtime handler_url interface. This is mostly just proxying to the module level `handler_url` function defined higher up in this file. We're doing this indirection because the module level `handler_url` logic is also needed by the `DescriptorSystem`. The particular `handler_url` that a `DescriptorSystem` needs will be different when running an LMS process or a CMS/Studio process. That's accomplished by monkey-patching a global. It's a long story, but please know that you can't just refactor and fold that logic into here without breaking things. https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes See :method:`xblock.runtime:Runtime.handler_url` """ return handler_url(*args, **kwargs)
[ "def", "handler_url", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# lint-amnesty, pylint: disable=signature-differs", "return", "handler_url", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/lms_xblock/runtime.py#L169-L188
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/unicode_rules.py
python
starts_with
(*chars)
return ( re.compile(r'^[%s]' % ''.join(chars)), f'must start with: {", ".join(regex_chars_to_text(chars))}' )
Restrict first character. Example: >>> regex, message = starts_with('a', 'b', 'c') >>> message 'must start with: ``a``, ``b``, ``c``' >>> bool(regex.match('def')) False >>> bool(regex.match('adef')) True
Restrict first character.
[ "Restrict", "first", "character", "." ]
def starts_with(*chars): """Restrict first character. Example: >>> regex, message = starts_with('a', 'b', 'c') >>> message 'must start with: ``a``, ``b``, ``c``' >>> bool(regex.match('def')) False >>> bool(regex.match('adef')) True """ return ( re.compile(r'^[%s]' % ''.join(chars)), f'must start with: {", ".join(regex_chars_to_text(chars))}' )
[ "def", "starts_with", "(", "*", "chars", ")", ":", "return", "(", "re", ".", "compile", "(", "r'^[%s]'", "%", "''", ".", "join", "(", "chars", ")", ")", ",", "f'must start with: {\", \".join(regex_chars_to_text(chars))}'", ")" ]
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/unicode_rules.py#L112-L128
ucfopen/canvasapi
3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36
canvasapi/outcome.py
python
OutcomeGroup.import_outcome_group
(self, outcome_group)
return OutcomeGroup(self._requester, response.json())
Import an outcome group as a subgroup into the current outcome group :calls: `POST /api/v1/global/outcome_groups/:id/import \ <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.import>`_ or `POST /api/v1/accounts/:account_id/outcome_groups/:id/import \ <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.import>`_ or `POST /api/v1/courses/:course_id/outcome_groups/:id/import \ <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.import>`_ :param outcome: The object or ID of the outcome group to import. :type outcome: :class:`canvasapi.outcome.OutcomeGroup` or int :returns: Itself as an OutcomeGroup object. :rtype: :class:`canvasapi.outcome.OutcomeGroup`
Import an outcome group as a subgroup into the current outcome group
[ "Import", "an", "outcome", "group", "as", "a", "subgroup", "into", "the", "current", "outcome", "group" ]
def import_outcome_group(self, outcome_group): """ Import an outcome group as a subgroup into the current outcome group :calls: `POST /api/v1/global/outcome_groups/:id/import \ <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.import>`_ or `POST /api/v1/accounts/:account_id/outcome_groups/:id/import \ <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.import>`_ or `POST /api/v1/courses/:course_id/outcome_groups/:id/import \ <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.import>`_ :param outcome: The object or ID of the outcome group to import. :type outcome: :class:`canvasapi.outcome.OutcomeGroup` or int :returns: Itself as an OutcomeGroup object. :rtype: :class:`canvasapi.outcome.OutcomeGroup` """ source_outcome_group_id = obj_or_id( outcome_group, "outcome_group", (OutcomeGroup,) ) response = self._requester.request( "POST", "{}/outcome_groups/{}/import".format(self.context_ref(), self.id), source_outcome_group_id=source_outcome_group_id, ) return OutcomeGroup(self._requester, response.json())
[ "def", "import_outcome_group", "(", "self", ",", "outcome_group", ")", ":", "source_outcome_group_id", "=", "obj_or_id", "(", "outcome_group", ",", "\"outcome_group\"", ",", "(", "OutcomeGroup", ",", ")", ")", "response", "=", "self", ".", "_requester", ".", "re...
https://github.com/ucfopen/canvasapi/blob/3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36/canvasapi/outcome.py#L297-L324
lunixbochs/ActualVim
1f555ce719e49d6584f0e35e9f0db2f216b98fa5
lib/neovim/api/buffer.py
python
Buffer.__iter__
(self)
Iterate lines of a buffer. This will retrieve all lines locally before iteration starts. This approach is used because for most cases, the gain is much greater by minimizing the number of API calls by transfering all data needed to work.
Iterate lines of a buffer.
[ "Iterate", "lines", "of", "a", "buffer", "." ]
def __iter__(self): """Iterate lines of a buffer. This will retrieve all lines locally before iteration starts. This approach is used because for most cases, the gain is much greater by minimizing the number of API calls by transfering all data needed to work. """ lines = self[:] for line in lines: yield line
[ "def", "__iter__", "(", "self", ")", ":", "lines", "=", "self", "[", ":", "]", "for", "line", "in", "lines", ":", "yield", "line" ]
https://github.com/lunixbochs/ActualVim/blob/1f555ce719e49d6584f0e35e9f0db2f216b98fa5/lib/neovim/api/buffer.py#L75-L85
beetbox/audioread
5afc8a6dcb8ab801d19d67dc77fe8824ad04acb5
audioread/gstdec.py
python
GstAudioFile.close
(self, force=False)
Close the file and clean up associated resources. Calling `close()` a second time has no effect.
Close the file and clean up associated resources.
[ "Close", "the", "file", "and", "clean", "up", "associated", "resources", "." ]
def close(self, force=False): """Close the file and clean up associated resources. Calling `close()` a second time has no effect. """ if self.running or force: self.running = False self.finished = True # Unregister for signals, which we registered for above with # `add_signal_watch`. (Without this, GStreamer leaks file # descriptors.) self.pipeline.get_bus().remove_signal_watch() # Stop reading the file. self.dec.set_property("uri", None) # Block spurious signals. self.sink.get_static_pad("sink").disconnect(self.caps_handler) # Make space in the output queue to let the decoder thread # finish. (Otherwise, the thread blocks on its enqueue and # the interpreter hangs.) try: self.queue.get_nowait() except queue.Empty: pass # Halt the pipeline (closing file). self.pipeline.set_state(Gst.State.NULL)
[ "def", "close", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "running", "or", "force", ":", "self", ".", "running", "=", "False", "self", ".", "finished", "=", "True", "# Unregister for signals, which we registered for above with", "# ...
https://github.com/beetbox/audioread/blob/5afc8a6dcb8ab801d19d67dc77fe8824ad04acb5/audioread/gstdec.py#L377-L405
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/extensions_v1beta1_ingress_backend.py
python
ExtensionsV1beta1IngressBackend.resource
(self)
return self._resource
Gets the resource of this ExtensionsV1beta1IngressBackend. # noqa: E501 :return: The resource of this ExtensionsV1beta1IngressBackend. # noqa: E501 :rtype: V1TypedLocalObjectReference
Gets the resource of this ExtensionsV1beta1IngressBackend. # noqa: E501
[ "Gets", "the", "resource", "of", "this", "ExtensionsV1beta1IngressBackend", ".", "#", "noqa", ":", "E501" ]
def resource(self): """Gets the resource of this ExtensionsV1beta1IngressBackend. # noqa: E501 :return: The resource of this ExtensionsV1beta1IngressBackend. # noqa: E501 :rtype: V1TypedLocalObjectReference """ return self._resource
[ "def", "resource", "(", "self", ")", ":", "return", "self", ".", "_resource" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/extensions_v1beta1_ingress_backend.py#L66-L73
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/urllib3/util/ssltransport.py
python
SSLTransport.__enter__
(self)
return self
[]
def __enter__(self): return self
[ "def", "__enter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/urllib3/util/ssltransport.py#L63-L64
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/objects/ocel/util/filtering_utils.py
python
propagate_relations_filtering
(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None)
return ocel
Propagates the filtering at the relations level to the remaining parts of the OCEL structure (events, objects) Parameters ---------------- ocel Object-centric event log parameters Parameters of the algorithm, including: - Parameters.EVENT_ID => the column to be used as case identifier - Parameters.OBJECT_ID => the column to be used as object identifier - Parameters.OBJECT_TYPE => the column to be used as object type Returns ---------------- ocel Object-centric event log with propagated filter
Propagates the filtering at the relations level to the remaining parts of the OCEL structure (events, objects)
[ "Propagates", "the", "filtering", "at", "the", "relations", "level", "to", "the", "remaining", "parts", "of", "the", "OCEL", "structure", "(", "events", "objects", ")" ]
def propagate_relations_filtering(ocel: OCEL, parameters: Optional[Dict[Any, Any]] = None) -> OCEL: """ Propagates the filtering at the relations level to the remaining parts of the OCEL structure (events, objects) Parameters ---------------- ocel Object-centric event log parameters Parameters of the algorithm, including: - Parameters.EVENT_ID => the column to be used as case identifier - Parameters.OBJECT_ID => the column to be used as object identifier - Parameters.OBJECT_TYPE => the column to be used as object type Returns ---------------- ocel Object-centric event log with propagated filter """ if parameters is None: parameters = {} event_id = exec_utils.get_param_value(Parameters.EVENT_ID, parameters, ocel.event_id_column) object_id = exec_utils.get_param_value(Parameters.OBJECT_ID, parameters, ocel.object_id_column) selected_event_ids = set(ocel.relations[event_id].unique()) selected_object_ids = set(ocel.relations[object_id].unique()) ocel.events = ocel.events[ocel.events[event_id].isin(selected_event_ids)] ocel.objects = ocel.objects[ocel.objects[object_id].isin(selected_object_ids)] return ocel
[ "def", "propagate_relations_filtering", "(", "ocel", ":", "OCEL", ",", "parameters", ":", "Optional", "[", "Dict", "[", "Any", ",", "Any", "]", "]", "=", "None", ")", "->", "OCEL", ":", "if", "parameters", "is", "None", ":", "parameters", "=", "{", "}"...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/objects/ocel/util/filtering_utils.py#L98-L129
alan-turing-institute/sktime
79cc513346b1257a6f3fa8e4ed855b5a2a7de716
sktime/forecasting/hcrystalball.py
python
_adapt_y_pred
(y_pred)
return y_pred.iloc[:, 0]
Translate wrapper prediction to sktime format. From Dataframe to series. Parameters ---------- y_pred : pd.DataFrame Returns ------- pd.Series Predictions in form of series
Translate wrapper prediction to sktime format.
[ "Translate", "wrapper", "prediction", "to", "sktime", "format", "." ]
def _adapt_y_pred(y_pred): """Translate wrapper prediction to sktime format. From Dataframe to series. Parameters ---------- y_pred : pd.DataFrame Returns ------- pd.Series Predictions in form of series """ return y_pred.iloc[:, 0]
[ "def", "_adapt_y_pred", "(", "y_pred", ")", ":", "return", "y_pred", ".", "iloc", "[", ":", ",", "0", "]" ]
https://github.com/alan-turing-institute/sktime/blob/79cc513346b1257a6f3fa8e4ed855b5a2a7de716/sktime/forecasting/hcrystalball.py#L83-L97
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/pyxmpp2/ext/component.py
python
ComponentStream._post_connect
(self)
Initialize authentication when the connection is established and we are the initiator.
Initialize authentication when the connection is established and we are the initiator.
[ "Initialize", "authentication", "when", "the", "connection", "is", "established", "and", "we", "are", "the", "initiator", "." ]
def _post_connect(self): """Initialize authentication when the connection is established and we are the initiator.""" if self.initiator: self._auth()
[ "def", "_post_connect", "(", "self", ")", ":", "if", "self", ".", "initiator", ":", "self", ".", "_auth", "(", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/pyxmpp2/ext/component.py#L132-L136
tahoe-lafs/tahoe-lafs
766a53b5208c03c45ca0a98e97eee76870276aa1
src/allmydata/web/root.py
python
URIHandler.render_POST
(self, req)
"POST /uri?t=upload&file=newfile" to upload an unlinked file or "POST /uri?t=mkdir" to create a new directory
"POST /uri?t=upload&file=newfile" to upload an unlinked file or "POST /uri?t=mkdir" to create a new directory
[ "POST", "/", "uri?t", "=", "upload&file", "=", "newfile", "to", "upload", "an", "unlinked", "file", "or", "POST", "/", "uri?t", "=", "mkdir", "to", "create", "a", "new", "directory" ]
def render_POST(self, req): """ "POST /uri?t=upload&file=newfile" to upload an unlinked file or "POST /uri?t=mkdir" to create a new directory """ t = str(get_arg(req, "t", "").strip(), "ascii") if t in ("", "upload"): file_format = get_format(req) mutable_type = get_mutable_type(file_format) if mutable_type is not None: return unlinked.POSTUnlinkedSSK(req, self.client, mutable_type) else: return unlinked.POSTUnlinkedCHK(req, self.client) if t == "mkdir": return unlinked.POSTUnlinkedCreateDirectory(req, self.client) elif t == "mkdir-with-children": return unlinked.POSTUnlinkedCreateDirectoryWithChildren(req, self.client) elif t == "mkdir-immutable": return unlinked.POSTUnlinkedCreateImmutableDirectory(req, self.client) errmsg = ("/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, " "and POST?t=mkdir") raise WebError(errmsg, http.BAD_REQUEST)
[ "def", "render_POST", "(", "self", ",", "req", ")", ":", "t", "=", "str", "(", "get_arg", "(", "req", ",", "\"t\"", ",", "\"\"", ")", ".", "strip", "(", ")", ",", "\"ascii\"", ")", "if", "t", "in", "(", "\"\"", ",", "\"upload\"", ")", ":", "fil...
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/web/root.py#L127-L151
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client_builder/grr_response_client_builder/builders/windows.py
python
WindowsClientBuilder.BuildNanny
(self, dest_dir: str)
Use VS2010 to build the windows Nanny service.
Use VS2010 to build the windows Nanny service.
[ "Use", "VS2010", "to", "build", "the", "windows", "Nanny", "service", "." ]
def BuildNanny(self, dest_dir: str): """Use VS2010 to build the windows Nanny service.""" # When running under cygwin, the following environment variables are not set # (since they contain invalid chars). Visual Studio requires these or it # will fail. os.environ["ProgramFiles(x86)"] = r"C:\Program Files (x86)" with utils.TempDirectory() as temp_dir: nanny_dir = os.path.join(temp_dir, "grr", "client", "grr_response_client", "nanny") nanny_src_dir = config.CONFIG.Get( "ClientBuilder.nanny_source_dir", context=self.context) logging.info("Copying Nanny build files from %s to %s", nanny_src_dir, nanny_dir) shutil.copytree( config.CONFIG.Get( "ClientBuilder.nanny_source_dir", context=self.context), nanny_dir) build_type = config.CONFIG.Get( "ClientBuilder.build_type", context=self.context) vs_arch = config.CONFIG.Get( "ClientBuilder.vs_arch", default=None, context=self.context) # We have to set up the Visual Studio environment first and then call # msbuild. env_script = config.CONFIG.Get( "ClientBuilder.vs_env_script", default=None, context=self.context) if vs_arch is None or env_script is None or not os.path.exists( env_script) or config.CONFIG.Get( "ClientBuilder.use_prebuilt_nanny", context=self.context): # Visual Studio is not installed. We just use pre-built binaries in that # case. logging.warning( "Visual Studio does not appear to be installed, " "Falling back to prebuilt GRRNanny binaries." "If you want to build it you must have VS 2012 installed.") binaries_dir = config.CONFIG.Get( "ClientBuilder.nanny_prebuilt_binaries", context=self.context) shutil.copy( os.path.join(binaries_dir, "GRRNanny_%s.exe" % vs_arch), os.path.join(dest_dir, "GRRservice.exe")) else: # Lets build the nanny with the VS env script. subprocess.check_call( "cmd /c \"\"%s\" && msbuild /p:Configuration=%s;Platform=%s\"" % (env_script, build_type, vs_arch), cwd=nanny_dir) # The templates always contain the same filenames - the repack step # might rename them later. shutil.copy( os.path.join(nanny_dir, vs_arch, build_type, "GRRNanny.exe"), os.path.join(dest_dir, "GRRservice.exe"))
[ "def", "BuildNanny", "(", "self", ",", "dest_dir", ":", "str", ")", ":", "# When running under cygwin, the following environment variables are not set", "# (since they contain invalid chars). Visual Studio requires these or it", "# will fail.", "os", ".", "environ", "[", "\"Program...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client_builder/grr_response_client_builder/builders/windows.py#L230-L288
shmilylty/OneForAll
48591142a641e80f8a64ab215d11d06b696702d7
common/tablib/tablib.py
python
Dataset.insert
(self, index, row, tags=None)
Inserts a row to the :class:`Dataset` at the given index. Rows inserted must be the correct size (height or width). The default behaviour is to insert the given row to the :class:`Dataset` object at the given index.
Inserts a row to the :class:`Dataset` at the given index.
[ "Inserts", "a", "row", "to", "the", ":", "class", ":", "Dataset", "at", "the", "given", "index", "." ]
def insert(self, index, row, tags=None): """Inserts a row to the :class:`Dataset` at the given index. Rows inserted must be the correct size (height or width). The default behaviour is to insert the given row to the :class:`Dataset` object at the given index. """ if tags is None: tags = list() self._validate(row) self._data.insert(index, Row(row, tags=tags))
[ "def", "insert", "(", "self", ",", "index", ",", "row", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "list", "(", ")", "self", ".", "_validate", "(", "row", ")", "self", ".", "_data", ".", "insert", "(", "in...
https://github.com/shmilylty/OneForAll/blob/48591142a641e80f8a64ab215d11d06b696702d7/common/tablib/tablib.py#L289-L301
knownsec/ZoomEye-python
30b4a69e5724fce91c1dbd7afa1b04dafb048a58
zoomeye/data.py
python
filter_search_data
(keys, field_table, data)
return result
get the data of the corresponding field :param keys: list, user input field :param field_table: dict, fileds :param data: list, zoomeye api data :return: list, ex: [[1,2,3...],[1,2,3...],[1,2,3...]...]
get the data of the corresponding field :param keys: list, user input field :param field_table: dict, fileds :param data: list, zoomeye api data :return: list, ex: [[1,2,3...],[1,2,3...],[1,2,3...]...]
[ "get", "the", "data", "of", "the", "corresponding", "field", ":", "param", "keys", ":", "list", "user", "input", "field", ":", "param", "field_table", ":", "dict", "fileds", ":", "param", "data", ":", "list", "zoomeye", "api", "data", ":", "return", ":",...
def filter_search_data(keys, field_table, data): """ get the data of the corresponding field :param keys: list, user input field :param field_table: dict, fileds :param data: list, zoomeye api data :return: list, ex: [[1,2,3...],[1,2,3...],[1,2,3...]...] """ result = [] for d in data: item = [] zmdict = ZoomEyeDict(d) for key in keys: if field_table.get(key.strip()) is None: support_fields = ','.join(list(field_table.keys())) show.printf("filter command has unsupport fields [{}], support fields has [{}]" .format(key, support_fields), color='red') exit(0) res = zmdict.find(field_table.get(key.strip())) if key == "timestamp": utc_time = datetime.datetime.strptime(res, "%Y-%m-%dT%H:%M:%S") res = str(utc_time + datetime.timedelta(hours=8)) item.append(res) result.append(item) return result
[ "def", "filter_search_data", "(", "keys", ",", "field_table", ",", "data", ")", ":", "result", "=", "[", "]", "for", "d", "in", "data", ":", "item", "=", "[", "]", "zmdict", "=", "ZoomEyeDict", "(", "d", ")", "for", "key", "in", "keys", ":", "if", ...
https://github.com/knownsec/ZoomEye-python/blob/30b4a69e5724fce91c1dbd7afa1b04dafb048a58/zoomeye/data.py#L165-L189
NiaOrg/NiaPy
08f24ffc79fe324bc9c66ee7186ef98633026005
niapy/algorithms/basic/ca.py
python
Camel.next_supply
(self, burden_factor, max_iters)
r"""Apply nextS on Camel. Args: burden_factor (float): Burden factor. max_iters (int): Number of Camel Algorithm iterations/generations.
r"""Apply nextS on Camel.
[ "r", "Apply", "nextS", "on", "Camel", "." ]
def next_supply(self, burden_factor, max_iters): r"""Apply nextS on Camel. Args: burden_factor (float): Burden factor. max_iters (int): Number of Camel Algorithm iterations/generations. """ self.supply = self.supply_past * (1 - burden_factor * self.steps / max_iters)
[ "def", "next_supply", "(", "self", ",", "burden_factor", ",", "max_iters", ")", ":", "self", ".", "supply", "=", "self", ".", "supply_past", "*", "(", "1", "-", "burden_factor", "*", "self", ".", "steps", "/", "max_iters", ")" ]
https://github.com/NiaOrg/NiaPy/blob/08f24ffc79fe324bc9c66ee7186ef98633026005/niapy/algorithms/basic/ca.py#L75-L83
Mindwerks/worldengine
64dff8eb7824ce46b5b6cb8006bcef21822ef144
worldengine/model/world.py
python
World.has_watermap
(self)
return 'watermap' in self.layers
[]
def has_watermap(self): return 'watermap' in self.layers
[ "def", "has_watermap", "(", "self", ")", ":", "return", "'watermap'", "in", "self", ".", "layers" ]
https://github.com/Mindwerks/worldengine/blob/64dff8eb7824ce46b5b6cb8006bcef21822ef144/worldengine/model/world.py#L897-L898
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/logilab/astng/as_string.py
python
AsStringVisitor.__call__
(self, node)
return node.accept(self)
Makes this visitor behave as a simple function
Makes this visitor behave as a simple function
[ "Makes", "this", "visitor", "behave", "as", "a", "simple", "function" ]
def __call__(self, node): """Makes this visitor behave as a simple function""" return node.accept(self)
[ "def", "__call__", "(", "self", ",", "node", ")", ":", "return", "node", ".", "accept", "(", "self", ")" ]
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/logilab/astng/as_string.py#L44-L46
guillermooo/Vintageous
f958207009902052aed5fcac09745f1742648604
state.py
python
State.is_recording
(self, value)
[]
def is_recording(self, value): assert isinstance(value, bool), 'bad call' self.settings.vi['recording'] = value
[ "def", "is_recording", "(", "self", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "bool", ")", ",", "'bad call'", "self", ".", "settings", ".", "vi", "[", "'recording'", "]", "=", "value" ]
https://github.com/guillermooo/Vintageous/blob/f958207009902052aed5fcac09745f1742648604/state.py#L541-L543
sendgrid/sendgrid-python
df13b78b0cdcb410b4516f6761c4d3138edd4b2d
sendgrid/helpers/mail/email.py
python
Email.get
(self)
return email
Get a JSON-ready representation of this Email. :returns: This Email, ready for use in a request body. :rtype: dict
Get a JSON-ready representation of this Email.
[ "Get", "a", "JSON", "-", "ready", "representation", "of", "this", "Email", "." ]
def get(self): """ Get a JSON-ready representation of this Email. :returns: This Email, ready for use in a request body. :rtype: dict """ email = {} if self.name is not None: email["name"] = self.name if self.email is not None: email["email"] = self.email return email
[ "def", "get", "(", "self", ")", ":", "email", "=", "{", "}", "if", "self", ".", "name", "is", "not", "None", ":", "email", "[", "\"name\"", "]", "=", "self", ".", "name", "if", "self", ".", "email", "is", "not", "None", ":", "email", "[", "\"em...
https://github.com/sendgrid/sendgrid-python/blob/df13b78b0cdcb410b4516f6761c4d3138edd4b2d/sendgrid/helpers/mail/email.py#L215-L228
pykaldi/pykaldi
b4e7a15a31286e57c01259edfda54d113b5ceb0e
kaldi/kws/__init__.py
python
search_kws_index
(index, keyword, encode_table, n_best=-1, detailed=False)
Searches given keyword (FST) inside the KWS index (FST). Returns the `n_best` results found. Each result is a tuple of `(utt_id, time_beg, time_end, score)`. Since keyword can be an FST, there can be multiple matching paths in the keyword and the index in a given time period. If `detailed == True`, stats output provides the results for all matching paths together with appropriate scores while ilabels output provides the input labels on those paths. Args: index (KwsIndexVectorFst): The index FST. keyword (StdVectorFst): The keyword FST. encode_table (KwsIndexEncodeTable): The table to use for decoding output labels into utterance ids. This table is produced by :meth:`encode_kws_disambiguation_symbols`. n_best (int): The number of best results to return. If <= 0, all results found in the index are returned. detailed (bool): Whether to return detailed results representing individual index matches and the input label sequences for those matches. If True, output is a tuple of (results, stats, ilabels).
Searches given keyword (FST) inside the KWS index (FST).
[ "Searches", "given", "keyword", "(", "FST", ")", "inside", "the", "KWS", "index", "(", "FST", ")", "." ]
def search_kws_index(index, keyword, encode_table, n_best=-1, detailed=False): """Searches given keyword (FST) inside the KWS index (FST). Returns the `n_best` results found. Each result is a tuple of `(utt_id, time_beg, time_end, score)`. Since keyword can be an FST, there can be multiple matching paths in the keyword and the index in a given time period. If `detailed == True`, stats output provides the results for all matching paths together with appropriate scores while ilabels output provides the input labels on those paths. Args: index (KwsIndexVectorFst): The index FST. keyword (StdVectorFst): The keyword FST. encode_table (KwsIndexEncodeTable): The table to use for decoding output labels into utterance ids. This table is produced by :meth:`encode_kws_disambiguation_symbols`. n_best (int): The number of best results to return. If <= 0, all results found in the index are returned. detailed (bool): Whether to return detailed results representing individual index matches and the input label sequences for those matches. If True, output is a tuple of (results, stats, ilabels). """ if detailed: results, matched_seq = _kws_functions._search_kws_index_detailed( index, keyword, encode_table, n_best) stats, ilabels = _kws_functions._compute_detailed_statistics( matched_seq, encode_table) return results, stats, ilabels else: return _kws_functions._search_kws_index(index, keyword, encode_table, n_best)
[ "def", "search_kws_index", "(", "index", ",", "keyword", ",", "encode_table", ",", "n_best", "=", "-", "1", ",", "detailed", "=", "False", ")", ":", "if", "detailed", ":", "results", ",", "matched_seq", "=", "_kws_functions", ".", "_search_kws_index_detailed",...
https://github.com/pykaldi/pykaldi/blob/b4e7a15a31286e57c01259edfda54d113b5ceb0e/kaldi/kws/__init__.py#L40-L71
ioflo/ioflo
177ac656d7c4ff801aebb0d8b401db365a5248ce
ioflo/aid/odicting.py
python
modict.__init__
(self, *pa, **kwa)
modict() -> new empty modict instance. modict(pa1, pa2, ...) where pa = tuple of positional args, (pa1, pa2, ...) each paX may be a sequence of duples (k,v) or a dict modict(k1 = v1, k2 = v2, ...) where kwa = dictionary of keyword args, {k1: v1, k2 : v2, ...}
modict() -> new empty modict instance.
[ "modict", "()", "-", ">", "new", "empty", "modict", "instance", "." ]
def __init__(self, *pa, **kwa): """ modict() -> new empty modict instance. modict(pa1, pa2, ...) where pa = tuple of positional args, (pa1, pa2, ...) each paX may be a sequence of duples (k,v) or a dict modict(k1 = v1, k2 = v2, ...) where kwa = dictionary of keyword args, {k1: v1, k2 : v2, ...} """ super(modict, self).__init__() # must do this first self.update(*pa, **kwa)
[ "def", "__init__", "(", "self", ",", "*", "pa", ",", "*", "*", "kwa", ")", ":", "super", "(", "modict", ",", "self", ")", ".", "__init__", "(", ")", "# must do this first", "self", ".", "update", "(", "*", "pa", ",", "*", "*", "kwa", ")" ]
https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/aid/odicting.py#L407-L418
sabri-zaki/EasY_HaCk
2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9
.modules/.sqlmap/thirdparty/odict/odict.py
python
_OrderedDict.popitem
(self, i=-1)
return (key, self.pop(key))
Delete and return an item specified by index, not a random one as in dict. The index is -1 by default (the last item). >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.popitem() (2, 1) >>> d OrderedDict([(1, 3), (3, 2)]) >>> d.popitem(0) (1, 3) >>> OrderedDict().popitem() Traceback (most recent call last): KeyError: 'popitem(): dictionary is empty' >>> d.popitem(2) Traceback (most recent call last): IndexError: popitem(): index 2 not valid
Delete and return an item specified by index, not a random one as in dict. The index is -1 by default (the last item).
[ "Delete", "and", "return", "an", "item", "specified", "by", "index", "not", "a", "random", "one", "as", "in", "dict", ".", "The", "index", "is", "-", "1", "by", "default", "(", "the", "last", "item", ")", "." ]
def popitem(self, i=-1): """ Delete and return an item specified by index, not a random one as in dict. The index is -1 by default (the last item). >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.popitem() (2, 1) >>> d OrderedDict([(1, 3), (3, 2)]) >>> d.popitem(0) (1, 3) >>> OrderedDict().popitem() Traceback (most recent call last): KeyError: 'popitem(): dictionary is empty' >>> d.popitem(2) Traceback (most recent call last): IndexError: popitem(): index 2 not valid """ if not self._sequence: raise KeyError('popitem(): dictionary is empty') try: key = self._sequence[i] except IndexError: raise IndexError('popitem(): index %s not valid' % i) return (key, self.pop(key))
[ "def", "popitem", "(", "self", ",", "i", "=", "-", "1", ")", ":", "if", "not", "self", ".", "_sequence", ":", "raise", "KeyError", "(", "'popitem(): dictionary is empty'", ")", "try", ":", "key", "=", "self", ".", "_sequence", "[", "i", "]", "except", ...
https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.sqlmap/thirdparty/odict/odict.py#L624-L649
osroom/osroom
fcb9b7c5e5cfd8e919f8d87521800e70b09b5b44
apps/modules/plug_in_manager/process/setting.py
python
install_require_package
()
return data
安装插件需要的其他python 包 :return:
安装插件需要的其他python 包 :return:
[ "安装插件需要的其他python", "包", ":", "return", ":" ]
def install_require_package(): """ 安装插件需要的其他python 包 :return: """ plugin_name = request.argget.all('plugin_name') s, r = arg_verify(reqargs=[("plugin name", plugin_name)], required=True) if not s: return r plugin_req_file_path = "{}/requirements.txt".format( os.path.join(PLUG_IN_FOLDER, plugin_name)) if not os.path.exists(plugin_req_file_path): data = { "msg": gettext("There is no requirement file"), "msg_type": "e", "custom_status": 400} return data with open(plugin_req_file_path) as rf: new_reqs = rf.read().split() hosts = mdbs["sys"].db.sys_host.find({"host_info.local_ip": {"$exists": True}}) connection_failed = [] for host in hosts: host_info = host["host_info"] s, v = audit_host_info(host_info) if not s: connection_failed.append( {"host_ip": host_info["local_ip"], "error": r}) continue else: try: ssh = MySSH(host=host_info["local_ip"], port=host_info["port"], username=host_info["username"], password=host_info["password"]) except BaseException as e: connection_failed.append( {"host_ip": host_info["local_ip"], "error": str(e)}) continue if not ssh: connection_failed.append( {"host_ip": host_info["local_ip"], "error": "Failed to connect to server host"}) continue ssh.close() install_process(plugin_name, host_info, new_reqs) install_process.apply_async( kwargs={ "plugin_name": plugin_name, "host_info": host_info, "packages": new_reqs } ) if connection_failed: # 更新插件需求包安装状态 plugin = mdbs["sys"].db.plugin.find_one({"plugin_name": plugin_name}, { "require_package_install_result": 1}) for connect in connection_failed: if "require_package_install_result" in plugin and plugin[ "require_package_install_result"]: updated = False for old_result in plugin["require_package_install_result"]: if old_result["host_ip"] == connect["host_ip"]: old_result["error"] = connect["error"] old_result["time"] = time.time() updated = True break if not updated: result = { "host_ip": connect["host_ip"], "error": connect["error"], "time": time.time() } plugin["require_package_install_result"].append(result) else: plugin["require_package_install_result"] = [{ "host_ip": connect["host_ip"], "error": connect["error"], "time": time.time()}] mdbs["sys"].db.plugin.update_one({"plugin_name": plugin_name}, {"$set": { "require_package_install_result": plugin["require_package_install_result"]}}) data = { "msg": gettext("Some host connections failed. Successfully connected host has installed requirements package in the background"), "data": connection_failed, "msg_type": "w", "custom_status": 201} else: data = { "msg": gettext("Executed related installation commands in the background"), "msg_type": "s", "custom_status": 201} return data
[ "def", "install_require_package", "(", ")", ":", "plugin_name", "=", "request", ".", "argget", ".", "all", "(", "'plugin_name'", ")", "s", ",", "r", "=", "arg_verify", "(", "reqargs", "=", "[", "(", "\"plugin name\"", ",", "plugin_name", ")", "]", ",", "...
https://github.com/osroom/osroom/blob/fcb9b7c5e5cfd8e919f8d87521800e70b09b5b44/apps/modules/plug_in_manager/process/setting.py#L201-L298
xieyufei1993/InceptText-Tensorflow
bdb5c1bd4a7db277ddf9550e40c5a1fad0230ac4
lib/datasets/coco.py
python
coco.image_path_at
(self, i)
return self.image_path_from_index(self._image_index[i])
Return the absolute path to image i in the image sequence.
Return the absolute path to image i in the image sequence.
[ "Return", "the", "absolute", "path", "to", "image", "i", "in", "the", "image", "sequence", "." ]
def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_index[i])
[ "def", "image_path_at", "(", "self", ",", "i", ")", ":", "return", "self", ".", "image_path_from_index", "(", "self", ".", "_image_index", "[", "i", "]", ")" ]
https://github.com/xieyufei1993/InceptText-Tensorflow/blob/bdb5c1bd4a7db277ddf9550e40c5a1fad0230ac4/lib/datasets/coco.py#L112-L116
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo._proc_builtin
(self, tarfile)
return self
Process a builtin type or an unknown type which will be treated as a regular file.
Process a builtin type or an unknown type which will be treated as a regular file.
[ "Process", "a", "builtin", "type", "or", "an", "unknown", "type", "which", "will", "be", "treated", "as", "a", "regular", "file", "." ]
def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the following data blocks. offset += self._block(self.size) tarfile.offset = offset # Patch the TarInfo object with saved global # header information. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) return self
[ "def", "_proc_builtin", "(", "self", ",", "tarfile", ")", ":", "self", ".", "offset_data", "=", "tarfile", ".", "fileobj", ".", "tell", "(", ")", "offset", "=", "self", ".", "offset_data", "if", "self", ".", "isreg", "(", ")", "or", "self", ".", "typ...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1316-L1331
yiranran/Audio-driven-TalkingFace-HeadPose
d062a00a46a5d0ebb4bf66751e7a9af92ee418e8
render-to-video/util/visualizer.py
python
Visualizer.display_current_results
(self, visuals, epoch, save_result)
[]
def display_current_results(self, visuals, epoch, save_result): if self.display_id > 0: # show images in the browser ncols = self.ncols if ncols > 0: ncols = min(ncols, len(visuals)) h, w = next(iter(visuals.values())).shape[:2] table_css = """<style> table {border-collapse: separate; border-spacing:4px; white-space:nowrap; text-align:center} table td {width: %dpx; height: %dpx; padding: 4px; outline: 4px solid black} </style>""" % (w, h) title = self.name label_html = '' label_html_row = '' images = [] idx = 0 for label, image in visuals.items(): image_numpy = util.tensor2im(image) label_html_row += '<td>%s</td>' % label images.append(image_numpy.transpose([2, 0, 1])) idx += 1 if idx % ncols == 0: label_html += '<tr>%s</tr>' % label_html_row label_html_row = '' white_image = np.ones_like(image_numpy.transpose([2, 0, 1])) * 255 while idx % ncols != 0: images.append(white_image) label_html_row += '<td></td>' idx += 1 if label_html_row != '': label_html += '<tr>%s</tr>' % label_html_row # pane col = image row try: self.vis.images(images, nrow=ncols, win=self.display_id + 1, padding=2, opts=dict(title=title + ' images')) label_html = '<table>%s</table>' % label_html self.vis.text(table_css + label_html, win=self.display_id + 2, opts=dict(title=title + ' labels')) except ConnectionError: self.throw_visdom_connection_error() else: idx = 1 for label, image in visuals.items(): image_numpy = util.tensor2im(image) self.vis.image(image_numpy.transpose([2, 0, 1]), opts=dict(title=label), win=self.display_id + idx) idx += 1 if self.use_html and (save_result or not self.saved): # save images to a html file self.saved = True for label, image in visuals.items(): image_numpy = util.tensor2im(image) img_path = os.path.join(self.img_dir, 'epoch%.3d_%s.png' % (epoch, label)) util.save_image(image_numpy, img_path) # update website webpage = html.HTML(self.web_dir, 'Experiment name = %s' % self.name, refresh=1) for n in range(epoch, 0, -1): webpage.add_header('epoch [%d]' % n) ims, txts, links = [], [], [] for label, image_numpy in visuals.items(): image_numpy = util.tensor2im(image) img_path = 'epoch%.3d_%s.png' % (n, label) ims.append(img_path) txts.append(label) links.append(img_path) webpage.add_images(ims, txts, links, width=self.win_size) webpage.save()
[ "def", "display_current_results", "(", "self", ",", "visuals", ",", "epoch", ",", "save_result", ")", ":", "if", "self", ".", "display_id", ">", "0", ":", "# show images in the browser", "ncols", "=", "self", ".", "ncols", "if", "ncols", ">", "0", ":", "nc...
https://github.com/yiranran/Audio-driven-TalkingFace-HeadPose/blob/d062a00a46a5d0ebb4bf66751e7a9af92ee418e8/render-to-video/util/visualizer.py#L73-L140
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/tkinter/__init__.py
python
Misc.option_add
(self, pattern, value, priority = None)
Set a VALUE (second parameter) for an option PATTERN (first parameter). An optional third parameter gives the numeric priority (defaults to 80).
Set a VALUE (second parameter) for an option PATTERN (first parameter).
[ "Set", "a", "VALUE", "(", "second", "parameter", ")", "for", "an", "option", "PATTERN", "(", "first", "parameter", ")", "." ]
def option_add(self, pattern, value, priority = None): """Set a VALUE (second parameter) for an option PATTERN (first parameter). An optional third parameter gives the numeric priority (defaults to 80).""" self.tk.call('option', 'add', pattern, value, priority)
[ "def", "option_add", "(", "self", ",", "pattern", ",", "value", ",", "priority", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "'option'", ",", "'add'", ",", "pattern", ",", "value", ",", "priority", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/tkinter/__init__.py#L636-L642
tensorlayer/tensorlayer
cb4eb896dd063e650ef22533ed6fa6056a71cad5
examples/reinforcement_learning/tutorial_TD3.py
python
PolicyNetwork.sample_action
(self)
return self.action_range * a.numpy()
generate random actions for exploration
generate random actions for exploration
[ "generate", "random", "actions", "for", "exploration" ]
def sample_action(self): """ generate random actions for exploration """ a = tf.random.uniform([self.num_actions], -1, 1) return self.action_range * a.numpy()
[ "def", "sample_action", "(", "self", ")", ":", "a", "=", "tf", ".", "random", ".", "uniform", "(", "[", "self", ".", "num_actions", "]", ",", "-", "1", ",", "1", ")", "return", "self", ".", "action_range", "*", "a", ".", "numpy", "(", ")" ]
https://github.com/tensorlayer/tensorlayer/blob/cb4eb896dd063e650ef22533ed6fa6056a71cad5/examples/reinforcement_learning/tutorial_TD3.py#L204-L207
betamaxpy/betamax
f06fe32d657a8c78b6e5a00048dff7fa50ad9be6
src/betamax/cassette/interaction.py
python
Interaction.match
(self, matchers)
return all(m(request) for m in matchers)
Return whether this interaction is a match.
Return whether this interaction is a match.
[ "Return", "whether", "this", "interaction", "is", "a", "match", "." ]
def match(self, matchers): """Return whether this interaction is a match.""" request = self.data['request'] return all(m(request) for m in matchers)
[ "def", "match", "(", "self", ",", "matchers", ")", ":", "request", "=", "self", ".", "data", "[", "'request'", "]", "return", "all", "(", "m", "(", "request", ")", "for", "m", "in", "matchers", ")" ]
https://github.com/betamaxpy/betamax/blob/f06fe32d657a8c78b6e5a00048dff7fa50ad9be6/src/betamax/cassette/interaction.py#L55-L58
tryolabs/requestium
9533932ae688da26f3fb78b97b3c0b05c6f24934
requestium/requestium.py
python
DriverMixin.is_cookie_in_driver
(self, cookie)
return False
We check that the cookie is correctly added to the driver We only compare name, value and domain, as the rest can produce false negatives. We are a bit lenient when comparing domains.
We check that the cookie is correctly added to the driver
[ "We", "check", "that", "the", "cookie", "is", "correctly", "added", "to", "the", "driver" ]
def is_cookie_in_driver(self, cookie): """We check that the cookie is correctly added to the driver We only compare name, value and domain, as the rest can produce false negatives. We are a bit lenient when comparing domains. """ for driver_cookie in self.get_cookies(): if (cookie['name'] == driver_cookie['name'] and cookie['value'] == driver_cookie['value'] and (cookie['domain'] == driver_cookie['domain'] or '.' + cookie['domain'] == driver_cookie['domain'])): return True return False
[ "def", "is_cookie_in_driver", "(", "self", ",", "cookie", ")", ":", "for", "driver_cookie", "in", "self", ".", "get_cookies", "(", ")", ":", "if", "(", "cookie", "[", "'name'", "]", "==", "driver_cookie", "[", "'name'", "]", "and", "cookie", "[", "'value...
https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L246-L258
NaturalHistoryMuseum/inselect
196a3ae2a0ed4e2c7cb667aaba9a6be1bcd90ca6
inselect/gui/user_template_choice.py
python
UserTemplateChoice._load
(self, path)
return UserTemplate.load(path)
Loads the UserTemplate in path
Loads the UserTemplate in path
[ "Loads", "the", "UserTemplate", "in", "path" ]
def _load(self, path): "Loads the UserTemplate in path" debug_print('UserTemplateChoice._load [{0}]'.format(path)) return UserTemplate.load(path)
[ "def", "_load", "(", "self", ",", "path", ")", ":", "debug_print", "(", "'UserTemplateChoice._load [{0}]'", ".", "format", "(", "path", ")", ")", "return", "UserTemplate", ".", "load", "(", "path", ")" ]
https://github.com/NaturalHistoryMuseum/inselect/blob/196a3ae2a0ed4e2c7cb667aaba9a6be1bcd90ca6/inselect/gui/user_template_choice.py#L51-L54
GothicAi/Instaboost
b6f80405b8706adad4aca1c1bdbb650b9c1c71e5
detectron/lib/core/config.py
python
merge_cfg_from_file
(cfg_filename)
Load a yaml config file and merge it into the global config.
Load a yaml config file and merge it into the global config.
[ "Load", "a", "yaml", "config", "file", "and", "merge", "it", "into", "the", "global", "config", "." ]
def merge_cfg_from_file(cfg_filename): """Load a yaml config file and merge it into the global config.""" with open(cfg_filename, 'r') as f: yaml_cfg = AttrDict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C)
[ "def", "merge_cfg_from_file", "(", "cfg_filename", ")", ":", "with", "open", "(", "cfg_filename", ",", "'r'", ")", "as", "f", ":", "yaml_cfg", "=", "AttrDict", "(", "yaml", ".", "load", "(", "f", ")", ")", "_merge_a_into_b", "(", "yaml_cfg", ",", "__C", ...
https://github.com/GothicAi/Instaboost/blob/b6f80405b8706adad4aca1c1bdbb650b9c1c71e5/detectron/lib/core/config.py#L1034-L1038
hyperopt/hyperopt
6c5b33be93a71a4ae6a38f04a29b18020b78b702
hyperopt/base.py
python
Trials.count_by_state_unsynced
(self, arg)
return self.count_by_state_synced(arg, trials=exp_trials)
Return trial counts that count_by_state_synced would return if we called refresh() first.
Return trial counts that count_by_state_synced would return if we called refresh() first.
[ "Return", "trial", "counts", "that", "count_by_state_synced", "would", "return", "if", "we", "called", "refresh", "()", "first", "." ]
def count_by_state_unsynced(self, arg): """ Return trial counts that count_by_state_synced would return if we called refresh() first. """ if self._exp_key is not None: exp_trials = [ tt for tt in self._dynamic_trials if tt["exp_key"] == self._exp_key ] else: exp_trials = self._dynamic_trials return self.count_by_state_synced(arg, trials=exp_trials)
[ "def", "count_by_state_unsynced", "(", "self", ",", "arg", ")", ":", "if", "self", ".", "_exp_key", "is", "not", "None", ":", "exp_trials", "=", "[", "tt", "for", "tt", "in", "self", ".", "_dynamic_trials", "if", "tt", "[", "\"exp_key\"", "]", "==", "s...
https://github.com/hyperopt/hyperopt/blob/6c5b33be93a71a4ae6a38f04a29b18020b78b702/hyperopt/base.py#L521-L532
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/SocketServer.py
python
ThreadingMixIn.process_request_thread
(self, request, client_address)
Same as in BaseServer but as a thread. In addition, exception handling is done here.
Same as in BaseServer but as a thread. In addition, exception handling is done here.
[ "Same", "as", "in", "BaseServer", "but", "as", "a", "thread", ".", "In", "addition", "exception", "handling", "is", "done", "here", "." ]
def process_request_thread(self, request, client_address): """Same as in BaseServer but as a thread. In addition, exception handling is done here. """ try: self.finish_request(request, client_address) self.shutdown_request(request) except: self.handle_error(request, client_address) self.shutdown_request(request)
[ "def", "process_request_thread", "(", "self", ",", "request", ",", "client_address", ")", ":", "try", ":", "self", ".", "finish_request", "(", "request", ",", "client_address", ")", "self", ".", "shutdown_request", "(", "request", ")", "except", ":", "self", ...
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/SocketServer.py#L538-L549
braincorp/PVM
3de2683634f372d2ac5aaa8b19e8ff23420d94d1
PVM_tools/labeled_movie.py
python
LabeledMovieWriter.write_frame
(self, Frame)
:param Frame: a frame to be written :type Frame: PVM_tools.labeled_movie.LabeledMovieFrame
:param Frame: a frame to be written :type Frame: PVM_tools.labeled_movie.LabeledMovieFrame
[ ":", "param", "Frame", ":", "a", "frame", "to", "be", "written", ":", "type", "Frame", ":", "PVM_tools", ".", "labeled_movie", ".", "LabeledMovieFrame" ]
def write_frame(self, Frame): """ :param Frame: a frame to be written :type Frame: PVM_tools.labeled_movie.LabeledMovieFrame """ if not self._movie_header_written: cPickle.dump(obj=self._movie_header, file=self.file, protocol=-1) self._movie_header_written = True cPickle.dump(obj=Frame, file=self.file, protocol=-1)
[ "def", "write_frame", "(", "self", ",", "Frame", ")", ":", "if", "not", "self", ".", "_movie_header_written", ":", "cPickle", ".", "dump", "(", "obj", "=", "self", ".", "_movie_header", ",", "file", "=", "self", ".", "file", ",", "protocol", "=", "-", ...
https://github.com/braincorp/PVM/blob/3de2683634f372d2ac5aaa8b19e8ff23420d94d1/PVM_tools/labeled_movie.py#L520-L528
sony/nnabla-examples
068be490aacf73740502a1c3b10f8b2d15a52d32
object-detection/centernet/src/lib/tools/voc_eval_lib/utils/blob.py
python
im_list_to_blob
(ims)
return blob
Convert a list of images into a network input. Assumes images are already prepared (means subtracted, BGR order, ...).
Convert a list of images into a network input.
[ "Convert", "a", "list", "of", "images", "into", "a", "network", "input", "." ]
def im_list_to_blob(ims): """Convert a list of images into a network input. Assumes images are already prepared (means subtracted, BGR order, ...). """ max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) blob = np.zeros((num_images, max_shape[0], max_shape[1], 3), dtype=np.float32) for i in range(num_images): im = ims[i] blob[i, 0:im.shape[0], 0:im.shape[1], :] = im return blob
[ "def", "im_list_to_blob", "(", "ims", ")", ":", "max_shape", "=", "np", ".", "array", "(", "[", "im", ".", "shape", "for", "im", "in", "ims", "]", ")", ".", "max", "(", "axis", "=", "0", ")", "num_images", "=", "len", "(", "ims", ")", "blob", "...
https://github.com/sony/nnabla-examples/blob/068be490aacf73740502a1c3b10f8b2d15a52d32/object-detection/centernet/src/lib/tools/voc_eval_lib/utils/blob.py#L31-L44
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py
python
TowerSkein.isInsideRemovedOutsideCone
( self, island, removedBoundingLoop, untilLayerIndex )
return True
Determine if the island is entirely inside the removed bounding loop and outside the collision cone of the remaining islands.
Determine if the island is entirely inside the removed bounding loop and outside the collision cone of the remaining islands.
[ "Determine", "if", "the", "island", "is", "entirely", "inside", "the", "removed", "bounding", "loop", "and", "outside", "the", "collision", "cone", "of", "the", "remaining", "islands", "." ]
def isInsideRemovedOutsideCone( self, island, removedBoundingLoop, untilLayerIndex ): "Determine if the island is entirely inside the removed bounding loop and outside the collision cone of the remaining islands." if not island.boundingLoop.isEntirelyInsideAnother( removedBoundingLoop ): return False bottomLayerIndex = self.getBottomLayerIndex() coneAngleTangent = math.tan( math.radians( self.towerRepository.extruderPossibleCollisionConeAngle.value ) ) for layerIndex in xrange( bottomLayerIndex, untilLayerIndex ): islands = self.threadLayers[layerIndex].islands outsetDistance = self.edgeWidth * ( untilLayerIndex - layerIndex ) * coneAngleTangent + 0.5 * self.edgeWidth for belowIsland in self.threadLayers[layerIndex].islands: outsetIslandLoop = belowIsland.boundingLoop.getOutsetBoundingLoop( outsetDistance ) if island.boundingLoop.isOverlappingAnother( outsetIslandLoop ): return False return True
[ "def", "isInsideRemovedOutsideCone", "(", "self", ",", "island", ",", "removedBoundingLoop", ",", "untilLayerIndex", ")", ":", "if", "not", "island", ".", "boundingLoop", ".", "isEntirelyInsideAnother", "(", "removedBoundingLoop", ")", ":", "return", "False", "botto...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py#L279-L292
moraes/tipfy
20cc0dab85f5433e399ae2d948d2b32dad051d66
project/app/hello_world/handlers.py
python
PrettyHelloWorldHandler.get
(self)
return self.render_response('hello_world.html', **context)
Simply returns a rendered template with an enigmatic salutation.
Simply returns a rendered template with an enigmatic salutation.
[ "Simply", "returns", "a", "rendered", "template", "with", "an", "enigmatic", "salutation", "." ]
def get(self): """Simply returns a rendered template with an enigmatic salutation.""" context = { 'message': 'Hello, World!', } return self.render_response('hello_world.html', **context)
[ "def", "get", "(", "self", ")", ":", "context", "=", "{", "'message'", ":", "'Hello, World!'", ",", "}", "return", "self", ".", "render_response", "(", "'hello_world.html'", ",", "*", "*", "context", ")" ]
https://github.com/moraes/tipfy/blob/20cc0dab85f5433e399ae2d948d2b32dad051d66/project/app/hello_world/handlers.py#L23-L28
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/xml/etree/ElementTree.py
python
Element.iterfind
(self, path, namespaces=None)
return ElementPath.iterfind(self, path, namespaces)
Find all matching subelements by tag name or path. *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return an iterable yielding all matching elements in document order.
Find all matching subelements by tag name or path.
[ "Find", "all", "matching", "subelements", "by", "tag", "name", "or", "path", "." ]
def iterfind(self, path, namespaces=None): """Find all matching subelements by tag name or path. *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return an iterable yielding all matching elements in document order. """ return ElementPath.iterfind(self, path, namespaces)
[ "def", "iterfind", "(", "self", ",", "path", ",", "namespaces", "=", "None", ")", ":", "return", "ElementPath", ".", "iterfind", "(", "self", ",", "path", ",", "namespaces", ")" ]
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/xml/etree/ElementTree.py#L324-L333
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/cui/settings.py
python
PhonopySettings.set_run_mode
(self, val)
Set run_mode.
Set run_mode.
[ "Set", "run_mode", "." ]
def set_run_mode(self, val): """Set run_mode.""" self._v["run_mode"] = val
[ "def", "set_run_mode", "(", "self", ",", "val", ")", ":", "self", ".", "_v", "[", "\"run_mode\"", "]", "=", "val" ]
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/cui/settings.py#L1400-L1402
cakebread/yolk
ee8c9f529a542d9c5eff4fe69b9c7906c802e4d8
yolk/pypi.py
python
CheeseShop.fetch_pkg_list
(self)
Fetch and cache master list of package names from PYPI
Fetch and cache master list of package names from PYPI
[ "Fetch", "and", "cache", "master", "list", "of", "package", "names", "from", "PYPI" ]
def fetch_pkg_list(self): """Fetch and cache master list of package names from PYPI""" self.logger.debug("DEBUG: Fetching package name list from PyPI") package_list = self.list_packages() cPickle.dump(package_list, open(self.pkg_cache_file, "w")) self.pkg_list = package_list
[ "def", "fetch_pkg_list", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"DEBUG: Fetching package name list from PyPI\"", ")", "package_list", "=", "self", ".", "list_packages", "(", ")", "cPickle", ".", "dump", "(", "package_list", ",", "open...
https://github.com/cakebread/yolk/blob/ee8c9f529a542d9c5eff4fe69b9c7906c802e4d8/yolk/pypi.py#L208-L213
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/plug/_windows.py
python
PluginStatus.__populate_load_list
(self)
Build list of loaded plugins
Build list of loaded plugins
[ "Build", "list", "of", "loaded", "plugins" ]
def __populate_load_list(self): """ Build list of loaded plugins""" fail_list = self.__pmgr.get_fail_list() for i in fail_list: # i = (filename, (exception-type, exception, traceback), pdata) err = i[1][0] pdata = i[2] hidden = pdata.id in self.hidden if hidden: hiddenstr = self.HIDDEN else: hiddenstr = self.AVAILABLE if err == UnavailableError: self.model.append(row=[ '<span color="blue">%s</span>' % _('Unavailable'), i[0], str(i[1][1]), None, pdata.id, hiddenstr]) else: self.model.append(row=[ '<span weight="bold" color="red">%s</span>' % _('Fail'), i[0], str(i[1][1]), i[1], pdata.id, hiddenstr]) success_list = sorted(self.__pmgr.get_success_list(), key=lambda x: (x[0], x[2]._get_name())) for i in success_list: # i = (filename, module, pdata) pdata = i[2] modname = i[1].__name__ hidden = pdata.id in self.hidden if hidden: hiddenstr = self.HIDDEN else: hiddenstr = self.AVAILABLE self.model.append(row=[ '<span weight="bold" color="#267726">%s</span>' % _("OK"), i[0], pdata.description, None, pdata.id, hiddenstr])
[ "def", "__populate_load_list", "(", "self", ")", ":", "fail_list", "=", "self", ".", "__pmgr", ".", "get_fail_list", "(", ")", "for", "i", "in", "fail_list", ":", "# i = (filename, (exception-type, exception, traceback), pdata)", "err", "=", "i", "[", "1", "]", ...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/plug/_windows.py#L479-L514
urwid/urwid
e2423b5069f51d318ea1ac0f355a0efe5448f7eb
urwid/web_display.py
python
Screen.set_mouse_tracking
(self, enable=True)
Not yet implemented
Not yet implemented
[ "Not", "yet", "implemented" ]
def set_mouse_tracking(self, enable=True): """Not yet implemented""" pass
[ "def", "set_mouse_tracking", "(", "self", ",", "enable", "=", "True", ")", ":", "pass" ]
https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/urwid/web_display.py#L619-L621
ghostop14/sparrow-wifi
4b8289773ea4304872062f65a6ffc9352612b08e
sparrowcommon.py
python
stringtobool
(instr)
[]
def stringtobool(instr): if (instr == 'True' or instr == 'true'): return True else: return False
[ "def", "stringtobool", "(", "instr", ")", ":", "if", "(", "instr", "==", "'True'", "or", "instr", "==", "'true'", ")", ":", "return", "True", "else", ":", "return", "False" ]
https://github.com/ghostop14/sparrow-wifi/blob/4b8289773ea4304872062f65a6ffc9352612b08e/sparrowcommon.py#L29-L33
adamrehn/ue4-docker
4ad926620fb7ee86dbaa2b80c22a78ecdf5e5287
ue4docker/infrastructure/Logger.py
python
Logger.action
(self, output, newline=True)
Prints information about an action that is being performed
Prints information about an action that is being performed
[ "Prints", "information", "about", "an", "action", "that", "is", "being", "performed" ]
def action(self, output, newline=True): """ Prints information about an action that is being performed """ self._print("green", output, newline)
[ "def", "action", "(", "self", ",", "output", ",", "newline", "=", "True", ")", ":", "self", ".", "_print", "(", "\"green\"", ",", "output", ",", "newline", ")" ]
https://github.com/adamrehn/ue4-docker/blob/4ad926620fb7ee86dbaa2b80c22a78ecdf5e5287/ue4docker/infrastructure/Logger.py#L13-L17
michaelliao/sinaweibopy
eb5298ad84ea774bf2006f28b6158a9a05d723e5
snspy.py
python
APIClient.__getattr__
(self, attr)
return _Callable(self, attr)
[]
def __getattr__(self, attr): if hasattr(self._mixin, attr): return getattr(self._mixin, attr) return _Callable(self, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "hasattr", "(", "self", ".", "_mixin", ",", "attr", ")", ":", "return", "getattr", "(", "self", ".", "_mixin", ",", "attr", ")", "return", "_Callable", "(", "self", ",", "attr", ")" ]
https://github.com/michaelliao/sinaweibopy/blob/eb5298ad84ea774bf2006f28b6158a9a05d723e5/snspy.py#L409-L412
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
contrib/paramiko/paramiko/win_pageant.py
python
can_talk_to_agent
()
return bool(_get_pageant_window_object())
Check to see if there is a "Pageant" agent we can talk to. This checks both if we have the required libraries (win32all or ctypes) and if there is a Pageant currently running.
Check to see if there is a "Pageant" agent we can talk to.
[ "Check", "to", "see", "if", "there", "is", "a", "Pageant", "agent", "we", "can", "talk", "to", "." ]
def can_talk_to_agent(): """ Check to see if there is a "Pageant" agent we can talk to. This checks both if we have the required libraries (win32all or ctypes) and if there is a Pageant currently running. """ return bool(_get_pageant_window_object())
[ "def", "can_talk_to_agent", "(", ")", ":", "return", "bool", "(", "_get_pageant_window_object", "(", ")", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/contrib/paramiko/paramiko/win_pageant.py#L50-L57
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/space/__init__.py
python
Space._validate
(self, is_numeric, batch)
Shared implementation of validate() and np_validate(). Calls validate_callbacks or np_validate_callbacks as appropriate, then calls self._validate_impl(batch) to verify that batch belongs to this space. Parameters ---------- is_numeric : bool. Set to True to call np_validate_callbacks, False to call validate_callbacks. Necessary because it can be impossible to tell from the batch whether it should be treated as a numeric of symbolic batch, for example when the batch is the empty tuple (), or NullSpace batch None. batch : a theano variable, numpy ndarray, scipy.sparse matrix \ or a nested tuple thereof Represents a batch belonging to this space.
Shared implementation of validate() and np_validate(). Calls validate_callbacks or np_validate_callbacks as appropriate, then calls self._validate_impl(batch) to verify that batch belongs to this space.
[ "Shared", "implementation", "of", "validate", "()", "and", "np_validate", "()", ".", "Calls", "validate_callbacks", "or", "np_validate_callbacks", "as", "appropriate", "then", "calls", "self", ".", "_validate_impl", "(", "batch", ")", "to", "verify", "that", "batc...
def _validate(self, is_numeric, batch): """ Shared implementation of validate() and np_validate(). Calls validate_callbacks or np_validate_callbacks as appropriate, then calls self._validate_impl(batch) to verify that batch belongs to this space. Parameters ---------- is_numeric : bool. Set to True to call np_validate_callbacks, False to call validate_callbacks. Necessary because it can be impossible to tell from the batch whether it should be treated as a numeric of symbolic batch, for example when the batch is the empty tuple (), or NullSpace batch None. batch : a theano variable, numpy ndarray, scipy.sparse matrix \ or a nested tuple thereof Represents a batch belonging to this space. """ if is_numeric: self._check_is_numeric(batch) callbacks_name = "np_validate_callbacks" else: self._check_is_symbolic(batch) callbacks_name = "validate_callbacks" if not hasattr(self, callbacks_name): raise TypeError("The " + str(type(self)) + " Space subclass " "is required to call the Space superclass " "constructor but does not.") else: callbacks = getattr(self, callbacks_name) for callback in callbacks: callback(batch) self._validate_impl(is_numeric, batch)
[ "def", "_validate", "(", "self", ",", "is_numeric", ",", "batch", ")", ":", "if", "is_numeric", ":", "self", ".", "_check_is_numeric", "(", "batch", ")", "callbacks_name", "=", "\"np_validate_callbacks\"", "else", ":", "self", ".", "_check_is_symbolic", "(", "...
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/space/__init__.py#L688-L726
missionpinball/mpf
8e6b74cff4ba06d2fec9445742559c1068b88582
mpf/core/bcp/bcp_pickle_client.py
python
BcpPickleClient.connect
(self, config)
return True
Actively connect to server.
Actively connect to server.
[ "Actively", "connect", "to", "server", "." ]
async def connect(self, config): """Actively connect to server.""" config = self.machine.config_validator.validate_config( 'bcp:connections', config, 'bcp:connections') self.info_log("Connecting BCP to '%s' at %s:%s...", self.name, config['host'], config['port']) while True: connector = self.machine.clock.open_connection(config['host'], config['port']) try: self._receiver, self._sender = await connector except OSError: if config.get('required'): await asyncio.sleep(.1) continue self.info_log("No BCP connection made to '%s' %s:%s", self.name, config['host'], config['port']) return False break self.info_log("Connected BCP to '%s' %s:%s", self.name, config['host'], config['port']) return True
[ "async", "def", "connect", "(", "self", ",", "config", ")", ":", "config", "=", "self", ".", "machine", ".", "config_validator", ".", "validate_config", "(", "'bcp:connections'", ",", "config", ",", "'bcp:connections'", ")", "self", ".", "info_log", "(", "\"...
https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/core/bcp/bcp_pickle_client.py#L26-L49
openstack/openstacksdk
58384268487fa854f21c470b101641ab382c9897
openstack/identity/v3/_proxy.py
python
Proxy.domains
(self, **query)
return self._list(_domain.Domain, **query)
Retrieve a generator of domains :param kwargs query: Optional query parameters to be sent to limit the resources being returned. :returns: A generator of domain instances. :rtype: :class:`~openstack.identity.v3.domain.Domain`
Retrieve a generator of domains
[ "Retrieve", "a", "generator", "of", "domains" ]
def domains(self, **query): """Retrieve a generator of domains :param kwargs query: Optional query parameters to be sent to limit the resources being returned. :returns: A generator of domain instances. :rtype: :class:`~openstack.identity.v3.domain.Domain` """ # TODO(briancurtin): This is paginated but requires base list changes. return self._list(_domain.Domain, **query)
[ "def", "domains", "(", "self", ",", "*", "*", "query", ")", ":", "# TODO(briancurtin): This is paginated but requires base list changes.", "return", "self", ".", "_list", "(", "_domain", ".", "Domain", ",", "*", "*", "query", ")" ]
https://github.com/openstack/openstacksdk/blob/58384268487fa854f21c470b101641ab382c9897/openstack/identity/v3/_proxy.py#L179-L189
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/compute/manager.py
python
ComputeManager.prep_resize
(self, context, image, instance, instance_type, reservations=None, request_spec=None, filter_properties=None, node=None)
Initiates the process of moving a running instance to another host. Possibly changes the RAM and disk size in the process.
Initiates the process of moving a running instance to another host.
[ "Initiates", "the", "process", "of", "moving", "a", "running", "instance", "to", "another", "host", "." ]
def prep_resize(self, context, image, instance, instance_type, reservations=None, request_spec=None, filter_properties=None, node=None): """Initiates the process of moving a running instance to another host. Possibly changes the RAM and disk size in the process. """ if node is None: node = self.driver.get_available_nodes()[0] LOG.debug(_("No node specified, defaulting to %(node)s") % locals()) with self._error_out_instance_on_exception(context, instance['uuid'], reservations): self.conductor_api.notify_usage_exists( context, instance, current_period=True) self._notify_about_instance_usage( context, instance, "resize.prep.start") try: self._prep_resize(context, image, instance, instance_type, reservations, request_spec, filter_properties, node) except Exception: # try to re-schedule the resize elsewhere: exc_info = sys.exc_info() self._reschedule_resize_or_reraise(context, image, instance, exc_info, instance_type, reservations, request_spec, filter_properties) finally: extra_usage_info = dict( new_instance_type=instance_type['name'], new_instance_type_id=instance_type['id']) self._notify_about_instance_usage( context, instance, "resize.prep.end", extra_usage_info=extra_usage_info)
[ "def", "prep_resize", "(", "self", ",", "context", ",", "image", ",", "instance", ",", "instance_type", ",", "reservations", "=", "None", ",", "request_spec", "=", "None", ",", "filter_properties", "=", "None", ",", "node", "=", "None", ")", ":", "if", "...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/compute/manager.py#L2260-L2295
SCons/scons
309f0234d1d9cc76955818be47c5c722f577dac6
SCons/Warnings.py
python
suppressWarningClass
(clazz)
Suppresses all warnings of type clazz or derived from clazz.
Suppresses all warnings of type clazz or derived from clazz.
[ "Suppresses", "all", "warnings", "of", "type", "clazz", "or", "derived", "from", "clazz", "." ]
def suppressWarningClass(clazz): """Suppresses all warnings of type clazz or derived from clazz.""" _enabled.insert(0, (clazz, False))
[ "def", "suppressWarningClass", "(", "clazz", ")", ":", "_enabled", ".", "insert", "(", "0", ",", "(", "clazz", ",", "False", ")", ")" ]
https://github.com/SCons/scons/blob/309f0234d1d9cc76955818be47c5c722f577dac6/SCons/Warnings.py#L144-L146
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/wheel.py
python
Wheel.support_index_min
(self, tags=None)
return min(indexes) if indexes else None
Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported.
Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported.
[ "Return", "the", "lowest", "index", "that", "one", "of", "the", "wheel", "s", "file_tag", "combinations", "achieves", "in", "the", "supported_tags", "list", "e", ".", "g", ".", "if", "there", "are", "8", "supported", "tags", "and", "one", "of", "the", "f...
def support_index_min(self, tags=None): """ Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported. """ if tags is None: # for mock tags = pep425tags.supported_tags indexes = [tags.index(c) for c in self.file_tags if c in tags] return min(indexes) if indexes else None
[ "def", "support_index_min", "(", "self", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "# for mock", "tags", "=", "pep425tags", ".", "supported_tags", "indexes", "=", "[", "tags", ".", "index", "(", "c", ")", "for", "c", "in", ...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/wheel.py#L626-L636
zhaoyingjun/TensorFlow-Coding
1ff292e5d659aa98e7bf6d9cc3986ef07ac2ca81
lessonFour/cyclegan/data_provider.py
python
provide_custom_datasets
(image_file_patterns, batch_size, shuffle=True, num_threads=1, patch_size=128)
return custom_datasets
Provides multiple batches of custom image data. Args: image_file_patterns: A list of glob patterns of image files. batch_size: The number of images in each batch. shuffle: Whether to shuffle the read images. Defaults to True. num_threads: Number of prefetching threads. Defaults to 1. patch_size: Size of the patch to extract from the image. Defaults to 128. Returns: A list of tf.data.Datasets the same number as `image_file_patterns`. Each of the datasets have `Tensor`'s in the list has a shape of [batch_size, patch_size, patch_size, 3] representing a batch of images. Raises: ValueError: If image_file_patterns is not a list or tuple.
Provides multiple batches of custom image data.
[ "Provides", "multiple", "batches", "of", "custom", "image", "data", "." ]
def provide_custom_datasets(image_file_patterns, batch_size, shuffle=True, num_threads=1, patch_size=128): """Provides multiple batches of custom image data. Args: image_file_patterns: A list of glob patterns of image files. batch_size: The number of images in each batch. shuffle: Whether to shuffle the read images. Defaults to True. num_threads: Number of prefetching threads. Defaults to 1. patch_size: Size of the patch to extract from the image. Defaults to 128. Returns: A list of tf.data.Datasets the same number as `image_file_patterns`. Each of the datasets have `Tensor`'s in the list has a shape of [batch_size, patch_size, patch_size, 3] representing a batch of images. Raises: ValueError: If image_file_patterns is not a list or tuple. """ if not isinstance(image_file_patterns, (list, tuple)): raise ValueError( '`image_file_patterns` should be either list or tuple, but was {}.'. format(type(image_file_patterns))) custom_datasets = [] for pattern in image_file_patterns: custom_datasets.append( _provide_custom_dataset( pattern, batch_size=batch_size, shuffle=shuffle, num_threads=num_threads, patch_size=patch_size)) return custom_datasets
[ "def", "provide_custom_datasets", "(", "image_file_patterns", ",", "batch_size", ",", "shuffle", "=", "True", ",", "num_threads", "=", "1", ",", "patch_size", "=", "128", ")", ":", "if", "not", "isinstance", "(", "image_file_patterns", ",", "(", "list", ",", ...
https://github.com/zhaoyingjun/TensorFlow-Coding/blob/1ff292e5d659aa98e7bf6d9cc3986ef07ac2ca81/lessonFour/cyclegan/data_provider.py#L99-L135
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/configparser.py
python
RawConfigParser.has_section
(self, section)
return section in self._sections
Indicate whether the named section is present in the configuration. The DEFAULT section is not acknowledged.
Indicate whether the named section is present in the configuration.
[ "Indicate", "whether", "the", "named", "section", "is", "present", "in", "the", "configuration", "." ]
def has_section(self, section): """Indicate whether the named section is present in the configuration. The DEFAULT section is not acknowledged. """ return section in self._sections
[ "def", "has_section", "(", "self", ",", "section", ")", ":", "return", "section", "in", "self", ".", "_sections" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/configparser.py#L642-L647
gpodder/gpodder
40fd34b14ab0127ed4263f86ce15d379d0114968
share/gpodder/extensions/sonos.py
python
gPodderExtension.on_episodes_context_menu
(self, episodes)
return list(dict(menu_entries).items())
Adds a context menu for each Sonos speaker group
Adds a context menu for each Sonos speaker group
[ "Adds", "a", "context", "menu", "for", "each", "Sonos", "speaker", "group" ]
def on_episodes_context_menu(self, episodes): """ Adds a context menu for each Sonos speaker group """ # Only show context menu if we can play at least one file if not any(SONOS_CAN_PLAY(e) for e in episodes): return [] menu_entries = [] for uid in list(self.speakers.keys()): callback = partial(self._stream_to_speaker, uid) controller = self.speakers[uid] is_grouped = ' (Grouped)' if len(controller.group.members) > 1 else '' name = controller.group.label + is_grouped item = ('/'.join((_('Stream to Sonos'), name)), callback) menu_entries.append(item) # Remove any duplicate group names. I doubt Sonos allows duplicate speaker names, # but we do initially get duplicated group names with the loop above return list(dict(menu_entries).items())
[ "def", "on_episodes_context_menu", "(", "self", ",", "episodes", ")", ":", "# Only show context menu if we can play at least one file", "if", "not", "any", "(", "SONOS_CAN_PLAY", "(", "e", ")", "for", "e", "in", "episodes", ")", ":", "return", "[", "]", "menu_entr...
https://github.com/gpodder/gpodder/blob/40fd34b14ab0127ed4263f86ce15d379d0114968/share/gpodder/extensions/sonos.py#L67-L86
KhronosGroup/glTF-Blender-Exporter
dd7a3dbd8f43a79d572e7c45f4215f770bb92a37
scripts/addons/io_scene_gltf2/gltf2_generate.py
python
generate_animations
(operator, context, export_settings, glTF)
Generates the top level animations entry.
Generates the top level animations entry.
[ "Generates", "the", "top", "level", "animations", "entry", "." ]
def generate_animations(operator, context, export_settings, glTF): """ Generates the top level animations entry. """ def process_object_animations(blender_object, blender_action): correction_matrix_local = blender_object.matrix_parent_inverse matrix_basis = mathutils.Matrix.Identity(4) # if export_settings['gltf_bake_skins']: blender_action = bake_action(export_settings, blender_object, blender_action) # if blender_action.name not in animations: animations[blender_action.name] = { 'name': blender_action.name, 'channels': [], 'samplers': [] } channels = animations[blender_action.name]['channels'] samplers = animations[blender_action.name]['samplers'] # Add entry to joint cache. Current action may not need skinnning, # but there are too many places to check for and add it later. gltf_joint_cache = export_settings['gltf_joint_cache'] if not gltf_joint_cache.get(blender_action.name): gltf_joint_cache[blender_action.name] = {} # generate_animations_parameter( operator, context, export_settings, glTF, blender_action, channels, samplers, blender_object.name, None, blender_object.rotation_mode, correction_matrix_local, matrix_basis, False ) if export_settings['gltf_skins']: if blender_object.type == 'ARMATURE' and len(blender_object.pose.bones) > 0: # if export_settings['gltf_yup']: axis_basis_change = mathutils.Matrix( ((1.0, 0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, -1.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0)) ) else: axis_basis_change = mathutils.Matrix.Identity(4) # Precalculate joint animation data. start, end = compute_action_range(export_settings, [blender_action]) # Iterate over frames in export range for frame in range(int(start), int(end) + 1): bpy.context.scene.frame_set(frame) # Iterate over object's bones for blender_bone in blender_object.pose.bones: correction_matrix_local, matrix_basis = compute_bone_matrices( axis_basis_change, blender_bone, blender_object, export_settings ) if not gltf_joint_cache[blender_action.name].get(blender_bone.name): gltf_joint_cache[blender_action.name][blender_bone.name] = {} matrix = correction_matrix_local * matrix_basis tmp_location, tmp_rotation, tmp_scale = matrix.decompose() gltf_joint_cache[blender_action.name][blender_bone.name][float(frame)] = [tmp_location, tmp_rotation, tmp_scale] # for blender_bone in blender_object.pose.bones: correction_matrix_local, matrix_basis = compute_bone_matrices( axis_basis_change, blender_bone, blender_object, export_settings ) generate_animations_parameter( operator, context, export_settings, glTF, blender_action, channels, samplers, blender_object.name, blender_bone.name, blender_bone.rotation_mode, correction_matrix_local, matrix_basis, False ) animations = {} # # filtered_objects = export_settings['filtered_objects'] # # processed_meshes = {} def process_mesh_object(blender_object, blender_action): blender_mesh = blender_object.data if not blender_action.name in processed_meshes: processed_meshes[blender_action.name] = [] if blender_mesh in processed_meshes[blender_action.name]: return # if blender_action.name not in animations: animations[blender_action.name] = { 'name': blender_action.name, 'channels': [], 'samplers': [] } channels = animations[blender_action.name]['channels'] samplers = animations[blender_action.name]['samplers'] # correction_matrix_local = mathutils.Matrix.Identity(4) matrix_basis = mathutils.Matrix.Identity(4) generate_animations_parameter(operator, context, export_settings, glTF, blender_action, channels, samplers, blender_object.name, None, blender_object.rotation_mode, correction_matrix_local, matrix_basis, True) processed_meshes[blender_action.name].append(blender_mesh) for blender_object in filtered_objects: animation_data = blender_object.animation_data if animation_data is not None: object_actions = [] # Collect active action. if animation_data.action: object_actions.append(animation_data.action) # Collect associated strips from NLA tracks. for track in animation_data.nla_tracks: # Multi-strip tracks do not export correctly yet (they need to be baked), # so skip them for now and only write single-strip tracks. if track.strips is None or len(track.strips) != 1: continue for strip in track.strips: object_actions.append(strip.action) # Remove duplicate actions. object_actions = list(set(object_actions)) # Export all collected actions. for action in object_actions: active_action = animation_data.action animation_data.action = action process_object_animations(blender_object, action) animation_data.action = active_action # # Export shape keys. if (blender_object.type != 'MESH' or blender_object.data is None or blender_object.data.shape_keys is None or blender_object.data.shape_keys.animation_data is None): continue shape_keys = blender_object.data.shape_keys shape_key_actions = [] if shape_keys.animation_data.action: shape_key_actions.append(shape_keys.animation_data.action) for track in shape_keys.animation_data.nla_tracks: for strip in track.strips: shape_key_actions.append(strip.action) for action in shape_key_actions: active_action = shape_keys.animation_data.action shape_keys.animation_data.action = action process_mesh_object(blender_object, action) shape_keys.animation_data.action = active_action # # if len(animations) > 0: glTF['animations'] = [] # Sampler 'name' is used to gather the index. However, 'name' is no property of sampler and has to be removed. for animation in animations.values(): for sampler in animation['samplers']: del sampler['name'] if len(animation['channels']) > 0: glTF['animations'].append(animation)
[ "def", "generate_animations", "(", "operator", ",", "context", ",", "export_settings", ",", "glTF", ")", ":", "def", "process_object_animations", "(", "blender_object", ",", "blender_action", ")", ":", "correction_matrix_local", "=", "blender_object", ".", "matrix_par...
https://github.com/KhronosGroup/glTF-Blender-Exporter/blob/dd7a3dbd8f43a79d572e7c45f4215f770bb92a37/scripts/addons/io_scene_gltf2/gltf2_generate.py#L610-L843
USEPA/WNTR
2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc
wntr/network/base.py
python
Link.velocity
(self)
return self._velocity
float: (read-only) current simulated velocity through the link
float: (read-only) current simulated velocity through the link
[ "float", ":", "(", "read", "-", "only", ")", "current", "simulated", "velocity", "through", "the", "link" ]
def velocity(self): """float: (read-only) current simulated velocity through the link""" return self._velocity
[ "def", "velocity", "(", "self", ")", ":", "return", "self", ".", "_velocity" ]
https://github.com/USEPA/WNTR/blob/2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc/wntr/network/base.py#L482-L484
has2k1/plydata
d9d022def44ade656fbb39c16d2f7fe45e9e96da
plydata/operators.py
python
get_verb_function
(data, verb)
Return function that implements the verb for given data type
Return function that implements the verb for given data type
[ "Return", "function", "that", "implements", "the", "verb", "for", "given", "data", "type" ]
def get_verb_function(data, verb): """ Return function that implements the verb for given data type """ try: datatype = dataclass_lookup[type(data)] except KeyError: # Some guess work for subclasses for klass, type_ in dataclass_lookup.items(): if isinstance(data, klass): datatype = type_ break else: raise TypeError( "Data of type {} is not supported.".format(type(data)) ) try: return REGISTRY[datatype][verb] except KeyError: raise TypeError( "Could not find a {} implementation for the verb {} ".format( datatype, verb ) )
[ "def", "get_verb_function", "(", "data", ",", "verb", ")", ":", "try", ":", "datatype", "=", "dataclass_lookup", "[", "type", "(", "data", ")", "]", "except", "KeyError", ":", "# Some guess work for subclasses", "for", "klass", ",", "type_", "in", "dataclass_l...
https://github.com/has2k1/plydata/blob/d9d022def44ade656fbb39c16d2f7fe45e9e96da/plydata/operators.py#L44-L67
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3db/hrm.py
python
hrm_TrainingEventRepresent.represent_row
(self, row)
return " ".join(representation)
Represent a row Args: row: the Row Note: This needs to be machine-parseable by training.xsl
Represent a row
[ "Represent", "a", "row" ]
def represent_row(self, row): """ Represent a row Args: row: the Row Note: This needs to be machine-parseable by training.xsl """ # Do we have a Name? name = row.get("hrm_training_event.name") if name: return name # Course Details course = row.get("hrm_course") if not course: return NONE name = course.get("name") if not name: name = NONE representation = ["%s --" % name] append = representation.append code = course.get("code") if code: append("(%s)" % code) # Venue and instructor event = row.hrm_training_event try: site = row.org_site.name except AttributeError: site = None instructors = current.deployment_settings.get_hrm_training_instructors() instructor = None if instructors in ("internal", "both"): person_id = event.get("person_id") if person_id: instructor = self.table.person_id.represent(person_id) if instructor is None and instructors in ("external", "both"): instructor = event.get("instructor") if instructor and site: append("%s - {%s}" % (instructor, site)) elif instructor: append("%s" % instructor) elif site: append("{%s}" % site) # Start date start_date = event.start_date if start_date: # Easier for users & machines start_date = S3DateTime.date_represent(start_date, format="%Y-%m-%d") append("[%s]" % start_date) return " ".join(representation)
[ "def", "represent_row", "(", "self", ",", "row", ")", ":", "# Do we have a Name?", "name", "=", "row", ".", "get", "(", "\"hrm_training_event.name\"", ")", "if", "name", ":", "return", "name", "# Course Details", "course", "=", "row", ".", "get", "(", "\"hrm...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3db/hrm.py#L6245-L6305
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/nttcis.py
python
NttCisNodeDriver.ex_create_ip_address_list
( self, ex_network_domain, name, description, ip_version, ip_address_collection, child_ip_address_list=None, )
return response_code in ["IN_PROGRESS", "OK"]
Create IP Address List. IP Address list. >>> from pprint import pprint >>> from libcloud.compute.types import Provider >>> from libcloud.compute.providers import get_driver >>> from libcloud.common.nttcis import NttCisIpAddress >>> import libcloud.security >>> >>> # Get NTTC-CIS driver >>> libcloud.security.VERIFY_SSL_CERT = True >>> cls = get_driver(Provider.NTTCIS) >>> driver = cls('myusername','mypassword', region='dd-au') >>> >>> # Get location >>> location = driver.ex_get_location_by_id(id='AU9') >>> >>> # Get network domain by location >>> networkDomainName = "Baas QA" >>> network_domains = driver.ex_list_network_domains(location=location) >>> my_network_domain = [d for d in network_domains if d.name == networkDomainName][0] >>> >>> # IP Address collection >>> ipAddress_1 = NttCisIpAddress(begin='190.2.2.100') >>> ipAddress_2 = NttCisIpAddress(begin='190.2.2.106', end='190.2.2.108') >>> ipAddress_3 = NttCisIpAddress(begin='190.2.2.0', prefix_size='24') >>> ip_address_collection = [ipAddress_1, ipAddress_2, ipAddress_3] >>> >>> # Create IPAddressList >>> result = driver.ex_create_ip_address_list( >>> ex_network_domain=my_network_domain, >>> name='My_IP_AddressList_2', >>> ip_version='IPV4', >>> description='Test only', >>> ip_address_collection=ip_address_collection, >>> child_ip_address_list='08468e26-eeb3-4c3d-8ff2-5351fa6d8a04' >>> ) >>> >>> pprint(result) :param ex_network_domain: The network domain or network domain ID :type ex_network_domain: :class:`NttCisNetworkDomain` or 'str' :param name: IP Address List Name (required) :type name: :``str`` :param description: IP Address List Description (optional) :type description: :``str`` :param ip_version: IP Version of ip address (required) :type ip_version: :``str`` :param ip_address_collection: List of IP Address. At least one ipAddress element or one childIpAddressListId element must be provided. :type ip_address_collection: :``str`` :param child_ip_address_list: Child IP Address List or id to be included in this IP Address List. At least one ipAddress or one childIpAddressListId must be provided. :type child_ip_address_list: :class:'NttCisChildIpAddressList` or `str`` :return: a list of NttCisIpAddressList objects :rtype: ``list`` of :class:`NttCisIpAddressList`
Create IP Address List. IP Address list.
[ "Create", "IP", "Address", "List", ".", "IP", "Address", "list", "." ]
def ex_create_ip_address_list( self, ex_network_domain, name, description, ip_version, ip_address_collection, child_ip_address_list=None, ): """ Create IP Address List. IP Address list. >>> from pprint import pprint >>> from libcloud.compute.types import Provider >>> from libcloud.compute.providers import get_driver >>> from libcloud.common.nttcis import NttCisIpAddress >>> import libcloud.security >>> >>> # Get NTTC-CIS driver >>> libcloud.security.VERIFY_SSL_CERT = True >>> cls = get_driver(Provider.NTTCIS) >>> driver = cls('myusername','mypassword', region='dd-au') >>> >>> # Get location >>> location = driver.ex_get_location_by_id(id='AU9') >>> >>> # Get network domain by location >>> networkDomainName = "Baas QA" >>> network_domains = driver.ex_list_network_domains(location=location) >>> my_network_domain = [d for d in network_domains if d.name == networkDomainName][0] >>> >>> # IP Address collection >>> ipAddress_1 = NttCisIpAddress(begin='190.2.2.100') >>> ipAddress_2 = NttCisIpAddress(begin='190.2.2.106', end='190.2.2.108') >>> ipAddress_3 = NttCisIpAddress(begin='190.2.2.0', prefix_size='24') >>> ip_address_collection = [ipAddress_1, ipAddress_2, ipAddress_3] >>> >>> # Create IPAddressList >>> result = driver.ex_create_ip_address_list( >>> ex_network_domain=my_network_domain, >>> name='My_IP_AddressList_2', >>> ip_version='IPV4', >>> description='Test only', >>> ip_address_collection=ip_address_collection, >>> child_ip_address_list='08468e26-eeb3-4c3d-8ff2-5351fa6d8a04' >>> ) >>> >>> pprint(result) :param ex_network_domain: The network domain or network domain ID :type ex_network_domain: :class:`NttCisNetworkDomain` or 'str' :param name: IP Address List Name (required) :type name: :``str`` :param description: IP Address List Description (optional) :type description: :``str`` :param ip_version: IP Version of ip address (required) :type ip_version: :``str`` :param ip_address_collection: List of IP Address. At least one ipAddress element or one childIpAddressListId element must be provided. :type ip_address_collection: :``str`` :param child_ip_address_list: Child IP Address List or id to be included in this IP Address List. At least one ipAddress or one childIpAddressListId must be provided. :type child_ip_address_list: :class:'NttCisChildIpAddressList` or `str`` :return: a list of NttCisIpAddressList objects :rtype: ``list`` of :class:`NttCisIpAddressList` """ if ip_address_collection is None and child_ip_address_list is None: raise ValueError( "At least one ipAddress element or one " "childIpAddressListId element must be " "provided." ) create_ip_address_list = ET.Element("createIpAddressList", {"xmlns": TYPES_URN}) ET.SubElement( create_ip_address_list, "networkDomainId" ).text = self._network_domain_to_network_domain_id(ex_network_domain) ET.SubElement(create_ip_address_list, "name").text = name ET.SubElement(create_ip_address_list, "description").text = description ET.SubElement(create_ip_address_list, "ipVersion").text = ip_version for ip in ip_address_collection: ip_address = ET.SubElement( create_ip_address_list, "ipAddress", ) ip_address.set("begin", ip.begin) if ip.end: ip_address.set("end", ip.end) if ip.prefix_size: ip_address.set("prefixSize", ip.prefix_size) if child_ip_address_list is not None: ET.SubElement( create_ip_address_list, "childIpAddressListId" ).text = self._child_ip_address_list_to_child_ip_address_list_id( child_ip_address_list ) response = self.connection.request_with_orgId_api_2( "network/createIpAddressList", method="POST", data=ET.tostring(create_ip_address_list), ).object response_code = findtext(response, "responseCode", TYPES_URN) return response_code in ["IN_PROGRESS", "OK"]
[ "def", "ex_create_ip_address_list", "(", "self", ",", "ex_network_domain", ",", "name", ",", "description", ",", "ip_version", ",", "ip_address_collection", ",", "child_ip_address_list", "=", "None", ",", ")", ":", "if", "ip_address_collection", "is", "None", "and",...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/nttcis.py#L3735-L3863
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/liealgebras/type_a.py
python
TypeA.simple_root
(self, i)
return self.basic_root(i-1, i)
Every lie algebra has a unique root system. Given a root system Q, there is a subset of the roots such that an element of Q is called a simple root if it cannot be written as the sum of two elements in Q. If we let D denote the set of simple roots, then it is clear that every element of Q can be written as a linear combination of elements of D with all coefficients non-negative. In A_n the ith simple root is the root which has a 1 in the ith position, a -1 in the (i+1)th position, and zeroes elsewhere. This method returns the ith simple root for the A series. Examples ======== >>> from sympy.liealgebras.cartan_type import CartanType >>> c = CartanType("A4") >>> c.simple_root(1) [1, -1, 0, 0, 0]
Every lie algebra has a unique root system. Given a root system Q, there is a subset of the roots such that an element of Q is called a simple root if it cannot be written as the sum of two elements in Q. If we let D denote the set of simple roots, then it is clear that every element of Q can be written as a linear combination of elements of D with all coefficients non-negative.
[ "Every", "lie", "algebra", "has", "a", "unique", "root", "system", ".", "Given", "a", "root", "system", "Q", "there", "is", "a", "subset", "of", "the", "roots", "such", "that", "an", "element", "of", "Q", "is", "called", "a", "simple", "root", "if", ...
def simple_root(self, i): """ Every lie algebra has a unique root system. Given a root system Q, there is a subset of the roots such that an element of Q is called a simple root if it cannot be written as the sum of two elements in Q. If we let D denote the set of simple roots, then it is clear that every element of Q can be written as a linear combination of elements of D with all coefficients non-negative. In A_n the ith simple root is the root which has a 1 in the ith position, a -1 in the (i+1)th position, and zeroes elsewhere. This method returns the ith simple root for the A series. Examples ======== >>> from sympy.liealgebras.cartan_type import CartanType >>> c = CartanType("A4") >>> c.simple_root(1) [1, -1, 0, 0, 0] """ return self.basic_root(i-1, i)
[ "def", "simple_root", "(", "self", ",", "i", ")", ":", "return", "self", ".", "basic_root", "(", "i", "-", "1", ",", "i", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/liealgebras/type_a.py#L49-L76
EdinburghNLP/XSum
7b95485c3e861d7caff76a8b4c6b3fd3bf7ee9b1
XSum-ConvS2S/fairseq/sequence_generator.py
python
SequenceGenerator.generate_batched_itr
(self, data_itr, beam_size=None, maxlen_a=0.0, maxlen_b=None, cuda=False, timer=None, prefix_size=0)
Iterate over a batched dataset and yield individual translations. Args: maxlen_a/b: generate sequences of maximum length ax + b, where x is the source sentence length. cuda: use GPU for generation timer: StopwatchMeter for timing generations.
Iterate over a batched dataset and yield individual translations.
[ "Iterate", "over", "a", "batched", "dataset", "and", "yield", "individual", "translations", "." ]
def generate_batched_itr(self, data_itr, beam_size=None, maxlen_a=0.0, maxlen_b=None, cuda=False, timer=None, prefix_size=0): """Iterate over a batched dataset and yield individual translations. Args: maxlen_a/b: generate sequences of maximum length ax + b, where x is the source sentence length. cuda: use GPU for generation timer: StopwatchMeter for timing generations. """ if maxlen_b is None: maxlen_b = self.maxlen for sample in data_itr: s = utils.make_variable(sample, volatile=True, cuda=cuda) input = s['net_input'] srclen = input['src_tokens'].size(1) if timer is not None: timer.start() with utils.maybe_no_grad(): hypos = self.generate( input['src_tokens'], input['src_lengths'], beam_size=beam_size, maxlen=int(maxlen_a*srclen + maxlen_b), prefix_tokens=s['target'][:, :prefix_size] if prefix_size > 0 else None, ) if timer is not None: timer.stop(sum([len(h[0]['tokens']) for h in hypos])) for i, id in enumerate(s['id'].data): src = input['src_tokens'].data[i, :] # remove padding from ref ref = utils.strip_pad(s['target'].data[i, :], self.pad) if s['target'] is not None else None yield id, src, ref, hypos[i]
[ "def", "generate_batched_itr", "(", "self", ",", "data_itr", ",", "beam_size", "=", "None", ",", "maxlen_a", "=", "0.0", ",", "maxlen_b", "=", "None", ",", "cuda", "=", "False", ",", "timer", "=", "None", ",", "prefix_size", "=", "0", ")", ":", "if", ...
https://github.com/EdinburghNLP/XSum/blob/7b95485c3e861d7caff76a8b4c6b3fd3bf7ee9b1/XSum-ConvS2S/fairseq/sequence_generator.py#L52-L85
SecureAuthCorp/impacket
10e53952e64e290712d49e263420b70b681bbc73
impacket/dot11.py
python
LLC.set_SSAP
(self, value)
Set the Source Service Access Point (SAP) of LLC frame
Set the Source Service Access Point (SAP) of LLC frame
[ "Set", "the", "Source", "Service", "Access", "Point", "(", "SAP", ")", "of", "LLC", "frame" ]
def set_SSAP(self, value): "Set the Source Service Access Point (SAP) of LLC frame" self.header.set_byte(1, value)
[ "def", "set_SSAP", "(", "self", ",", "value", ")", ":", "self", ".", "header", ".", "set_byte", "(", "1", ",", "value", ")" ]
https://github.com/SecureAuthCorp/impacket/blob/10e53952e64e290712d49e263420b70b681bbc73/impacket/dot11.py#L978-L980
uqfoundation/multiprocess
028cc73f02655e6451d92e5147d19d8c10aebe50
py3.7/multiprocess/managers.py
python
BaseManager._run_server
(cls, registry, address, authkey, serializer, writer, initializer=None, initargs=())
Create a server, report its address and run it
Create a server, report its address and run it
[ "Create", "a", "server", "report", "its", "address", "and", "run", "it" ]
def _run_server(cls, registry, address, authkey, serializer, writer, initializer=None, initargs=()): ''' Create a server, report its address and run it ''' if initializer is not None: initializer(*initargs) # create server server = cls._Server(registry, address, authkey, serializer) # inform parent process of the server's address writer.send(server.address) writer.close() # run the manager util.info('manager serving at %r', server.address) server.serve_forever()
[ "def", "_run_server", "(", "cls", ",", "registry", ",", "address", ",", "authkey", ",", "serializer", ",", "writer", ",", "initializer", "=", "None", ",", "initargs", "=", "(", ")", ")", ":", "if", "initializer", "is", "not", "None", ":", "initializer", ...
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.7/multiprocess/managers.py#L580-L597
cloudmatrix/esky
6fde3201f0335064931a6c7f7847fc5ad39001b4
esky/bdist_esky/__init__.py
python
bdist_esky._run_initialise_dirs
(self)
Create the dirs into which to freeze the app.
Create the dirs into which to freeze the app.
[ "Create", "the", "dirs", "into", "which", "to", "freeze", "the", "app", "." ]
def _run_initialise_dirs(self): """Create the dirs into which to freeze the app.""" fullname = self.distribution.get_fullname() platform = get_platform() self.bootstrap_dir = os.path.join(self.dist_dir, "%s.%s"%(fullname,platform,)) if self.enable_appdata_dir: self.freeze_dir = os.path.join(self.bootstrap_dir,ESKY_APPDATA_DIR, "%s.%s"%(fullname,platform,)) else: self.freeze_dir = os.path.join(self.bootstrap_dir, "%s.%s"%(fullname,platform,)) if os.path.exists(self.bootstrap_dir): really_rmtree(self.bootstrap_dir) os.makedirs(self.freeze_dir)
[ "def", "_run_initialise_dirs", "(", "self", ")", ":", "fullname", "=", "self", ".", "distribution", ".", "get_fullname", "(", ")", "platform", "=", "get_platform", "(", ")", "self", ".", "bootstrap_dir", "=", "os", ".", "path", ".", "join", "(", "self", ...
https://github.com/cloudmatrix/esky/blob/6fde3201f0335064931a6c7f7847fc5ad39001b4/esky/bdist_esky/__init__.py#L330-L344
cheind/pytorch-blender
ef35c5b3eec884515d4f343671a8a3337b8aa1fb
examples/densityopt/densityopt.py
python
get_target_images
(dl, remotes, mu_m1m2, std_m1m2, n)
return data.TensorDataset(torch.tensor(np.concatenate(images, 0)))
Returns a set of images from the target distribution.
Returns a set of images from the target distribution.
[ "Returns", "a", "set", "of", "images", "from", "the", "target", "distribution", "." ]
def get_target_images(dl, remotes, mu_m1m2, std_m1m2, n): '''Returns a set of images from the target distribution.''' pm = ProbModel(mu_m1m2, std_m1m2) samples = pm.sample(n) update_simulations(remotes, ProbModel.to_supershape(samples)) images = [] gen = iter(dl) for _ in range(n//BATCH): (img, shape_id) = next(gen) images.append(img) return data.TensorDataset(torch.tensor(np.concatenate(images, 0)))
[ "def", "get_target_images", "(", "dl", ",", "remotes", ",", "mu_m1m2", ",", "std_m1m2", ",", "n", ")", ":", "pm", "=", "ProbModel", "(", "mu_m1m2", ",", "std_m1m2", ")", "samples", "=", "pm", ".", "sample", "(", "n", ")", "update_simulations", "(", "re...
https://github.com/cheind/pytorch-blender/blob/ef35c5b3eec884515d4f343671a8a3337b8aa1fb/examples/densityopt/densityopt.py#L121-L131
rpryzant/neutralizing-bias
fd1358a217f064db28f436879da2d05e1ae44079
baselines/decoders.py
python
AttentionalLSTM.__init__
(self, input_dim, hidden_dim, config, attention)
Initialize params.
Initialize params.
[ "Initialize", "params", "." ]
def __init__(self, input_dim, hidden_dim, config, attention): """Initialize params.""" super(AttentionalLSTM, self).__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.num_layers = 1 self.use_attention = attention self.config = config self.cell = nn.LSTMCell(input_dim, hidden_dim) if self.use_attention: self.attention_layer = ops.BilinearAttention(hidden_dim)
[ "def", "__init__", "(", "self", ",", "input_dim", ",", "hidden_dim", ",", "config", ",", "attention", ")", ":", "super", "(", "AttentionalLSTM", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "input_dim", "=", "input_dim", "self", ".", "hidden...
https://github.com/rpryzant/neutralizing-bias/blob/fd1358a217f064db28f436879da2d05e1ae44079/baselines/decoders.py#L16-L27
BEEmod/BEE2.4
02767f3cf476581789425ab308ca1bea978f6a74
src/packages/item.py
python
ItemConfig.export
(exp_data: ExportData)
This export is done in Item.export(). Here we don't know the version set for each item.
This export is done in Item.export().
[ "This", "export", "is", "done", "in", "Item", ".", "export", "()", "." ]
def export(exp_data: ExportData) -> None: """This export is done in Item.export(). Here we don't know the version set for each item. """ pass
[ "def", "export", "(", "exp_data", ":", "ExportData", ")", "->", "None", ":", "pass" ]
https://github.com/BEEmod/BEE2.4/blob/02767f3cf476581789425ab308ca1bea978f6a74/src/packages/item.py#L738-L743
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/coverage/results.py
python
Analysis.branch_stats
(self)
return stats
Get stats about branches. Returns a dict mapping line numbers to a tuple: (total_exits, taken_exits).
Get stats about branches.
[ "Get", "stats", "about", "branches", "." ]
def branch_stats(self): """Get stats about branches. Returns a dict mapping line numbers to a tuple: (total_exits, taken_exits). """ missing_arcs = self.missing_branch_arcs() stats = {} for lnum in self.branch_lines(): exits = self.exit_counts[lnum] try: missing = len(missing_arcs[lnum]) except KeyError: missing = 0 stats[lnum] = (exits, exits - missing) return stats
[ "def", "branch_stats", "(", "self", ")", ":", "missing_arcs", "=", "self", ".", "missing_branch_arcs", "(", ")", "stats", "=", "{", "}", "for", "lnum", "in", "self", ".", "branch_lines", "(", ")", ":", "exits", "=", "self", ".", "exit_counts", "[", "ln...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/coverage/results.py#L141-L157
pyvisa/pyvisa-py
91e3475883b0f6e20dd308f0925f9940fcf818ea
pyvisa_py/protocols/rpc.py
python
Server.handle_0
(self)
[]
def handle_0(self): # Handle NULL message self.turn_around()
[ "def", "handle_0", "(", "self", ")", ":", "# Handle NULL message", "self", ".", "turn_around", "(", ")" ]
https://github.com/pyvisa/pyvisa-py/blob/91e3475883b0f6e20dd308f0925f9940fcf818ea/pyvisa_py/protocols/rpc.py#L899-L901
DataBiosphere/toil
2e148eee2114ece8dcc3ec8a83f36333266ece0d
src/toil/batchSystems/kubernetes.py
python
KubernetesBatchSystem._create_pod_spec
( self, jobDesc: JobDescription, job_environment: Optional[Dict[str, str]] = None )
return pod_spec
Make the specification for a pod that can execute the given job.
Make the specification for a pod that can execute the given job.
[ "Make", "the", "specification", "for", "a", "pod", "that", "can", "execute", "the", "given", "job", "." ]
def _create_pod_spec( self, jobDesc: JobDescription, job_environment: Optional[Dict[str, str]] = None ) -> kubernetes.client.V1PodSpec: """ Make the specification for a pod that can execute the given job. """ environment = self.environment.copy() if job_environment: environment.update(job_environment) # Make a job dict to send to the executor. # First just wrap the command and the environment to run it in # TODO: send environment via pod spec job = {'command': jobDesc.command, 'environment': environment} # TODO: query customDockerInitCmd to respect TOIL_CUSTOM_DOCKER_INIT_COMMAND if self.userScript is not None: # If there's a user script resource be sure to send it along job['userScript'] = self.userScript # Encode it in a form we can send in a command-line argument. Pickle in # the highest protocol to prevent mixed-Python-version workflows from # trying to work. Make sure it is text so we can ship it to Kubernetes # via JSON. encodedJob = base64.b64encode(pickle.dumps(job, pickle.HIGHEST_PROTOCOL)).decode('utf-8') # The Kubernetes API makes sense only in terms of the YAML format. Objects # represent sections of the YAML files. Except from our point of view, all # the internal nodes in the YAML structure are named and typed. # For docs, start at the root of the job hierarchy: # https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Job.md # Make a definition for the container's resource requirements. # Add on a bit for Kubernetes overhead (Toil worker's memory, hot deployed # user scripts). # Kubernetes needs some lower limit of memory to run the pod at all without # OOMing. We also want to provision some extra space so that when # we test _isPodStuckOOM we never get True unless the job has # exceeded jobDesc.memory. requirements_dict = {'cpu': jobDesc.cores, 'memory': jobDesc.memory + 1024 * 1024 * 512, 'ephemeral-storage': jobDesc.disk + 1024 * 1024 * 512} # Use the requirements as the limits, for predictable behavior, and because # the UCSC Kubernetes admins want it that way. limits_dict = requirements_dict resources = kubernetes.client.V1ResourceRequirements(limits=limits_dict, requests=requirements_dict) # Collect volumes and mounts volumes = [] mounts = [] if self.host_path is not None: # Provision Toil WorkDir from a HostPath volume, to share with other pods host_path_volume_name = 'workdir' # Use type='Directory' to fail if the host directory doesn't exist already. host_path_volume_source = kubernetes.client.V1HostPathVolumeSource(path=self.host_path, type='Directory') host_path_volume = kubernetes.client.V1Volume(name=host_path_volume_name, host_path=host_path_volume_source) volumes.append(host_path_volume) host_path_volume_mount = kubernetes.client.V1VolumeMount(mount_path=self.workerWorkDir, name=host_path_volume_name) mounts.append(host_path_volume_mount) else: # Provision Toil WorkDir as an ephemeral volume ephemeral_volume_name = 'workdir' ephemeral_volume_source = kubernetes.client.V1EmptyDirVolumeSource() ephemeral_volume = kubernetes.client.V1Volume(name=ephemeral_volume_name, empty_dir=ephemeral_volume_source) volumes.append(ephemeral_volume) ephemeral_volume_mount = kubernetes.client.V1VolumeMount(mount_path=self.workerWorkDir, name=ephemeral_volume_name) mounts.append(ephemeral_volume_mount) if self.awsSecretName is not None: # Also mount an AWS secret, if provided. # TODO: make this generic somehow secret_volume_name = 's3-credentials' secret_volume_source = kubernetes.client.V1SecretVolumeSource(secret_name=self.awsSecretName) secret_volume = kubernetes.client.V1Volume(name=secret_volume_name, secret=secret_volume_source) volumes.append(secret_volume) secret_volume_mount = kubernetes.client.V1VolumeMount(mount_path='/root/.aws', name=secret_volume_name) mounts.append(secret_volume_mount) # Make a container definition container = kubernetes.client.V1Container(command=['_toil_contained_executor', encodedJob], image=self.dockerImage, name="runner-container", resources=resources, volume_mounts=mounts) # Wrap the container in a spec pod_spec = kubernetes.client.V1PodSpec(containers=[container], volumes=volumes, restart_policy="Never") # Tell the spec where to land pod_spec.affinity = self._create_affinity(jobDesc.preemptable) if self.service_account: # Apply service account if set pod_spec.service_account_name = self.service_account return pod_spec
[ "def", "_create_pod_spec", "(", "self", ",", "jobDesc", ":", "JobDescription", ",", "job_environment", ":", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "kubernetes", ".", "client", ".", "V1PodSpec", ":", "environment"...
https://github.com/DataBiosphere/toil/blob/2e148eee2114ece8dcc3ec8a83f36333266ece0d/src/toil/batchSystems/kubernetes.py#L379-L484
huggingface/datasets
249b4a38390bf1543f5b6e2f3dc208b5689c1c13
datasets/tiny_shakespeare/tiny_shakespeare.py
python
TinyShakespeare._generate_examples
(self, split_key, split_text)
Yields examples.
Yields examples.
[ "Yields", "examples", "." ]
def _generate_examples(self, split_key, split_text): """Yields examples.""" data_key = split_key # Should uniquely identify the thing yielded feature_dict = {"text": split_text} yield data_key, feature_dict
[ "def", "_generate_examples", "(", "self", ",", "split_key", ",", "split_text", ")", ":", "data_key", "=", "split_key", "# Should uniquely identify the thing yielded", "feature_dict", "=", "{", "\"text\"", ":", "split_text", "}", "yield", "data_key", ",", "feature_dict...
https://github.com/huggingface/datasets/blob/249b4a38390bf1543f5b6e2f3dc208b5689c1c13/datasets/tiny_shakespeare/tiny_shakespeare.py#L106-L110
mikeckennedy/write-pythonic-code-demos
1bdfb61c90fa778e0da800395f1783929b018675
code/ch_01_pep8/_01_pep8.py
python
some_method
(a1, a2, a3)
some_method returns the larger of 1 or 2 :param a1: First item to compare :param a2: Second item to compare :param a3: Should reverse :return: 1 or 2
some_method returns the larger of 1 or 2
[ "some_method", "returns", "the", "larger", "of", "1", "or", "2" ]
def some_method(a1, a2, a3): """ some_method returns the larger of 1 or 2 :param a1: First item to compare :param a2: Second item to compare :param a3: Should reverse :return: 1 or 2 """ x = 1 if x > 2: return 1 else: return 2
[ "def", "some_method", "(", "a1", ",", "a2", ",", "a3", ")", ":", "x", "=", "1", "if", "x", ">", "2", ":", "return", "1", "else", ":", "return", "2" ]
https://github.com/mikeckennedy/write-pythonic-code-demos/blob/1bdfb61c90fa778e0da800395f1783929b018675/code/ch_01_pep8/_01_pep8.py#L15-L29
RTIInternational/gobbli
d9ec8132f74ce49dc4bead2fad25b661bcef6e76
gobbli/augment/marian/model.py
python
MarianMT.image_tag
(self)
return f"gobbli-marian-nmt"
Returns: The Docker image tag to be used for the Marian container.
Returns: The Docker image tag to be used for the Marian container.
[ "Returns", ":", "The", "Docker", "image", "tag", "to", "be", "used", "for", "the", "Marian", "container", "." ]
def image_tag(self) -> str: """ Returns: The Docker image tag to be used for the Marian container. """ return f"gobbli-marian-nmt"
[ "def", "image_tag", "(", "self", ")", "->", "str", ":", "return", "f\"gobbli-marian-nmt\"" ]
https://github.com/RTIInternational/gobbli/blob/d9ec8132f74ce49dc4bead2fad25b661bcef6e76/gobbli/augment/marian/model.py#L177-L182
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
python
Standard_Suite_Events.make
(self, _no_object=None, _attributes={}, **_arguments)
make: Make a new element Keyword argument new: the class of the new element Keyword argument at: the location at which to insert the element Keyword argument with_data: the initial data for the element Keyword argument with_properties: the initial values for the properties of the element Keyword argument _attributes: AppleEvent attribute dictionary Returns: to the new object(s)
make: Make a new element Keyword argument new: the class of the new element Keyword argument at: the location at which to insert the element Keyword argument with_data: the initial data for the element Keyword argument with_properties: the initial values for the properties of the element Keyword argument _attributes: AppleEvent attribute dictionary Returns: to the new object(s)
[ "make", ":", "Make", "a", "new", "element", "Keyword", "argument", "new", ":", "the", "class", "of", "the", "new", "element", "Keyword", "argument", "at", ":", "the", "location", "at", "which", "to", "insert", "the", "element", "Keyword", "argument", "with...
def make(self, _no_object=None, _attributes={}, **_arguments): """make: Make a new element Keyword argument new: the class of the new element Keyword argument at: the location at which to insert the element Keyword argument with_data: the initial data for the element Keyword argument with_properties: the initial values for the properties of the element Keyword argument _attributes: AppleEvent attribute dictionary Returns: to the new object(s) """ _code = 'core' _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) if _no_object is not None: raise TypeError, 'No direct arg expected' _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "make", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'crel'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", ...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py#L245-L267
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/wordnet/wordnet.py
python
Sense.__str__
(self)
return `self.form` + " in " + str(self.synset)
Return a human-readable representation. >>> str(N['dog']) 'dog(n.)'
Return a human-readable representation. >>> str(N['dog']) 'dog(n.)'
[ "Return", "a", "human", "-", "readable", "representation", ".", ">>>", "str", "(", "N", "[", "dog", "]", ")", "dog", "(", "n", ".", ")" ]
def __str__(self): """Return a human-readable representation. >>> str(N['dog']) 'dog(n.)' """ return `self.form` + " in " + str(self.synset)
[ "def", "__str__", "(", "self", ")", ":", "return", "`self.form`", "+", "\" in \"", "+", "str", "(", "self", ".", "synset", ")" ]
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/wordnet/wordnet.py#L578-L584
RatulSaha/leetcode
81a71f6acbe3120b10fd30e1b38f41bad7e8e2cb
101-150/106-binary-tree-in-post.py
python
buildTree
(inorder, postorder)
return root
:type inorder: List[int] :type postorder: List[int] :rtype: TreeNode
:type inorder: List[int] :type postorder: List[int] :rtype: TreeNode
[ ":", "type", "inorder", ":", "List", "[", "int", "]", ":", "type", "postorder", ":", "List", "[", "int", "]", ":", "rtype", ":", "TreeNode" ]
def buildTree(inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not postorder or not inorder: return None root_val = postorder[-1] root_val_index = inorder.index(root_val) root = TreeNode(root_val) post_left = postorder[:root_val_index] post_right = postorder[root_val_index:-1] in_left = inorder[:root_val_index] in_right = inorder[root_val_index+1:] root.left = buildTree(in_left,post_left) root.right = buildTree(in_right,post_right) return root
[ "def", "buildTree", "(", "inorder", ",", "postorder", ")", ":", "if", "not", "postorder", "or", "not", "inorder", ":", "return", "None", "root_val", "=", "postorder", "[", "-", "1", "]", "root_val_index", "=", "inorder", ".", "index", "(", "root_val", ")...
https://github.com/RatulSaha/leetcode/blob/81a71f6acbe3120b10fd30e1b38f41bad7e8e2cb/101-150/106-binary-tree-in-post.py#L21-L38
OpenAgricultureFoundation/openag-device-software
a51d2de399c0a6781ae51d0dcfaae1583d75f346
device/peripherals/modules/atlas_ec/manager.py
python
AtlasECManager.new_compensation_temperature
(self)
return True
Checks if there is a new compensation temperature value.
Checks if there is a new compensation temperature value.
[ "Checks", "if", "there", "is", "a", "new", "compensation", "temperature", "value", "." ]
def new_compensation_temperature(self) -> bool: """Checks if there is a new compensation temperature value.""" # Check if calibrating if self.mode == modes.CALIBRATE: return False # Check if compensation temperature exists if self.temperature == None: return False # Check if temperature value sufficiently different delta = abs(self.temperature - self.prev_temperature) # type: ignore if delta < self.temperature_threshold: return False # New compensation temperature exists return True
[ "def", "new_compensation_temperature", "(", "self", ")", "->", "bool", ":", "# Check if calibrating", "if", "self", ".", "mode", "==", "modes", ".", "CALIBRATE", ":", "return", "False", "# Check if compensation temperature exists", "if", "self", ".", "temperature", ...
https://github.com/OpenAgricultureFoundation/openag-device-software/blob/a51d2de399c0a6781ae51d0dcfaae1583d75f346/device/peripherals/modules/atlas_ec/manager.py#L117-L134
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/_weakrefset.py
python
WeakSet.__iter__
(self)
[]
def __iter__(self): with _IterationGuard(self): for itemref in self.data: item = itemref() if item is not None: # Caveat: the iterator will keep a strong reference to # `item` until it is resumed or closed. yield item
[ "def", "__iter__", "(", "self", ")", ":", "with", "_IterationGuard", "(", "self", ")", ":", "for", "itemref", "in", "self", ".", "data", ":", "item", "=", "itemref", "(", ")", "if", "item", "is", "not", "None", ":", "# Caveat: the iterator will keep a stro...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/_weakrefset.py#L58-L65
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/_task_modules/channels/ci_channel.py
python
CIChannel.ci_period_dig_fltr_min_pulse_width
(self)
return val.value
float: Specifies in seconds the minimum pulse width the filter recognizes.
float: Specifies in seconds the minimum pulse width the filter recognizes.
[ "float", ":", "Specifies", "in", "seconds", "the", "minimum", "pulse", "width", "the", "filter", "recognizes", "." ]
def ci_period_dig_fltr_min_pulse_width(self): """ float: Specifies in seconds the minimum pulse width the filter recognizes. """ val = ctypes.c_double() cfunc = lib_importer.windll.DAQmxGetCIPeriodDigFltrMinPulseWidth if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ lib_importer.task_handle, ctypes_byte_str, ctypes.POINTER(ctypes.c_double)] error_code = cfunc( self._handle, self._name, ctypes.byref(val)) check_for_error(error_code) return val.value
[ "def", "ci_period_dig_fltr_min_pulse_width", "(", "self", ")", ":", "val", "=", "ctypes", ".", "c_double", "(", ")", "cfunc", "=", "lib_importer", ".", "windll", ".", "DAQmxGetCIPeriodDigFltrMinPulseWidth", "if", "cfunc", ".", "argtypes", "is", "None", ":", "wit...
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/channels/ci_channel.py#L6162-L6181
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/pkg_resources/__init__.py
python
Environment.__init__
( self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR)
Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distributions must be compatible with. If unspecified, it defaults to the current platform. `python` is an optional string naming the desired version of Python (e.g. ``'3.6'``); it defaults to the current version. You may explicitly set `platform` (and/or `python`) to ``None`` if you wish to map *all* distributions, not just those compatible with the running platform or Python version.
Snapshot distributions available on a search path
[ "Snapshot", "distributions", "available", "on", "a", "search", "path" ]
def __init__( self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR): """Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distributions must be compatible with. If unspecified, it defaults to the current platform. `python` is an optional string naming the desired version of Python (e.g. ``'3.6'``); it defaults to the current version. You may explicitly set `platform` (and/or `python`) to ``None`` if you wish to map *all* distributions, not just those compatible with the running platform or Python version. """ self._distmap = {} self.platform = platform self.python = python self.scan(search_path)
[ "def", "__init__", "(", "self", ",", "search_path", "=", "None", ",", "platform", "=", "get_supported_platform", "(", ")", ",", "python", "=", "PY_MAJOR", ")", ":", "self", ".", "_distmap", "=", "{", "}", "self", ".", "platform", "=", "platform", "self",...
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pkg_resources/__init__.py#L957-L979
littlecodersh/MyPlatform
6f9a946605466f580205f6e9e96e533720fce578
vendor/requests/sessions.py
python
Session.request
(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)
return resp
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object.
[ "Constructs", "a", ":", "class", ":", "Request", "<Request", ">", "prepares", "it", "and", "sends", "it", ".", "Returns", ":", "class", ":", "Response", "<Response", ">", "object", "." ]
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. """ # Create the Request. req = Request( method = method.upper(), url = url, headers = headers, files = files, data = data or {}, json = json, params = params or {}, auth = auth, cookies = cookies, hooks = hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "files", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "N...
https://github.com/littlecodersh/MyPlatform/blob/6f9a946605466f580205f6e9e96e533720fce578/vendor/requests/sessions.py#L392-L470
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/_collections_abc.py
python
Generator.close
(self)
Raise GeneratorExit inside generator.
Raise GeneratorExit inside generator.
[ "Raise", "GeneratorExit", "inside", "generator", "." ]
def close(self): """Raise GeneratorExit inside generator. """ try: self.throw(GeneratorExit) except (GeneratorExit, StopIteration): pass else: raise RuntimeError("generator ignored GeneratorExit")
[ "def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "throw", "(", "GeneratorExit", ")", "except", "(", "GeneratorExit", ",", "StopIteration", ")", ":", "pass", "else", ":", "raise", "RuntimeError", "(", "\"generator ignored GeneratorExit\"", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/_collections_abc.py#L340-L348
pyqteval/evlal_win
ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92
Clicked_Controller/requests/models.py
python
RequestEncodingMixin._encode_files
(files, data)
return body, content_type
Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
Build the body for a multipart/form-data request.
[ "Build", "the", "body", "for", "a", "multipart", "/", "form", "-", "data", "request", "." ]
def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). """ if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, '__iter__'): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( (field.decode('utf-8') if isinstance(field, bytes) else field, v.encode('utf-8') if isinstance(v, str) else v)) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp else: fdata = fp.read() rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type
[ "def", "_encode_files", "(", "files", ",", "data", ")", ":", "if", "(", "not", "files", ")", ":", "raise", "ValueError", "(", "\"Files must be provided.\"", ")", "elif", "isinstance", "(", "data", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\...
https://github.com/pyqteval/evlal_win/blob/ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92/Clicked_Controller/requests/models.py#L102-L160
sqlfluff/sqlfluff
c2278f41f270a29ef5ffc6b179236abf32dc18e1
src/sqlfluff/rules/L056.py
python
Rule_L056._eval
(self, context: RuleContext)
return None
r"""``SP_`` prefix should not be used for user-defined stored procedures.
r"""``SP_`` prefix should not be used for user-defined stored procedures.
[ "r", "SP_", "prefix", "should", "not", "be", "used", "for", "user", "-", "defined", "stored", "procedures", "." ]
def _eval(self, context: RuleContext) -> Optional[LintResult]: r"""``SP_`` prefix should not be used for user-defined stored procedures.""" # Rule only applies to T-SQL syntax. if context.dialect.name != "tsql": return None # We are only interested in CREATE PROCEDURE statements. if context.segment.type != "create_procedure_statement": return None # Find the object reference for the stored procedure. object_reference_segment = next( (s for s in context.segment.segments if s.type == "object_reference") ) # We only want to check the stored procedure name. procedure_segment = object_reference_segment.segments[-1] # If stored procedure name starts with 'SP\_' then raise lint error. if procedure_segment.raw_upper.lstrip('["').startswith("SP_"): "s".lstrip return LintResult( procedure_segment, description="'SP_' prefix should not be used for user-defined stored procedures.", ) return None
[ "def", "_eval", "(", "self", ",", "context", ":", "RuleContext", ")", "->", "Optional", "[", "LintResult", "]", ":", "# Rule only applies to T-SQL syntax.", "if", "context", ".", "dialect", ".", "name", "!=", "\"tsql\"", ":", "return", "None", "# We are only int...
https://github.com/sqlfluff/sqlfluff/blob/c2278f41f270a29ef5ffc6b179236abf32dc18e1/src/sqlfluff/rules/L056.py#L52-L78
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/difflib.py
python
ndiff
(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)
return Differ(linejunk, charjunk).compare(a, b)
r""" Compare `a` and `b` (lists of strings); return a `Differ`-style delta. Optional keyword parameters `linejunk` and `charjunk` are for filter functions (or None): - linejunk: A function that should accept a single string argument, and return true iff the string is junk. The default is None, and is recommended; as of Python 2.3, an adaptive notion of "noise" lines is used that does a good job on its own. - charjunk: A function that should accept a string of length 1. The default is module-level function IS_CHARACTER_JUNK, which filters out whitespace characters (a blank or tab; note: bad idea to include newline in this!). Tools/scripts/ndiff.py is a command-line front-end to this function. Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> print ''.join(diff), - one ? ^ + ore ? ^ - two - three ? - + tree + emu
r""" Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
[ "r", "Compare", "a", "and", "b", "(", "lists", "of", "strings", ")", ";", "return", "a", "Differ", "-", "style", "delta", "." ]
def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK): r""" Compare `a` and `b` (lists of strings); return a `Differ`-style delta. Optional keyword parameters `linejunk` and `charjunk` are for filter functions (or None): - linejunk: A function that should accept a single string argument, and return true iff the string is junk. The default is None, and is recommended; as of Python 2.3, an adaptive notion of "noise" lines is used that does a good job on its own. - charjunk: A function that should accept a string of length 1. The default is module-level function IS_CHARACTER_JUNK, which filters out whitespace characters (a blank or tab; note: bad idea to include newline in this!). Tools/scripts/ndiff.py is a command-line front-end to this function. Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> print ''.join(diff), - one ? ^ + ore ? ^ - two - three ? - + tree + emu """ return Differ(linejunk, charjunk).compare(a, b)
[ "def", "ndiff", "(", "a", ",", "b", ",", "linejunk", "=", "None", ",", "charjunk", "=", "IS_CHARACTER_JUNK", ")", ":", "return", "Differ", "(", "linejunk", ",", "charjunk", ")", ".", "compare", "(", "a", ",", "b", ")" ]
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/difflib.py#L1314-L1348