repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
paulovn/sparql-kernel | sparqlkernel/utils.py | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/utils.py#L89-L111 | def data_msg( msg, mtype=None ):
"""
Return a Jupyter display_data message, in both HTML & text formats, by
formatting a given single message. The passed message may be:
* An exception (including a KrnlException): will generate an error message
* A list of messages (with \c mtype equal to \c mu... | [
"def",
"data_msg",
"(",
"msg",
",",
"mtype",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"KrnlException",
")",
":",
"return",
"msg",
"(",
")",
"# a KrnlException knows how to format itself",
"elif",
"isinstance",
"(",
"msg",
",",
"Exception",
... | Return a Jupyter display_data message, in both HTML & text formats, by
formatting a given single message. The passed message may be:
* An exception (including a KrnlException): will generate an error message
* A list of messages (with \c mtype equal to \c multi)
* A single message
@param m... | [
"Return",
"a",
"Jupyter",
"display_data",
"message",
"in",
"both",
"HTML",
"&",
"text",
"formats",
"by",
"formatting",
"a",
"given",
"single",
"message",
".",
"The",
"passed",
"message",
"may",
"be",
":",
"*",
"An",
"exception",
"(",
"including",
"a",
"Krn... | python | train |
ska-sa/purr | Purr/Plugins/local_pychart/chart_data.py | https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Plugins/local_pychart/chart_data.py#L291-L309 | def func(f, xmin, xmax, step=None):
"""Create sample points from function <f>, which must be a
single-parameter function that returns a number (e.g., math.sin).
Parameters <xmin> and <xmax> specify the first and last X values, and
<step> specifies the sampling interval.
>>> chart_data.func(math.sin, 0,... | [
"def",
"func",
"(",
"f",
",",
"xmin",
",",
"xmax",
",",
"step",
"=",
"None",
")",
":",
"data",
"=",
"[",
"]",
"x",
"=",
"xmin",
"if",
"not",
"step",
":",
"step",
"=",
"(",
"xmax",
"-",
"xmin",
")",
"/",
"100.0",
"while",
"x",
"<",
"xmax",
"... | Create sample points from function <f>, which must be a
single-parameter function that returns a number (e.g., math.sin).
Parameters <xmin> and <xmax> specify the first and last X values, and
<step> specifies the sampling interval.
>>> chart_data.func(math.sin, 0, math.pi * 4, math.pi / 2)
[(0, 0.0), (1.57... | [
"Create",
"sample",
"points",
"from",
"function",
"<f",
">",
"which",
"must",
"be",
"a",
"single",
"-",
"parameter",
"function",
"that",
"returns",
"a",
"number",
"(",
"e",
".",
"g",
".",
"math",
".",
"sin",
")",
".",
"Parameters",
"<xmin",
">",
"and",... | python | train |
cherrypy/cheroot | cheroot/wsgi.py | https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/wsgi.py#L249-L318 | def get_environ(self):
"""Return a new environ dict targeting the given wsgi.version."""
req = self.req
req_conn = req.conn
env = {
# set a non-standard environ entry so the WSGI app can know what
# the *real* server protocol is (and what features to support).
... | [
"def",
"get_environ",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"req",
"req_conn",
"=",
"req",
".",
"conn",
"env",
"=",
"{",
"# set a non-standard environ entry so the WSGI app can know what",
"# the *real* server protocol is (and what features to support).",
"# See h... | Return a new environ dict targeting the given wsgi.version. | [
"Return",
"a",
"new",
"environ",
"dict",
"targeting",
"the",
"given",
"wsgi",
".",
"version",
"."
] | python | train |
googlefonts/fontbakery | Lib/fontbakery/callable.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/callable.py#L18-L29 | def cached_getter(func):
"""Decorate a property by executing it at instatiation time and cache the
result on the instance object."""
@wraps(func)
def wrapper(self):
attribute = f'_{func.__name__}'
value = getattr(self, attribute, None)
if value is None:
value = func(self)
setattr(self, a... | [
"def",
"cached_getter",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
")",
":",
"attribute",
"=",
"f'_{func.__name__}'",
"value",
"=",
"getattr",
"(",
"self",
",",
"attribute",
",",
"None",
")",
"if",
"value",
"i... | Decorate a property by executing it at instatiation time and cache the
result on the instance object. | [
"Decorate",
"a",
"property",
"by",
"executing",
"it",
"at",
"instatiation",
"time",
"and",
"cache",
"the",
"result",
"on",
"the",
"instance",
"object",
"."
] | python | train |
edx/bok-choy | bok_choy/query.py | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L452-L466 | def is_focused(self):
"""
Checks that *at least one* matched element is focused. More
specifically, it checks whether the element is document.activeElement.
If no matching element is focused, this returns `False`.
Returns:
bool
"""
active_el = self.br... | [
"def",
"is_focused",
"(",
"self",
")",
":",
"active_el",
"=",
"self",
".",
"browser",
".",
"execute_script",
"(",
"\"return document.activeElement\"",
")",
"query_results",
"=",
"self",
".",
"map",
"(",
"lambda",
"el",
":",
"el",
"==",
"active_el",
",",
"'fo... | Checks that *at least one* matched element is focused. More
specifically, it checks whether the element is document.activeElement.
If no matching element is focused, this returns `False`.
Returns:
bool | [
"Checks",
"that",
"*",
"at",
"least",
"one",
"*",
"matched",
"element",
"is",
"focused",
".",
"More",
"specifically",
"it",
"checks",
"whether",
"the",
"element",
"is",
"document",
".",
"activeElement",
".",
"If",
"no",
"matching",
"element",
"is",
"focused"... | python | train |
log2timeline/plaso | plaso/storage/sqlite/sqlite_file.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/sqlite/sqlite_file.py#L829-L847 | def GetEventTagByIdentifier(self, identifier):
"""Retrieves a specific event tag.
Args:
identifier (SQLTableIdentifier): event tag identifier.
Returns:
EventTag: event tag or None if not available.
"""
event_tag = self._GetAttributeContainerByIndex(
self._CONTAINER_TYPE_EVENT_T... | [
"def",
"GetEventTagByIdentifier",
"(",
"self",
",",
"identifier",
")",
":",
"event_tag",
"=",
"self",
".",
"_GetAttributeContainerByIndex",
"(",
"self",
".",
"_CONTAINER_TYPE_EVENT_TAG",
",",
"identifier",
".",
"row_identifier",
"-",
"1",
")",
"if",
"event_tag",
"... | Retrieves a specific event tag.
Args:
identifier (SQLTableIdentifier): event tag identifier.
Returns:
EventTag: event tag or None if not available. | [
"Retrieves",
"a",
"specific",
"event",
"tag",
"."
] | python | train |
saltstack/salt | salt/modules/postgres.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1393-L1421 | def installed_extensions(user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
List installed postgresql extensions
CLI Example:
.. code-block:: ... | [
"def",
"installed_extensions",
"(",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"exts",
"=",
"[",
"]",
"query",
"=",
... | List installed postgresql extensions
CLI Example:
.. code-block:: bash
salt '*' postgres.installed_extensions | [
"List",
"installed",
"postgresql",
"extensions"
] | python | train |
raiden-network/raiden | raiden/network/transport/matrix/transport.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L180-L254 | def _check_and_send(self):
"""Check and send all pending/queued messages that are not waiting on retry timeout
After composing the to-be-sent message, also message queue from messages that are not
present in the respective SendMessageEvent queue anymore
"""
if self.transport._st... | [
"def",
"_check_and_send",
"(",
"self",
")",
":",
"if",
"self",
".",
"transport",
".",
"_stop_event",
".",
"ready",
"(",
")",
"or",
"not",
"self",
".",
"transport",
".",
"greenlet",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Can't retry - stopped\"",
... | Check and send all pending/queued messages that are not waiting on retry timeout
After composing the to-be-sent message, also message queue from messages that are not
present in the respective SendMessageEvent queue anymore | [
"Check",
"and",
"send",
"all",
"pending",
"/",
"queued",
"messages",
"that",
"are",
"not",
"waiting",
"on",
"retry",
"timeout"
] | python | train |
bivab/smbus-cffi | smbus/smbus.py | https://github.com/bivab/smbus-cffi/blob/7486931edf55fcdde84db38356331c65851a40b1/smbus/smbus.py#L102-L111 | def read_byte(self, addr):
"""read_byte(addr) -> result
Perform SMBus Read Byte transaction.
"""
self._set_addr(addr)
result = SMBUS.i2c_smbus_read_byte(self._fd)
if result == -1:
raise IOError(ffi.errno)
return result | [
"def",
"read_byte",
"(",
"self",
",",
"addr",
")",
":",
"self",
".",
"_set_addr",
"(",
"addr",
")",
"result",
"=",
"SMBUS",
".",
"i2c_smbus_read_byte",
"(",
"self",
".",
"_fd",
")",
"if",
"result",
"==",
"-",
"1",
":",
"raise",
"IOError",
"(",
"ffi",... | read_byte(addr) -> result
Perform SMBus Read Byte transaction. | [
"read_byte",
"(",
"addr",
")",
"-",
">",
"result"
] | python | test |
diefans/objective | src/objective/core.py | https://github.com/diefans/objective/blob/e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88/src/objective/core.py#L134-L149 | def node(self):
"""Create a :py:class:`Node` instance.
All args and kwargs are forwarded to the node.
:returns: a :py:class:`Node` instance
"""
if self.node_class is None:
raise ValueError("You have to create an ``Item`` by calling ``__init__`` with ``node_class`` ... | [
"def",
"node",
"(",
"self",
")",
":",
"if",
"self",
".",
"node_class",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You have to create an ``Item`` by calling ``__init__`` with ``node_class`` argument\"",
"\" or by decorating a ``Node`` class.\"",
")",
"node",
"=",
"sel... | Create a :py:class:`Node` instance.
All args and kwargs are forwarded to the node.
:returns: a :py:class:`Node` instance | [
"Create",
"a",
":",
"py",
":",
"class",
":",
"Node",
"instance",
"."
] | python | train |
SecurityInnovation/PGPy | pgpy/pgp.py | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L586-L591 | def selfsig(self):
"""
This will be the most recent, self-signature of this User ID or Attribute. If there isn't one, this will be ``None``.
"""
if self.parent is not None:
return next((sig for sig in reversed(self._signatures) if sig.signer == self.parent.fingerprint.keyid),... | [
"def",
"selfsig",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"return",
"next",
"(",
"(",
"sig",
"for",
"sig",
"in",
"reversed",
"(",
"self",
".",
"_signatures",
")",
"if",
"sig",
".",
"signer",
"==",
"self",
".",
... | This will be the most recent, self-signature of this User ID or Attribute. If there isn't one, this will be ``None``. | [
"This",
"will",
"be",
"the",
"most",
"recent",
"self",
"-",
"signature",
"of",
"this",
"User",
"ID",
"or",
"Attribute",
".",
"If",
"there",
"isn",
"t",
"one",
"this",
"will",
"be",
"None",
"."
] | python | train |
RedHatInsights/insights-core | insights/parsers/system_time.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/system_time.py#L135-L153 | def get_last(self, keyword, param=None, default=None):
"""
Get the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds the last declaration of the given parameter (which is the
one which takes effect). If no parame... | [
"def",
"get_last",
"(",
"self",
",",
"keyword",
",",
"param",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_param",
"(",
"keyword",
",",
"param",
",",
"default",
")",
"[",
"-",
"1",
"]"
] | Get the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds the last declaration of the given parameter (which is the
one which takes effect). If no parameter is given, then the entire
line is treated as the parameter and ... | [
"Get",
"the",
"parameters",
"for",
"a",
"given",
"keyword",
"or",
"default",
"if",
"keyword",
"or",
"parameter",
"are",
"not",
"present",
"in",
"the",
"configuration",
"."
] | python | train |
ScriptSmith/socialreaper | socialreaper/tools.py | https://github.com/ScriptSmith/socialreaper/blob/87fcc3b74bbed6c4f8e7f49a5f0eb8a616cf38da/socialreaper/tools.py#L31-L49 | def fill_gaps(list_dicts):
"""
Fill gaps in a list of dictionaries. Add empty keys to dictionaries in
the list that don't contain other entries' keys
:param list_dicts: A list of dictionaries
:return: A list of field names, a list of dictionaries with identical keys
"""
field_name... | [
"def",
"fill_gaps",
"(",
"list_dicts",
")",
":",
"field_names",
"=",
"[",
"]",
"# != set bc. preserving order is better for output\r",
"for",
"datum",
"in",
"list_dicts",
":",
"for",
"key",
"in",
"datum",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
... | Fill gaps in a list of dictionaries. Add empty keys to dictionaries in
the list that don't contain other entries' keys
:param list_dicts: A list of dictionaries
:return: A list of field names, a list of dictionaries with identical keys | [
"Fill",
"gaps",
"in",
"a",
"list",
"of",
"dictionaries",
".",
"Add",
"empty",
"keys",
"to",
"dictionaries",
"in",
"the",
"list",
"that",
"don",
"t",
"contain",
"other",
"entries",
"keys",
":",
"param",
"list_dicts",
":",
"A",
"list",
"of",
"dictionaries",
... | python | valid |
jmgilman/Neolib | neolib/pyamf/__init__.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L436-L460 | def get_decoder(encoding, *args, **kwargs):
"""
Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}.
"""
def _get_decoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except Imp... | [
"def",
"get_decoder",
"(",
"encoding",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_get_decoder_class",
"(",
")",
":",
"if",
"encoding",
"==",
"AMF0",
":",
"try",
":",
"from",
"cpyamf",
"import",
"amf0",
"except",
"ImportError",
":",
"... | Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}. | [
"Returns",
"a",
"L",
"{",
"codec",
".",
"Decoder",
"}",
"capable",
"of",
"decoding",
"AMF",
"[",
"C",
"{",
"encoding",
"}",
"]",
"streams",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/sortedcontainers/sorteddict.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/sortedcontainers/sorteddict.py#L17-L27 | def not26(func):
"""Function decorator for methods not implemented in Python 2.6."""
@wraps(func)
def errfunc(*args, **kwargs):
raise NotImplementedError
if hexversion < 0x02070000:
return errfunc
else:
return func | [
"def",
"not26",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"errfunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"if",
"hexversion",
"<",
"0x02070000",
":",
"return",
"errfunc",
"else",
":",
... | Function decorator for methods not implemented in Python 2.6. | [
"Function",
"decorator",
"for",
"methods",
"not",
"implemented",
"in",
"Python",
"2",
".",
"6",
"."
] | python | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L401-L410 | def difference(self, other):
"""
Returns a new tree, comprising all intervals in self but not
in other.
"""
ivs = set()
for iv in self:
if iv not in other:
ivs.add(iv)
return IntervalTree(ivs) | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"ivs",
"=",
"set",
"(",
")",
"for",
"iv",
"in",
"self",
":",
"if",
"iv",
"not",
"in",
"other",
":",
"ivs",
".",
"add",
"(",
"iv",
")",
"return",
"IntervalTree",
"(",
"ivs",
")"
] | Returns a new tree, comprising all intervals in self but not
in other. | [
"Returns",
"a",
"new",
"tree",
"comprising",
"all",
"intervals",
"in",
"self",
"but",
"not",
"in",
"other",
"."
] | python | train |
mosdef-hub/mbuild | mbuild/compound.py | https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1537-L1648 | def _energy_minimize_openbabel(self, tmp_dir, steps=1000, algorithm='cg',
forcefield='UFF'):
"""Perform an energy minimization on a Compound
Utilizes Open Babel (http://openbabel.org/docs/dev/) to perform an
energy minimization/geometry optimization on a Compo... | [
"def",
"_energy_minimize_openbabel",
"(",
"self",
",",
"tmp_dir",
",",
"steps",
"=",
"1000",
",",
"algorithm",
"=",
"'cg'",
",",
"forcefield",
"=",
"'UFF'",
")",
":",
"openbabel",
"=",
"import_",
"(",
"'openbabel'",
")",
"for",
"particle",
"in",
"self",
".... | Perform an energy minimization on a Compound
Utilizes Open Babel (http://openbabel.org/docs/dev/) to perform an
energy minimization/geometry optimization on a Compound by applying
a generic force field.
This function is primarily intended to be used on smaller components,
with ... | [
"Perform",
"an",
"energy",
"minimization",
"on",
"a",
"Compound"
] | python | train |
saltstack/salt | salt/modules/vsphere.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L8197-L8285 | def _create_disks(service_instance, disks, scsi_controllers=None, parent=None):
'''
Returns a list of disk specs representing the disks to be created for a
virtual machine
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
disks
List of... | [
"def",
"_create_disks",
"(",
"service_instance",
",",
"disks",
",",
"scsi_controllers",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"disk_specs",
"=",
"[",
"]",
"keys",
"=",
"range",
"(",
"-",
"2000",
",",
"-",
"2050",
",",
"-",
"1",
")",
"if"... | Returns a list of disk specs representing the disks to be created for a
virtual machine
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
disks
List of disks with properties
scsi_controllers
List of SCSI controllers
parent
... | [
"Returns",
"a",
"list",
"of",
"disk",
"specs",
"representing",
"the",
"disks",
"to",
"be",
"created",
"for",
"a",
"virtual",
"machine"
] | python | train |
koalalorenzo/python-digitalocean | digitalocean/Droplet.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L595-L604 | def get_action(self, action_id):
"""Returns a specific Action by its ID.
Args:
action_id (int): id of action
"""
return Action.get_object(
api_token=self.token,
action_id=action_id
) | [
"def",
"get_action",
"(",
"self",
",",
"action_id",
")",
":",
"return",
"Action",
".",
"get_object",
"(",
"api_token",
"=",
"self",
".",
"token",
",",
"action_id",
"=",
"action_id",
")"
] | Returns a specific Action by its ID.
Args:
action_id (int): id of action | [
"Returns",
"a",
"specific",
"Action",
"by",
"its",
"ID",
"."
] | python | valid |
astrorafael/twisted-mqtt | mqtt/pdu.py | https://github.com/astrorafael/twisted-mqtt/blob/5b322f7c2b82a502b1e1b70703ae45f1f668d07d/mqtt/pdu.py#L251-L289 | def decode(self, packet):
'''
Decode a CONNECT control packet.
'''
self.encoded = packet
# Strip the fixed header plus variable length field
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
# Var... | [
"def",
"decode",
"(",
"self",
",",
"packet",
")",
":",
"self",
".",
"encoded",
"=",
"packet",
"# Strip the fixed header plus variable length field",
"lenLen",
"=",
"1",
"while",
"packet",
"[",
"lenLen",
"]",
"&",
"0x80",
":",
"lenLen",
"+=",
"1",
"packet_remai... | Decode a CONNECT control packet. | [
"Decode",
"a",
"CONNECT",
"control",
"packet",
"."
] | python | test |
DAI-Lab/Copulas | copulas/bivariate/base.py | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/base.py#L352-L364 | def load(cls, copula_path):
"""Create a new instance from a file.
Args:
copula_path: `str` file with the serialized copula.
Returns:
Bivariate: Instance with the parameters stored in the file.
"""
with open(copula_path) as f:
copula_dict = js... | [
"def",
"load",
"(",
"cls",
",",
"copula_path",
")",
":",
"with",
"open",
"(",
"copula_path",
")",
"as",
"f",
":",
"copula_dict",
"=",
"json",
".",
"load",
"(",
"f",
")",
"return",
"cls",
".",
"from_dict",
"(",
"copula_dict",
")"
] | Create a new instance from a file.
Args:
copula_path: `str` file with the serialized copula.
Returns:
Bivariate: Instance with the parameters stored in the file. | [
"Create",
"a",
"new",
"instance",
"from",
"a",
"file",
"."
] | python | train |
numenta/nupic | examples/opf/experiments/classification/makeDatasets.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/experiments/classification/makeDatasets.py#L36-L79 | def _generateCategory(filename="simple.csv", numSequences=2, elementsPerSeq=1,
numRepeats=10, resets=False):
""" Generate a simple dataset. This contains a bunch of non-overlapping
sequences.
Parameters:
----------------------------------------------------
filename: name of the ... | [
"def",
"_generateCategory",
"(",
"filename",
"=",
"\"simple.csv\"",
",",
"numSequences",
"=",
"2",
",",
"elementsPerSeq",
"=",
"1",
",",
"numRepeats",
"=",
"10",
",",
"resets",
"=",
"False",
")",
":",
"# Create the output file",
"scriptDir",
"=",
"os",
".",
... | Generate a simple dataset. This contains a bunch of non-overlapping
sequences.
Parameters:
----------------------------------------------------
filename: name of the file to produce, including extension. It will
be created in a 'datasets' sub-directory within the
d... | [
"Generate",
"a",
"simple",
"dataset",
".",
"This",
"contains",
"a",
"bunch",
"of",
"non",
"-",
"overlapping",
"sequences",
".",
"Parameters",
":",
"----------------------------------------------------",
"filename",
":",
"name",
"of",
"the",
"file",
"to",
"produce",
... | python | valid |
tensorflow/tensor2tensor | tensor2tensor/utils/metrics.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics.py#L417-L432 | def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None):
"""Calculate softmax cross entropy given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels a... | [
"def",
"softmax_cross_entropy_one_hot",
"(",
"logits",
",",
"labels",
",",
"weights_fn",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"softmax_cross_entropy_one_hot\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"del... | Calculate softmax cross entropy given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
cross-entropy (scalar), weight... | [
"Calculate",
"softmax",
"cross",
"entropy",
"given",
"one",
"-",
"hot",
"labels",
"and",
"logits",
"."
] | python | train |
inveniosoftware/invenio-files-rest | invenio_files_rest/models.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L803-L815 | def update_contents(self, stream, seek=0, size=None, chunk_size=None,
progress_callback=None, **kwargs):
"""Save contents of stream to this file.
:param obj: ObjectVersion instance from where this file is accessed
from.
:param stream: File-like stream.
... | [
"def",
"update_contents",
"(",
"self",
",",
"stream",
",",
"seek",
"=",
"0",
",",
"size",
"=",
"None",
",",
"chunk_size",
"=",
"None",
",",
"progress_callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"checksum",
"=",
"None",
"re... | Save contents of stream to this file.
:param obj: ObjectVersion instance from where this file is accessed
from.
:param stream: File-like stream. | [
"Save",
"contents",
"of",
"stream",
"to",
"this",
"file",
"."
] | python | train |
wdbm/scalar | scalar/__init__.py | https://github.com/wdbm/scalar/blob/c4d70e778a6151b95aad721ca2d3a8bfa38126da/scalar/__init__.py#L71-L101 | def setup(path_config="~/.config/scalar/config.yaml", configuration_name=None):
"""
Load a configuration from a default or specified configuration file, accessing a default or
specified configuration name.
"""
global config
global client
global token
global room
# config file
pat... | [
"def",
"setup",
"(",
"path_config",
"=",
"\"~/.config/scalar/config.yaml\"",
",",
"configuration_name",
"=",
"None",
")",
":",
"global",
"config",
"global",
"client",
"global",
"token",
"global",
"room",
"# config file",
"path_config",
"=",
"Path",
"(",
"path_config... | Load a configuration from a default or specified configuration file, accessing a default or
specified configuration name. | [
"Load",
"a",
"configuration",
"from",
"a",
"default",
"or",
"specified",
"configuration",
"file",
"accessing",
"a",
"default",
"or",
"specified",
"configuration",
"name",
"."
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/flow/conversion.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/conversion.py#L220-L229 | def convert(self):
"""
Performs the actual conversion.
:return: None if successful, otherwise errors message
:rtype: str
"""
cname = str(self.config["wrapper"])
self._output = classes.from_commandline(self._input, classname=cname)
return None | [
"def",
"convert",
"(",
"self",
")",
":",
"cname",
"=",
"str",
"(",
"self",
".",
"config",
"[",
"\"wrapper\"",
"]",
")",
"self",
".",
"_output",
"=",
"classes",
".",
"from_commandline",
"(",
"self",
".",
"_input",
",",
"classname",
"=",
"cname",
")",
... | Performs the actual conversion.
:return: None if successful, otherwise errors message
:rtype: str | [
"Performs",
"the",
"actual",
"conversion",
"."
] | python | train |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L149-L217 | def trace_incoming_web_request(
self,
webapp_info,
url,
method,
headers=None,
remote_address=None,
str_tag=None,
byte_tag=None):
'''Create a tracer for an incoming webrequest.
:param WebapplicationInfoHandle... | [
"def",
"trace_incoming_web_request",
"(",
"self",
",",
"webapp_info",
",",
"url",
",",
"method",
",",
"headers",
"=",
"None",
",",
"remote_address",
"=",
"None",
",",
"str_tag",
"=",
"None",
",",
"byte_tag",
"=",
"None",
")",
":",
"assert",
"isinstance",
"... | Create a tracer for an incoming webrequest.
:param WebapplicationInfoHandle webapp_info: Web application
information (see :meth:`create_web_application_info`).
:param str url: The requested URL (including scheme, hostname/port,
path and query).
:param str method: The HTT... | [
"Create",
"a",
"tracer",
"for",
"an",
"incoming",
"webrequest",
"."
] | python | train |
uw-it-aca/uw-restclients | restclients/mailman/course_list.py | https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/mailman/course_list.py#L15-L26 | def get_course_list_name(curriculum_abbr, course_number, section_id,
quarter, year):
"""
Return the list address of UW course email list
"""
return "%s%s%s_%s%s" % (
_get_list_name_curr_abbr(curriculum_abbr),
course_number,
section_id.lower(),
qua... | [
"def",
"get_course_list_name",
"(",
"curriculum_abbr",
",",
"course_number",
",",
"section_id",
",",
"quarter",
",",
"year",
")",
":",
"return",
"\"%s%s%s_%s%s\"",
"%",
"(",
"_get_list_name_curr_abbr",
"(",
"curriculum_abbr",
")",
",",
"course_number",
",",
"section... | Return the list address of UW course email list | [
"Return",
"the",
"list",
"address",
"of",
"UW",
"course",
"email",
"list"
] | python | train |
square/pylink | pylink/jlink.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4197-L4210 | def trace_stop(self):
"""Stops collecting trace data.
Args:
self (JLink): the ``JLink`` instance.
Returns:
``None``
"""
cmd = enums.JLinkTraceCommand.STOP
res = self._dll.JLINKARM_TRACE_Control(cmd, 0)
if (res == 1):
raise errors.... | [
"def",
"trace_stop",
"(",
"self",
")",
":",
"cmd",
"=",
"enums",
".",
"JLinkTraceCommand",
".",
"STOP",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_TRACE_Control",
"(",
"cmd",
",",
"0",
")",
"if",
"(",
"res",
"==",
"1",
")",
":",
"raise",
"errors... | Stops collecting trace data.
Args:
self (JLink): the ``JLink`` instance.
Returns:
``None`` | [
"Stops",
"collecting",
"trace",
"data",
"."
] | python | train |
eqcorrscan/EQcorrscan | setup.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/setup.py#L181-L186 | def export_symbols(*path):
"""
Required for windows systems - functions defined in libutils.def.
"""
lines = open(os.path.join(*path), 'r').readlines()[2:]
return [s.strip() for s in lines if s.strip() != ''] | [
"def",
"export_symbols",
"(",
"*",
"path",
")",
":",
"lines",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"*",
"path",
")",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"[",
"2",
":",
"]",
"return",
"[",
"s",
".",
"strip",
"(",
")"... | Required for windows systems - functions defined in libutils.def. | [
"Required",
"for",
"windows",
"systems",
"-",
"functions",
"defined",
"in",
"libutils",
".",
"def",
"."
] | python | train |
draperunner/fjlc | fjlc/classifier/classifier.py | https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/classifier/classifier.py#L26-L40 | def classify(self, tweet):
"""
Classifies the tweet into one of three classes (negative, neutral or positive) depending on the sentiment value
of the tweet and the thresholds specified in the classifier_options
:param tweet: String tweet to classify
:return: Sentiment classifica... | [
"def",
"classify",
"(",
"self",
",",
"tweet",
")",
":",
"sentiment_value",
"=",
"self",
".",
"calculate_sentiment",
"(",
"tweet",
")",
"return",
"Classification",
".",
"classify_from_thresholds",
"(",
"sentiment_value",
",",
"classifier_options",
".",
"get_variable"... | Classifies the tweet into one of three classes (negative, neutral or positive) depending on the sentiment value
of the tweet and the thresholds specified in the classifier_options
:param tweet: String tweet to classify
:return: Sentiment classification (negative, neutral or positive) | [
"Classifies",
"the",
"tweet",
"into",
"one",
"of",
"three",
"classes",
"(",
"negative",
"neutral",
"or",
"positive",
")",
"depending",
"on",
"the",
"sentiment",
"value",
"of",
"the",
"tweet",
"and",
"the",
"thresholds",
"specified",
"in",
"the",
"classifier_op... | python | train |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2413-L2422 | def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
... | [
"def",
"redirect",
"(",
"url",
",",
"code",
"=",
"None",
")",
":",
"if",
"not",
"code",
":",
"code",
"=",
"303",
"if",
"request",
".",
"get",
"(",
"'SERVER_PROTOCOL'",
")",
"==",
"\"HTTP/1.1\"",
"else",
"302",
"res",
"=",
"response",
".",
"copy",
"("... | Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. | [
"Aborts",
"execution",
"and",
"causes",
"a",
"303",
"or",
"302",
"redirect",
"depending",
"on",
"the",
"HTTP",
"protocol",
"version",
"."
] | python | train |
jf-parent/brome | brome/core/proxy_driver.py | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/core/proxy_driver.py#L1078-L1117 | def assert_present(self, selector, testid=None, **kwargs):
"""Assert that the element is present in the dom
Args:
selector (str): the selector used to find the element
test_id (str): the test_id or a str
Kwargs:
wait_until_present (bool)
Returns:
... | [
"def",
"assert_present",
"(",
"self",
",",
"selector",
",",
"testid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"info_log",
"(",
"\"Assert present selector(%s) testid(%s)\"",
"%",
"(",
"selector",
",",
"testid",
")",
")",
"wait_until_present... | Assert that the element is present in the dom
Args:
selector (str): the selector used to find the element
test_id (str): the test_id or a str
Kwargs:
wait_until_present (bool)
Returns:
bool: True is the assertion succeed; False otherwise. | [
"Assert",
"that",
"the",
"element",
"is",
"present",
"in",
"the",
"dom"
] | python | train |
cltk/cltk | cltk/inflection/old_norse/nouns.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/nouns.py#L55-L66 | def get_representative_cases(self):
"""
>>> armr = OldNorseNoun("armr", decl_utils.Gender.masculine)
>>> armr.set_representative_cases("armr", "arms", "armar")
>>> armr.get_representative_cases()
('armr', 'arms', 'armar')
:return: nominative singular, genetive singular, ... | [
"def",
"get_representative_cases",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"get_declined",
"(",
"decl_utils",
".",
"Case",
".",
"nominative",
",",
"decl_utils",
".",
"Number",
".",
"singular",
")",
",",
"self",
".",
"get_declined",
"(",
"decl_util... | >>> armr = OldNorseNoun("armr", decl_utils.Gender.masculine)
>>> armr.set_representative_cases("armr", "arms", "armar")
>>> armr.get_representative_cases()
('armr', 'arms', 'armar')
:return: nominative singular, genetive singular, nominative plural | [
">>>",
"armr",
"=",
"OldNorseNoun",
"(",
"armr",
"decl_utils",
".",
"Gender",
".",
"masculine",
")",
">>>",
"armr",
".",
"set_representative_cases",
"(",
"armr",
"arms",
"armar",
")",
">>>",
"armr",
".",
"get_representative_cases",
"()",
"(",
"armr",
"arms",
... | python | train |
sentinelsat/sentinelsat | sentinelsat/sentinel.py | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L889-L940 | def geojson_to_wkt(geojson_obj, feature_number=0, decimals=4):
"""Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries.
In case of FeatureCollection, only one of the features is used (the first by default).
3D points are converted to 2D.
Parameters
----------
g... | [
"def",
"geojson_to_wkt",
"(",
"geojson_obj",
",",
"feature_number",
"=",
"0",
",",
"decimals",
"=",
"4",
")",
":",
"if",
"'coordinates'",
"in",
"geojson_obj",
":",
"geometry",
"=",
"geojson_obj",
"elif",
"'geometry'",
"in",
"geojson_obj",
":",
"geometry",
"=",... | Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries.
In case of FeatureCollection, only one of the features is used (the first by default).
3D points are converted to 2D.
Parameters
----------
geojson_obj : dict
a GeoJSON object
feature_number : int, o... | [
"Convert",
"a",
"GeoJSON",
"object",
"to",
"Well",
"-",
"Known",
"Text",
".",
"Intended",
"for",
"use",
"with",
"OpenSearch",
"queries",
"."
] | python | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L70-L88 | async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, x.BlobType)
data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_bl... | [
"async",
"def",
"dump_blob",
"(",
"elem",
",",
"elem_type",
"=",
"None",
")",
":",
"elem_is_blob",
"=",
"isinstance",
"(",
"elem",
",",
"x",
".",
"BlobType",
")",
"data",
"=",
"getattr",
"(",
"elem",
",",
"x",
".",
"BlobType",
".",
"DATA_ATTR",
")",
... | Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return: | [
"Dumps",
"blob",
"message",
".",
"Supports",
"both",
"blob",
"and",
"raw",
"value",
"."
] | python | train |
quantopian/pyfolio | pyfolio/perf_attrib.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/perf_attrib.py#L620-L647 | def _stack_positions(positions, pos_in_dollars=True):
"""
Convert positions to percentages if necessary, and change them
to long format.
Parameters
----------
positions: pd.DataFrame
Daily holdings (in dollars or percentages), indexed by date.
Will be converted to percentages if... | [
"def",
"_stack_positions",
"(",
"positions",
",",
"pos_in_dollars",
"=",
"True",
")",
":",
"if",
"pos_in_dollars",
":",
"# convert holdings to percentages",
"positions",
"=",
"get_percent_alloc",
"(",
"positions",
")",
"# remove cash after normalizing positions",
"positions... | Convert positions to percentages if necessary, and change them
to long format.
Parameters
----------
positions: pd.DataFrame
Daily holdings (in dollars or percentages), indexed by date.
Will be converted to percentages if positions are in dollars.
Short positions show up as cash... | [
"Convert",
"positions",
"to",
"percentages",
"if",
"necessary",
"and",
"change",
"them",
"to",
"long",
"format",
"."
] | python | valid |
spyder-ide/spyder | spyder/widgets/calltip.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L105-L108 | def leaveEvent(self, event):
"""Override Qt method to hide the tooltip on leave."""
super(ToolTipWidget, self).leaveEvent(event)
self.hide() | [
"def",
"leaveEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"ToolTipWidget",
",",
"self",
")",
".",
"leaveEvent",
"(",
"event",
")",
"self",
".",
"hide",
"(",
")"
] | Override Qt method to hide the tooltip on leave. | [
"Override",
"Qt",
"method",
"to",
"hide",
"the",
"tooltip",
"on",
"leave",
"."
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L511-L537 | def bodvar(body, item, dim):
"""
Deprecated: This routine has been superseded by :func:`bodvcd` and
:func:`bodvrd`. This routine is supported for purposes of backward
compatibility only.
Return the values of some item for any body in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_d... | [
"def",
"bodvar",
"(",
"body",
",",
"item",
",",
"dim",
")",
":",
"body",
"=",
"ctypes",
".",
"c_int",
"(",
"body",
")",
"dim",
"=",
"ctypes",
".",
"c_int",
"(",
"dim",
")",
"item",
"=",
"stypes",
".",
"stringToCharP",
"(",
"item",
")",
"values",
... | Deprecated: This routine has been superseded by :func:`bodvcd` and
:func:`bodvrd`. This routine is supported for purposes of backward
compatibility only.
Return the values of some item for any body in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvar_c.html
:param bo... | [
"Deprecated",
":",
"This",
"routine",
"has",
"been",
"superseded",
"by",
":",
"func",
":",
"bodvcd",
"and",
":",
"func",
":",
"bodvrd",
".",
"This",
"routine",
"is",
"supported",
"for",
"purposes",
"of",
"backward",
"compatibility",
"only",
"."
] | python | train |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L312-L345 | def on_service_departure(self, svc_ref):
"""
Called when a service has been unregistered from the framework
:param svc_ref: A service reference
"""
with self._lock:
if svc_ref is self.reference:
# Forget about the service
self._value.u... | [
"def",
"on_service_departure",
"(",
"self",
",",
"svc_ref",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"svc_ref",
"is",
"self",
".",
"reference",
":",
"# Forget about the service",
"self",
".",
"_value",
".",
"unset_service",
"(",
")",
"# Clear the ref... | Called when a service has been unregistered from the framework
:param svc_ref: A service reference | [
"Called",
"when",
"a",
"service",
"has",
"been",
"unregistered",
"from",
"the",
"framework"
] | python | train |
pyca/pyopenssl | src/OpenSSL/SSL.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/SSL.py#L812-L859 | def set_default_verify_paths(self):
"""
Specify that the platform provided CA certificates are to be used for
verification purposes. This method has some caveats related to the
binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
* macOS will only load certi... | [
"def",
"set_default_verify_paths",
"(",
"self",
")",
":",
"# SSL_CTX_set_default_verify_paths will attempt to load certs from",
"# both a cafile and capath that are set at compile time. However,",
"# it will first check environment variables and, if present, load",
"# those paths instead",
"set_... | Specify that the platform provided CA certificates are to be used for
verification purposes. This method has some caveats related to the
binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
* macOS will only load certificates using this method if the user has
th... | [
"Specify",
"that",
"the",
"platform",
"provided",
"CA",
"certificates",
"are",
"to",
"be",
"used",
"for",
"verification",
"purposes",
".",
"This",
"method",
"has",
"some",
"caveats",
"related",
"to",
"the",
"binary",
"wheels",
"that",
"cryptography",
"(",
"pyO... | python | test |
ANTsX/ANTsPy | ants/utils/iMath.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/iMath.py#L70-L107 | def iMath(image, operation, *args):
"""
Perform various (often mathematical) operations on the input image/s.
Additional parameters should be specific for each operation.
See the the full iMath in ANTs, on which this function is based.
ANTsR function: `iMath`
Arguments
---------
image ... | [
"def",
"iMath",
"(",
"image",
",",
"operation",
",",
"*",
"args",
")",
":",
"if",
"operation",
"not",
"in",
"_iMathOps",
":",
"raise",
"ValueError",
"(",
"'Operation not recognized'",
")",
"imagedim",
"=",
"image",
".",
"dimension",
"outimage",
"=",
"image",... | Perform various (often mathematical) operations on the input image/s.
Additional parameters should be specific for each operation.
See the the full iMath in ANTs, on which this function is based.
ANTsR function: `iMath`
Arguments
---------
image : ANTsImage
input object, usually antsIm... | [
"Perform",
"various",
"(",
"often",
"mathematical",
")",
"operations",
"on",
"the",
"input",
"image",
"/",
"s",
".",
"Additional",
"parameters",
"should",
"be",
"specific",
"for",
"each",
"operation",
".",
"See",
"the",
"the",
"full",
"iMath",
"in",
"ANTs",
... | python | train |
cloud-custodian/cloud-custodian | c7n/policy.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L118-L123 | def resource_types(self):
"""resource types used by the collection."""
rtypes = set()
for p in self.policies:
rtypes.add(p.resource_type)
return rtypes | [
"def",
"resource_types",
"(",
"self",
")",
":",
"rtypes",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"self",
".",
"policies",
":",
"rtypes",
".",
"add",
"(",
"p",
".",
"resource_type",
")",
"return",
"rtypes"
] | resource types used by the collection. | [
"resource",
"types",
"used",
"by",
"the",
"collection",
"."
] | python | train |
jquast/wcwidth | setup.py | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L271-L307 | def main():
"""Setup.py entry point."""
import codecs
setuptools.setup(
name='wcwidth',
version='0.1.7',
description=("Measures number of Terminal column cells "
"of wide-character codes"),
long_description=codecs.open(
os.path.join(HERE, 'REA... | [
"def",
"main",
"(",
")",
":",
"import",
"codecs",
"setuptools",
".",
"setup",
"(",
"name",
"=",
"'wcwidth'",
",",
"version",
"=",
"'0.1.7'",
",",
"description",
"=",
"(",
"\"Measures number of Terminal column cells \"",
"\"of wide-character codes\"",
")",
",",
"lo... | Setup.py entry point. | [
"Setup",
".",
"py",
"entry",
"point",
"."
] | python | train |
cfobel/si-prefix | si_prefix/__init__.py | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L109-L125 | def prefix(expof10):
'''
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY".
'''
prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2
si_level = expof10 // 3
if abs(si_level) > ... | [
"def",
"prefix",
"(",
"expof10",
")",
":",
"prefix_levels",
"=",
"(",
"len",
"(",
"SI_PREFIX_UNITS",
")",
"-",
"1",
")",
"//",
"2",
"si_level",
"=",
"expof10",
"//",
"3",
"if",
"abs",
"(",
"si_level",
")",
">",
"prefix_levels",
":",
"raise",
"ValueErro... | Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY". | [
"Args",
":"
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/misc.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L505-L519 | def path_type(path, target):
"""
Determine if given path is file, directory, or other. Compare with target to see if it's the type we wanted.
:param str path: Path
:param str target: Target type wanted
:return bool: Path is what it claims to be (True) or mismatch (False)
"""
if os.path.isfi... | [
"def",
"path_type",
"(",
"path",
",",
"target",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"target",
"==",
"\"file\"",
":",
"return",
"True",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"and",
"target"... | Determine if given path is file, directory, or other. Compare with target to see if it's the type we wanted.
:param str path: Path
:param str target: Target type wanted
:return bool: Path is what it claims to be (True) or mismatch (False) | [
"Determine",
"if",
"given",
"path",
"is",
"file",
"directory",
"or",
"other",
".",
"Compare",
"with",
"target",
"to",
"see",
"if",
"it",
"s",
"the",
"type",
"we",
"wanted",
"."
] | python | train |
dmbee/seglearn | seglearn/pipe.py | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/pipe.py#L310-L325 | def decision_function(self, X):
"""
Apply transforms, and decision_function of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
... | [
"def",
"decision_function",
"(",
"self",
",",
"X",
")",
":",
"Xt",
",",
"_",
",",
"_",
"=",
"self",
".",
"_transform",
"(",
"X",
")",
"return",
"self",
".",
"_final_estimator",
".",
"decision_function",
"(",
"Xt",
")"
] | Apply transforms, and decision_function of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_score : array-like, shape = [n_samples, n_class... | [
"Apply",
"transforms",
"and",
"decision_function",
"of",
"the",
"final",
"estimator"
] | python | train |
bitcraft/PyTMX | pytmx/pytmx.py | https://github.com/bitcraft/PyTMX/blob/3fb9788dd66ecfd0c8fa0e9f38c582337d89e1d9/pytmx/pytmx.py#L196-L213 | def parse_properties(node):
""" Parse a Tiled xml node and return a dict that represents a tiled "property"
:param node: etree element
:return: dict
"""
d = dict()
for child in node.findall('properties'):
for subnode in child.findall('property'):
cls = None
try:
... | [
"def",
"parse_properties",
"(",
"node",
")",
":",
"d",
"=",
"dict",
"(",
")",
"for",
"child",
"in",
"node",
".",
"findall",
"(",
"'properties'",
")",
":",
"for",
"subnode",
"in",
"child",
".",
"findall",
"(",
"'property'",
")",
":",
"cls",
"=",
"None... | Parse a Tiled xml node and return a dict that represents a tiled "property"
:param node: etree element
:return: dict | [
"Parse",
"a",
"Tiled",
"xml",
"node",
"and",
"return",
"a",
"dict",
"that",
"represents",
"a",
"tiled",
"property"
] | python | train |
turicas/rows | rows/plugins/plugin_csv.py | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_csv.py#L139-L201 | def export_to_csv(
table,
filename_or_fobj=None,
encoding="utf-8",
dialect=unicodecsv.excel,
batch_size=100,
callback=None,
*args,
**kwargs
):
"""Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='... | [
"def",
"export_to_csv",
"(",
"table",
",",
"filename_or_fobj",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"dialect",
"=",
"unicodecsv",
".",
"excel",
",",
"batch_size",
"=",
"100",
",",
"callback",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
... | Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='wb')`.
If not filename/fobj is provided, the function returns a string with CSV
contents. | [
"Export",
"a",
"rows",
".",
"Table",
"to",
"a",
"CSV",
"file",
"."
] | python | train |
edx/edx-django-release-util | scripts/update_repos_version.py | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/scripts/update_repos_version.py#L55-L153 | def bump_repos_version(module_name, new_version, local_only):
"""
Changes the pinned version number in the requirements files of all repos
which have the specified Python module as a dependency.
This script assumes that GITHUB_TOKEN is set for GitHub authentication.
"""
# Make the cloning direc... | [
"def",
"bump_repos_version",
"(",
"module_name",
",",
"new_version",
",",
"local_only",
")",
":",
"# Make the cloning directory and change directories into it.",
"tmp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"dir",
"=",
"os",
".",
"getcwd",
"(",
")",
")",
"# Iter... | Changes the pinned version number in the requirements files of all repos
which have the specified Python module as a dependency.
This script assumes that GITHUB_TOKEN is set for GitHub authentication. | [
"Changes",
"the",
"pinned",
"version",
"number",
"in",
"the",
"requirements",
"files",
"of",
"all",
"repos",
"which",
"have",
"the",
"specified",
"Python",
"module",
"as",
"a",
"dependency",
"."
] | python | train |
zerotk/easyfs | zerotk/easyfs/_easyfs.py | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L802-L837 | def MoveDirectory(source_dir, target_dir):
'''
Moves a directory.
:param unicode source_dir:
:param unicode target_dir:
:raises NotImplementedError:
If trying to move anything other than:
Local dir -> local dir
FTP dir -> FTP dir (same host)
'''
if not IsDi... | [
"def",
"MoveDirectory",
"(",
"source_dir",
",",
"target_dir",
")",
":",
"if",
"not",
"IsDir",
"(",
"source_dir",
")",
":",
"from",
".",
"_exceptions",
"import",
"DirectoryNotFoundError",
"raise",
"DirectoryNotFoundError",
"(",
"source_dir",
")",
"if",
"Exists",
... | Moves a directory.
:param unicode source_dir:
:param unicode target_dir:
:raises NotImplementedError:
If trying to move anything other than:
Local dir -> local dir
FTP dir -> FTP dir (same host) | [
"Moves",
"a",
"directory",
"."
] | python | valid |
koalalorenzo/python-digitalocean | digitalocean/Volume.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L74-L108 | def create_from_snapshot(self, *args, **kwargs):
"""
Creates a Block Storage volume
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
name: string - a name for the volume
snapshot_id: string - unique identifier... | [
"def",
"create_from_snapshot",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"get_data",
"(",
"'volumes/'",
",",
"type",
"=",
"POST",
",",
"params",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'... | Creates a Block Storage volume
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
name: string - a name for the volume
snapshot_id: string - unique identifier for the volume snapshot
size_gigabytes: int - size of th... | [
"Creates",
"a",
"Block",
"Storage",
"volume"
] | python | valid |
rjdkmr/do_x3dna | dnaMD/dnaMD/dnaMD.py | https://github.com/rjdkmr/do_x3dna/blob/fe910335eefcada76737f9e7cd6f25036cd32ab6/dnaMD/dnaMD/dnaMD.py#L481-L581 | def parameter_distribution(self, parameter, bp, bins=30, merge=False, merge_method='mean', masked=False):
"""To get the parameter distribution of either a specific base-pair/step or a DNA segment over the MD simulation.
parameters
----------
parameter : str
Name of a base-pa... | [
"def",
"parameter_distribution",
"(",
"self",
",",
"parameter",
",",
"bp",
",",
"bins",
"=",
"30",
",",
"merge",
"=",
"False",
",",
"merge_method",
"=",
"'mean'",
",",
"masked",
"=",
"False",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"bp",
",",
... | To get the parameter distribution of either a specific base-pair/step or a DNA segment over the MD simulation.
parameters
----------
parameter : str
Name of a base-pair or base-step or helical parameter
For details about accepted keywords, see ``parameter`` in the method... | [
"To",
"get",
"the",
"parameter",
"distribution",
"of",
"either",
"a",
"specific",
"base",
"-",
"pair",
"/",
"step",
"or",
"a",
"DNA",
"segment",
"over",
"the",
"MD",
"simulation",
"."
] | python | train |
pypa/setuptools | setuptools/monkey.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/monkey.py#L132-L179 | def patch_for_msvc_specialized_compiler():
"""
Patch functions in distutils to use standalone Microsoft Visual C++
compilers.
"""
# import late to avoid circular imports on Python < 3.5
msvc = import_module('setuptools.msvc')
if platform.system() != 'Windows':
# Compilers only avail... | [
"def",
"patch_for_msvc_specialized_compiler",
"(",
")",
":",
"# import late to avoid circular imports on Python < 3.5",
"msvc",
"=",
"import_module",
"(",
"'setuptools.msvc'",
")",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Windows'",
":",
"# Compilers only availabl... | Patch functions in distutils to use standalone Microsoft Visual C++
compilers. | [
"Patch",
"functions",
"in",
"distutils",
"to",
"use",
"standalone",
"Microsoft",
"Visual",
"C",
"++",
"compilers",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L5702-L5705 | def resolveURI(self, URI):
"""Do a complete resolution lookup of an URI """
ret = libxml2mod.xmlACatalogResolveURI(self._o, URI)
return ret | [
"def",
"resolveURI",
"(",
"self",
",",
"URI",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlACatalogResolveURI",
"(",
"self",
".",
"_o",
",",
"URI",
")",
"return",
"ret"
] | Do a complete resolution lookup of an URI | [
"Do",
"a",
"complete",
"resolution",
"lookup",
"of",
"an",
"URI"
] | python | train |
jic-dtool/dtoolcore | dtoolcore/storagebroker.py | https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L273-L278 | def put_overlay(self, overlay_name, overlay):
"""Store the overlay."""
logger.debug("Putting overlay: {}".format(overlay_name))
key = self.get_overlay_key(overlay_name)
text = json.dumps(overlay, indent=2)
self.put_text(key, text) | [
"def",
"put_overlay",
"(",
"self",
",",
"overlay_name",
",",
"overlay",
")",
":",
"logger",
".",
"debug",
"(",
"\"Putting overlay: {}\"",
".",
"format",
"(",
"overlay_name",
")",
")",
"key",
"=",
"self",
".",
"get_overlay_key",
"(",
"overlay_name",
")",
"tex... | Store the overlay. | [
"Store",
"the",
"overlay",
"."
] | python | train |
gholt/swiftly | swiftly/cli/get.py | https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/get.py#L79-L161 | def cli_get_account_listing(context):
"""
Performs a GET on the account as a listing request.
See :py:mod:`swiftly.cli.get` for context usage information.
See :py:class:`CLIGet` for more information.
"""
limit = context.query.get('limit')
delimiter = context.query.get('delimiter')
pref... | [
"def",
"cli_get_account_listing",
"(",
"context",
")",
":",
"limit",
"=",
"context",
".",
"query",
".",
"get",
"(",
"'limit'",
")",
"delimiter",
"=",
"context",
".",
"query",
".",
"get",
"(",
"'delimiter'",
")",
"prefix",
"=",
"context",
".",
"query",
".... | Performs a GET on the account as a listing request.
See :py:mod:`swiftly.cli.get` for context usage information.
See :py:class:`CLIGet` for more information. | [
"Performs",
"a",
"GET",
"on",
"the",
"account",
"as",
"a",
"listing",
"request",
"."
] | python | test |
cloudify-cosmo/repex | repex.py | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L328-L340 | def _match_tags(repex_tags, path_tags):
"""Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match.
"""
if 'any' ... | [
"def",
"_match_tags",
"(",
"repex_tags",
",",
"path_tags",
")",
":",
"if",
"'any'",
"in",
"repex_tags",
"or",
"(",
"not",
"repex_tags",
"and",
"not",
"path_tags",
")",
":",
"return",
"True",
"elif",
"set",
"(",
"repex_tags",
")",
"&",
"set",
"(",
"path_t... | Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match. | [
"Check",
"for",
"matching",
"tags",
"between",
"what",
"the",
"user",
"provided",
"and",
"the",
"tags",
"set",
"in",
"the",
"config",
"."
] | python | train |
polyaxon/polyaxon | polyaxon/pipelines/dags.py | https://github.com/polyaxon/polyaxon/blob/e1724f0756b1a42f9e7aa08a976584a84ef7f016/polyaxon/pipelines/dags.py#L50-L77 | def sort_topologically(dag):
"""Sort the dag breath first topologically.
Only the nodes inside the dag are returned, i.e. the nodes that are also keys.
Returns:
a topological ordering of the DAG.
Raises:
an error if this is not possible (graph is not valid).
"""
dag = copy.de... | [
"def",
"sort_topologically",
"(",
"dag",
")",
":",
"dag",
"=",
"copy",
".",
"deepcopy",
"(",
"dag",
")",
"sorted_nodes",
"=",
"[",
"]",
"independent_nodes",
"=",
"deque",
"(",
"get_independent_nodes",
"(",
"dag",
")",
")",
"while",
"independent_nodes",
":",
... | Sort the dag breath first topologically.
Only the nodes inside the dag are returned, i.e. the nodes that are also keys.
Returns:
a topological ordering of the DAG.
Raises:
an error if this is not possible (graph is not valid). | [
"Sort",
"the",
"dag",
"breath",
"first",
"topologically",
"."
] | python | train |
numenta/nupic | src/nupic/database/connection.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L373-L409 | def _trackInstanceAndCheckForConcurrencyViolation(self):
""" Check for concurrency violation and add self to
_clsOutstandingInstances.
ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is
incremented
"""
global g_max_concurrency, g_max_concurrency_raise_exception
assert g_max_c... | [
"def",
"_trackInstanceAndCheckForConcurrencyViolation",
"(",
"self",
")",
":",
"global",
"g_max_concurrency",
",",
"g_max_concurrency_raise_exception",
"assert",
"g_max_concurrency",
"is",
"not",
"None",
"assert",
"self",
"not",
"in",
"self",
".",
"_clsOutstandingInstances"... | Check for concurrency violation and add self to
_clsOutstandingInstances.
ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is
incremented | [
"Check",
"for",
"concurrency",
"violation",
"and",
"add",
"self",
"to",
"_clsOutstandingInstances",
"."
] | python | valid |
clusterpoint/python-client-api | pycps/converters.py | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/converters.py#L178-L204 | def to_raw_xml(source):
""" Convert various representations of an XML structure to a normal XML string.
Args:
source -- The source object to be converted - ET.Element, dict or string.
Returns:
A rew xml string matching the source object.
>>> to_raw_xml("<content/>")
... | [
"def",
"to_raw_xml",
"(",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"basestring",
")",
":",
"return",
"source",
"elif",
"hasattr",
"(",
"source",
",",
"'getiterator'",
")",
":",
"# Element or ElementTree.",
"return",
"ET",
".",
"tostring",
... | Convert various representations of an XML structure to a normal XML string.
Args:
source -- The source object to be converted - ET.Element, dict or string.
Returns:
A rew xml string matching the source object.
>>> to_raw_xml("<content/>")
'<content/>'
>>> to_raw_x... | [
"Convert",
"various",
"representations",
"of",
"an",
"XML",
"structure",
"to",
"a",
"normal",
"XML",
"string",
"."
] | python | train |
monarch-initiative/dipper | dipper/sources/UDP.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/UDP.py#L770-L821 | def _get_rs_id(variant, rs_map, variant_type):
"""
Given a variant dict, return unambiguous RS ID
TODO
Some sequence alterations appear to have mappings to dbsnp's notation
for example,
reference allele: TTTTTTTTTTTTTT
variant allele: TTTTTTTTTTTTTTT
Is ... | [
"def",
"_get_rs_id",
"(",
"variant",
",",
"rs_map",
",",
"variant_type",
")",
":",
"rs_id",
"=",
"None",
"if",
"variant_type",
"==",
"'snp'",
":",
"variant_key",
"=",
"\"{0}-{1}\"",
".",
"format",
"(",
"variant",
"[",
"'chromosome'",
"]",
",",
"variant",
"... | Given a variant dict, return unambiguous RS ID
TODO
Some sequence alterations appear to have mappings to dbsnp's notation
for example,
reference allele: TTTTTTTTTTTTTT
variant allele: TTTTTTTTTTTTTTT
Is theoretically the same as -/T, we should clarify with UDP and then ... | [
"Given",
"a",
"variant",
"dict",
"return",
"unambiguous",
"RS",
"ID",
"TODO",
"Some",
"sequence",
"alterations",
"appear",
"to",
"have",
"mappings",
"to",
"dbsnp",
"s",
"notation",
"for",
"example",
"reference",
"allele",
":",
"TTTTTTTTTTTTTT",
"variant",
"allel... | python | train |
bitshares/uptick | uptick/wallet.py | https://github.com/bitshares/uptick/blob/66c102200fdbf96cef4fd55cc69d00e690f62001/uptick/wallet.py#L158-L201 | def importaccount(ctx, account, role):
""" Import an account using an account password
"""
from bitsharesbase.account import PasswordKey
password = click.prompt("Account Passphrase", hide_input=True)
account = Account(account, bitshares_instance=ctx.bitshares)
imported = False
if role == "... | [
"def",
"importaccount",
"(",
"ctx",
",",
"account",
",",
"role",
")",
":",
"from",
"bitsharesbase",
".",
"account",
"import",
"PasswordKey",
"password",
"=",
"click",
".",
"prompt",
"(",
"\"Account Passphrase\"",
",",
"hide_input",
"=",
"True",
")",
"account",... | Import an account using an account password | [
"Import",
"an",
"account",
"using",
"an",
"account",
"password"
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L960-L967 | def _assertField(self, name):
"""Raise AttributeError when PacketHistory has no field with the given
name.
"""
if name not in self._names:
msg = 'PacketHistory "%s" has no field "%s"'
values = self._defn.name, name
raise AttributeError(msg % values) | [
"def",
"_assertField",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_names",
":",
"msg",
"=",
"'PacketHistory \"%s\" has no field \"%s\"'",
"values",
"=",
"self",
".",
"_defn",
".",
"name",
",",
"name",
"raise",
"AttributeErro... | Raise AttributeError when PacketHistory has no field with the given
name. | [
"Raise",
"AttributeError",
"when",
"PacketHistory",
"has",
"no",
"field",
"with",
"the",
"given",
"name",
"."
] | python | train |
coderholic/pyradio | pyradio/config.py | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/config.py#L383-L401 | def read_playlists(self):
self.playlists = []
self.selected_playlist = -1
files = glob.glob(path.join(self.stations_dir, '*.csv'))
if len(files) == 0:
return 0, -1
else:
for a_file in files:
a_file_name = ''.join(path.basename(a_file).split... | [
"def",
"read_playlists",
"(",
"self",
")",
":",
"self",
".",
"playlists",
"=",
"[",
"]",
"self",
".",
"selected_playlist",
"=",
"-",
"1",
"files",
"=",
"glob",
".",
"glob",
"(",
"path",
".",
"join",
"(",
"self",
".",
"stations_dir",
",",
"'*.csv'",
"... | get already loaded playlist id | [
"get",
"already",
"loaded",
"playlist",
"id"
] | python | train |
saltstack/salt | salt/utils/msazure.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L123-L167 | def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "contain... | [
"def",
"get_blob",
"(",
"storage_conn",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"storage_conn",
":",
"storage_conn",
"=",
"get_storage_conn",
"(",
"opts",
"=",
"kwargs",
")",
"if",
"'container'",
"not",
"in",
"kwargs",
":",
"raise",
... | .. versionadded:: 2015.8.0
Download a blob | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | python | train |
kxgames/vecrec | vecrec/collisions.py | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/collisions.py#L3-L40 | def circle_touching_line(center, radius, start, end):
""" Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: Radius of the c... | [
"def",
"circle_touching_line",
"(",
"center",
",",
"radius",
",",
"start",
",",
"end",
")",
":",
"C",
",",
"R",
"=",
"center",
",",
"radius",
"A",
",",
"B",
"=",
"start",
",",
"end",
"a",
"=",
"(",
"B",
".",
"x",
"-",
"A",
".",
"x",
")",
"**"... | Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: Radius of the circle.
:type radius: float
:param start: The first end... | [
"Return",
"true",
"if",
"the",
"given",
"circle",
"intersects",
"the",
"given",
"segment",
".",
"Note",
"that",
"this",
"checks",
"for",
"intersection",
"with",
"a",
"line",
"segment",
"and",
"not",
"an",
"actual",
"line",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L157-L167 | def _check_model_types(self, models):
""" Check types of passed models for correctness and in case raise exception
:rtype: set
:returns: set of models that are valid for the class"""
if not hasattr(models, "__iter__"):
models = {models}
if not all([isinstance(model, ... | [
"def",
"_check_model_types",
"(",
"self",
",",
"models",
")",
":",
"if",
"not",
"hasattr",
"(",
"models",
",",
"\"__iter__\"",
")",
":",
"models",
"=",
"{",
"models",
"}",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"model",
",",
"(",
"AbstractSta... | Check types of passed models for correctness and in case raise exception
:rtype: set
:returns: set of models that are valid for the class | [
"Check",
"types",
"of",
"passed",
"models",
"for",
"correctness",
"and",
"in",
"case",
"raise",
"exception"
] | python | train |
cbclab/MOT | mot/library_functions/__init__.py | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/library_functions/__init__.py#L498-L504 | def get_kernel_data(self):
"""Get the kernel data needed for this optimization routine to work."""
return {
'nmsimplex_scratch': LocalMemory(
'mot_float_type', self._nmr_parameters * 2 + (self._nmr_parameters + 1) ** 2 + 1),
'initial_simplex_scale': LocalMemory('m... | [
"def",
"get_kernel_data",
"(",
"self",
")",
":",
"return",
"{",
"'nmsimplex_scratch'",
":",
"LocalMemory",
"(",
"'mot_float_type'",
",",
"self",
".",
"_nmr_parameters",
"*",
"2",
"+",
"(",
"self",
".",
"_nmr_parameters",
"+",
"1",
")",
"**",
"2",
"+",
"1",... | Get the kernel data needed for this optimization routine to work. | [
"Get",
"the",
"kernel",
"data",
"needed",
"for",
"this",
"optimization",
"routine",
"to",
"work",
"."
] | python | train |
manahl/arctic | arctic/store/version_store.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/store/version_store.py#L716-L761 | def write_metadata(self, symbol, metadata, prune_previous_version=True, **kwargs):
"""
Write 'metadata' under the specified 'symbol' name to this library.
The data will remain unchanged. A new version will be created.
If the symbol is missing, it causes a write with empty data (None, pic... | [
"def",
"write_metadata",
"(",
"self",
",",
"symbol",
",",
"metadata",
",",
"prune_previous_version",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make a normal write with empty data and supplied metadata if symbol does not exist",
"try",
":",
"previous_version",
"="... | Write 'metadata' under the specified 'symbol' name to this library.
The data will remain unchanged. A new version will be created.
If the symbol is missing, it causes a write with empty data (None, pickled, can't append)
and the supplied metadata.
Returns a VersionedItem object only with... | [
"Write",
"metadata",
"under",
"the",
"specified",
"symbol",
"name",
"to",
"this",
"library",
".",
"The",
"data",
"will",
"remain",
"unchanged",
".",
"A",
"new",
"version",
"will",
"be",
"created",
".",
"If",
"the",
"symbol",
"is",
"missing",
"it",
"causes"... | python | train |
saltstack/salt | salt/states/infoblox_cname.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/infoblox_cname.py#L104-L124 | def absent(name=None, canonical=None, **api_opts):
'''
Ensure the CNAME with the given name or canonical name is removed
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
obj = __salt__['infoblox.get_cname'](name=name, canonical=canonical, **api_opts)
if not obj:
r... | [
"def",
"absent",
"(",
"name",
"=",
"None",
",",
"canonical",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}... | Ensure the CNAME with the given name or canonical name is removed | [
"Ensure",
"the",
"CNAME",
"with",
"the",
"given",
"name",
"or",
"canonical",
"name",
"is",
"removed"
] | python | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L725-L778 | def reconfigure_bird(cmd):
"""Reconfigure BIRD daemon.
Arguments:
cmd (string): A command to trigger a reconfiguration of Bird daemon
Notes:
Runs 'birdc configure' to reconfigure BIRD. Some useful information on
how birdc tool works:
-- Returns a non-zero exit code only... | [
"def",
"reconfigure_bird",
"(",
"cmd",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"log",
".",
"info",
"(",
"\"reconfiguring BIRD by running %s\"",
",",
"' '",
".",
"join"... | Reconfigure BIRD daemon.
Arguments:
cmd (string): A command to trigger a reconfiguration of Bird daemon
Notes:
Runs 'birdc configure' to reconfigure BIRD. Some useful information on
how birdc tool works:
-- Returns a non-zero exit code only when it can't access BIRD
... | [
"Reconfigure",
"BIRD",
"daemon",
"."
] | python | train |
jupyterhub/kubespawner | kubespawner/spawner.py | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1824-L1837 | def _options_form_default(self):
'''
Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined.
'''
if not self.profile_list:
... | [
"def",
"_options_form_default",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"profile_list",
":",
"return",
"''",
"if",
"callable",
"(",
"self",
".",
"profile_list",
")",
":",
"return",
"self",
".",
"_render_options_form_dynamically",
"else",
":",
"return"... | Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined. | [
"Build",
"the",
"form",
"template",
"according",
"to",
"the",
"profile_list",
"setting",
"."
] | python | train |
saltstack/salt | salt/modules/win_smtp_server.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_smtp_server.py#L403-L458 | def set_connection_ip_list(addresses=None, grant_by_default=False, server=_DEFAULT_SERVER):
'''
Set the IPGrant list for the SMTP virtual server.
:param str addresses: A dictionary of IP + subnet pairs.
:param bool grant_by_default: Whether the addresses should be a blacklist or whitelist.
:param s... | [
"def",
"set_connection_ip_list",
"(",
"addresses",
"=",
"None",
",",
"grant_by_default",
"=",
"False",
",",
"server",
"=",
"_DEFAULT_SERVER",
")",
":",
"setting",
"=",
"'IPGrant'",
"formatted_addresses",
"=",
"list",
"(",
")",
"# It's okay to accept an empty list for ... | Set the IPGrant list for the SMTP virtual server.
:param str addresses: A dictionary of IP + subnet pairs.
:param bool grant_by_default: Whether the addresses should be a blacklist or whitelist.
:param str server: The SMTP server name.
:return: A boolean representing whether the change succeeded.
... | [
"Set",
"the",
"IPGrant",
"list",
"for",
"the",
"SMTP",
"virtual",
"server",
"."
] | python | train |
micahhausler/container-transform | container_transform/kubernetes.py | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L267-L310 | def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << ... | [
"def",
"ingest_memory",
"(",
"self",
",",
"memory",
")",
":",
"def",
"lshift",
"(",
"num",
",",
"shift",
")",
":",
"return",
"num",
"<<",
"shift",
"def",
"k",
"(",
"num",
",",
"thousands",
")",
":",
"return",
"num",
"*",
"thousands",
"# if isinstance(m... | Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int | [
"Transform",
"the",
"memory",
"into",
"bytes"
] | python | train |
materialsvirtuallab/monty | monty/json.py | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L74-L120 | def as_dict(self):
"""
A JSON serializable dict representation of an object.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__}
try:
parent_module = self.__class__.__module__.split('.')[0]
module_version = impor... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"\"@module\"",
":",
"self",
".",
"__class__",
".",
"__module__",
",",
"\"@class\"",
":",
"self",
".",
"__class__",
".",
"__name__",
"}",
"try",
":",
"parent_module",
"=",
"self",
".",
"__class__",
... | A JSON serializable dict representation of an object. | [
"A",
"JSON",
"serializable",
"dict",
"representation",
"of",
"an",
"object",
"."
] | python | train |
markuskiller/textblob-de | textblob_de/tokenizers.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/tokenizers.py#L90-L132 | def word_tokenize(self, text, include_punc=True):
"""The Treebank tokenizer uses regular expressions to tokenize text as
in Penn Treebank.
It assumes that the text has already been segmented into sentences,
e.g. using ``self.sent_tokenize()``.
This tokenizer performs the follow... | [
"def",
"word_tokenize",
"(",
"self",
",",
"text",
",",
"include_punc",
"=",
"True",
")",
":",
"#: Do not process empty strings (Issue #3)",
"if",
"text",
".",
"strip",
"(",
")",
"==",
"\"\"",
":",
"return",
"[",
"]",
"_tokens",
"=",
"self",
".",
"word_tok",
... | The Treebank tokenizer uses regular expressions to tokenize text as
in Penn Treebank.
It assumes that the text has already been segmented into sentences,
e.g. using ``self.sent_tokenize()``.
This tokenizer performs the following steps:
- split standard contractions, e.g. ``don... | [
"The",
"Treebank",
"tokenizer",
"uses",
"regular",
"expressions",
"to",
"tokenize",
"text",
"as",
"in",
"Penn",
"Treebank",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/Util/prob_density.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Util/prob_density.py#L59-L69 | def _w_sigma_delta(self, sigma, delta):
"""
invert variance
:param sigma:
:param delta:
:return: w parameter
"""
sigma2=sigma**2
w2 = sigma2/(1-2*delta**2/np.pi)
w = np.sqrt(w2)
return w | [
"def",
"_w_sigma_delta",
"(",
"self",
",",
"sigma",
",",
"delta",
")",
":",
"sigma2",
"=",
"sigma",
"**",
"2",
"w2",
"=",
"sigma2",
"/",
"(",
"1",
"-",
"2",
"*",
"delta",
"**",
"2",
"/",
"np",
".",
"pi",
")",
"w",
"=",
"np",
".",
"sqrt",
"(",... | invert variance
:param sigma:
:param delta:
:return: w parameter | [
"invert",
"variance",
":",
"param",
"sigma",
":",
":",
"param",
"delta",
":",
":",
"return",
":",
"w",
"parameter"
] | python | train |
jaraco/keyrings.alt | keyrings/alt/multi.py | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/multi.py#L24-L41 | def get_password(self, service, username):
"""Get password of the username for the service
"""
init_part = self._keyring.get_password(service, username)
if init_part:
parts = [init_part]
i = 1
while True:
next_part = self._keyring.get_p... | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"init_part",
"=",
"self",
".",
"_keyring",
".",
"get_password",
"(",
"service",
",",
"username",
")",
"if",
"init_part",
":",
"parts",
"=",
"[",
"init_part",
"]",
"i",
"=",
... | Get password of the username for the service | [
"Get",
"password",
"of",
"the",
"username",
"for",
"the",
"service"
] | python | train |
evhub/coconut | coconut/compiler/grammar.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/grammar.py#L563-L574 | def subscriptgroup_handle(tokens):
"""Process subscriptgroups."""
internal_assert(0 < len(tokens) <= 3, "invalid slice args", tokens)
args = []
for arg in tokens:
if not arg:
arg = "None"
args.append(arg)
if len(args) == 1:
return args[0]
else:
return ... | [
"def",
"subscriptgroup_handle",
"(",
"tokens",
")",
":",
"internal_assert",
"(",
"0",
"<",
"len",
"(",
"tokens",
")",
"<=",
"3",
",",
"\"invalid slice args\"",
",",
"tokens",
")",
"args",
"=",
"[",
"]",
"for",
"arg",
"in",
"tokens",
":",
"if",
"not",
"... | Process subscriptgroups. | [
"Process",
"subscriptgroups",
"."
] | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/apiextensions_v1beta1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/apiextensions_v1beta1_api.py#L143-L171 | def delete_collection_custom_resource_definition(self, **kwargs): # noqa: E501
"""delete_collection_custom_resource_definition # noqa: E501
delete collection of CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP... | [
"def",
"delete_collection_custom_resource_definition",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
... | delete_collection_custom_resource_definition # noqa: E501
delete collection of CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_custom_reso... | [
"delete_collection_custom_resource_definition",
"#",
"noqa",
":",
"E501"
] | python | train |
wdbm/abstraction | es-1.py | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/es-1.py#L117-L175 | def deepdream(
net,
base_image,
iter_n = 10,
octave_n = 4,
octave_scale = 1.4,
end = "inception_4c/output",
clip = True,
**step_params
):
'''
an ascent through different scales called "octaves"
'''
# Prepare base images for all octaves.... | [
"def",
"deepdream",
"(",
"net",
",",
"base_image",
",",
"iter_n",
"=",
"10",
",",
"octave_n",
"=",
"4",
",",
"octave_scale",
"=",
"1.4",
",",
"end",
"=",
"\"inception_4c/output\"",
",",
"clip",
"=",
"True",
",",
"*",
"*",
"step_params",
")",
":",
"# Pr... | an ascent through different scales called "octaves" | [
"an",
"ascent",
"through",
"different",
"scales",
"called",
"octaves"
] | python | train |
freakboy3742/pyxero | xero/auth.py | https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L260-L279 | def verify(self, verifier):
"Verify an OAuth token"
# Construct the credentials for the verification request
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.oauth_token,
resource_owner_secret=self.oau... | [
"def",
"verify",
"(",
"self",
",",
"verifier",
")",
":",
"# Construct the credentials for the verification request",
"oauth",
"=",
"OAuth1",
"(",
"self",
".",
"consumer_key",
",",
"client_secret",
"=",
"self",
".",
"consumer_secret",
",",
"resource_owner_key",
"=",
... | Verify an OAuth token | [
"Verify",
"an",
"OAuth",
"token"
] | python | train |
ninuxorg/nodeshot | nodeshot/core/nodes/views.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/views.py#L56-L79 | def get_queryset(self):
"""
Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL.
"""
# retrieve all nodes which are published and accessible to current user
# and use joins to retrieve related fields
queryset = super(... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"# retrieve all nodes which are published and accessible to current user",
"# and use joins to retrieve related fields",
"queryset",
"=",
"super",
"(",
"NodeList",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
".",
"select_re... | Optionally restricts the returned nodes
by filtering against a `search` query parameter in the URL. | [
"Optionally",
"restricts",
"the",
"returned",
"nodes",
"by",
"filtering",
"against",
"a",
"search",
"query",
"parameter",
"in",
"the",
"URL",
"."
] | python | train |
bitprophet/ssh | ssh/channel.py | https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/channel.py#L767-L791 | def sendall(self, s):
"""
Send data to the channel, without allowing partial results. Unlike
L{send}, this method continues to send data from the given string until
either all data has been sent or an error occurs. Nothing is returned.
@param s: data to send.
@type s: ... | [
"def",
"sendall",
"(",
"self",
",",
"s",
")",
":",
"while",
"s",
":",
"if",
"self",
".",
"closed",
":",
"# this doesn't seem useful, but it is the documented behavior of Socket",
"raise",
"socket",
".",
"error",
"(",
"'Socket is closed'",
")",
"sent",
"=",
"self",... | Send data to the channel, without allowing partial results. Unlike
L{send}, this method continues to send data from the given string until
either all data has been sent or an error occurs. Nothing is returned.
@param s: data to send.
@type s: str
@raise socket.timeout: if sen... | [
"Send",
"data",
"to",
"the",
"channel",
"without",
"allowing",
"partial",
"results",
".",
"Unlike",
"L",
"{",
"send",
"}",
"this",
"method",
"continues",
"to",
"send",
"data",
"from",
"the",
"given",
"string",
"until",
"either",
"all",
"data",
"has",
"been... | python | train |
mojaie/chorus | chorus/model/graphmol.py | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L145-L166 | def add_molecule(self, mol, bond=None, base=None, target=None):
"""connect atom group (for SMILES parser)
May requires recalculation of 2D coordinate for drawing
Args:
mol: graphmol.Compound()
the original object will be copied.
bond: Bond object to be c... | [
"def",
"add_molecule",
"(",
"self",
",",
"mol",
",",
"bond",
"=",
"None",
",",
"base",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"ai",
"=",
"self",
".",
"available_idx",
"(",
")",
"mapping",
"=",
"{",
"n",
":",
"n",
"+",
"ai",
"-",
"1"... | connect atom group (for SMILES parser)
May requires recalculation of 2D coordinate for drawing
Args:
mol: graphmol.Compound()
the original object will be copied.
bond: Bond object to be connected.
the original will not be copied so be careful.
... | [
"connect",
"atom",
"group",
"(",
"for",
"SMILES",
"parser",
")"
] | python | train |
MacHu-GWU/single_file_module-project | sfm/ziplib.py | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/ziplib.py#L52-L73 | def compress(obj, level=6, return_type="bytes"):
"""Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode by... | [
"def",
"compress",
"(",
"obj",
",",
"level",
"=",
"6",
",",
"return_type",
"=",
"\"bytes\"",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":",
"b",
"=",
"_compress_bytes",
"(",
"obj",
",",
"level",
")",
"elif",
"isinstance",
"(",
... | Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode bytes in utf-8 string. | [
"Compress",
"anything",
"to",
"bytes",
"or",
"string",
"."
] | python | train |
thebjorn/pydeps | pydeps/pydeps.py | https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/pydeps.py#L66-L98 | def externals(trgt, **kwargs):
"""Return a list of direct external dependencies of ``pkgname``.
Called for the ``pydeps --externals`` command.
"""
kw = dict(
T='svg', config=None, debug=False, display=None, exclude=[], externals=True,
format='svg', max_bacon=2**65, no_config=True, nod... | [
"def",
"externals",
"(",
"trgt",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"dict",
"(",
"T",
"=",
"'svg'",
",",
"config",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"display",
"=",
"None",
",",
"exclude",
"=",
"[",
"]",
",",
"externals",
... | Return a list of direct external dependencies of ``pkgname``.
Called for the ``pydeps --externals`` command. | [
"Return",
"a",
"list",
"of",
"direct",
"external",
"dependencies",
"of",
"pkgname",
".",
"Called",
"for",
"the",
"pydeps",
"--",
"externals",
"command",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Debug.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Debug.py#L144-L162 | def caller_trace(back=0):
"""
Trace caller stack and save info into global dicts, which
are printed automatically at the end of SCons execution.
"""
global caller_bases, caller_dicts
import traceback
tb = traceback.extract_stack(limit=3+back)
tb.reverse()
callee = tb[1][:3]
calle... | [
"def",
"caller_trace",
"(",
"back",
"=",
"0",
")",
":",
"global",
"caller_bases",
",",
"caller_dicts",
"import",
"traceback",
"tb",
"=",
"traceback",
".",
"extract_stack",
"(",
"limit",
"=",
"3",
"+",
"back",
")",
"tb",
".",
"reverse",
"(",
")",
"callee"... | Trace caller stack and save info into global dicts, which
are printed automatically at the end of SCons execution. | [
"Trace",
"caller",
"stack",
"and",
"save",
"info",
"into",
"global",
"dicts",
"which",
"are",
"printed",
"automatically",
"at",
"the",
"end",
"of",
"SCons",
"execution",
"."
] | python | train |
numenta/htmresearch | htmresearch/frameworks/grid_cell_learning/CAN.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/grid_cell_learning/CAN.py#L531-L641 | def learn(self,
runs,
dir=1,
periodic=False,
recurrent=True,
randomSpeed=False):
"""
Traverses a sinusoidal trajectory across the environment, learning during
the process. A pair of runs across the environment (one in each direction)
takes 10 ... | [
"def",
"learn",
"(",
"self",
",",
"runs",
",",
"dir",
"=",
"1",
",",
"periodic",
"=",
"False",
",",
"recurrent",
"=",
"True",
",",
"randomSpeed",
"=",
"False",
")",
":",
"# Set up plotting",
"if",
"self",
".",
"plotting",
":",
"self",
".",
"fig",
"="... | Traverses a sinusoidal trajectory across the environment, learning during
the process. A pair of runs across the environment (one in each direction)
takes 10 seconds if in a periodic larger environment, and 4 seconds in a
smaller nonperiodic environment.
:param runs: How many runs across the environme... | [
"Traverses",
"a",
"sinusoidal",
"trajectory",
"across",
"the",
"environment",
"learning",
"during",
"the",
"process",
".",
"A",
"pair",
"of",
"runs",
"across",
"the",
"environment",
"(",
"one",
"in",
"each",
"direction",
")",
"takes",
"10",
"seconds",
"if",
... | python | train |
PyGithub/PyGithub | github/Organization.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Organization.py#L789-L799 | def get_teams(self):
"""
:calls: `GET /orgs/:org/teams <http://developer.github.com/v3/orgs/teams>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team`
"""
return github.PaginatedList.PaginatedList(
github.Team.Team,
self._req... | [
"def",
"get_teams",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"Team",
".",
"Team",
",",
"self",
".",
"_requester",
",",
"self",
".",
"url",
"+",
"\"/teams\"",
",",
"None",
")"
] | :calls: `GET /orgs/:org/teams <http://developer.github.com/v3/orgs/teams>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team` | [
":",
"calls",
":",
"GET",
"/",
"orgs",
"/",
":",
"org",
"/",
"teams",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"orgs",
"/",
"teams",
">",
"_",
":",
"rtype",
":",
":",
"class",
":",
"github",
".",
"PaginatedList"... | python | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L910-L914 | def seriesshape(self):
"""Shape of the whole time series (time being the first dimension)."""
seriesshape = [len(hydpy.pub.timegrids.init)]
seriesshape.extend(self.shape)
return tuple(seriesshape) | [
"def",
"seriesshape",
"(",
"self",
")",
":",
"seriesshape",
"=",
"[",
"len",
"(",
"hydpy",
".",
"pub",
".",
"timegrids",
".",
"init",
")",
"]",
"seriesshape",
".",
"extend",
"(",
"self",
".",
"shape",
")",
"return",
"tuple",
"(",
"seriesshape",
")"
] | Shape of the whole time series (time being the first dimension). | [
"Shape",
"of",
"the",
"whole",
"time",
"series",
"(",
"time",
"being",
"the",
"first",
"dimension",
")",
"."
] | python | train |
quora/qcore | qcore/decorators.py | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/decorators.py#L277-L304 | def decorator_of_context_manager(ctxt):
"""Converts a context manager into a decorator.
This decorator will run the decorated function in the context of the
manager.
:param ctxt: Context to run the function in.
:return: Wrapper around the original function.
"""
def decorator_fn(*outer_ar... | [
"def",
"decorator_of_context_manager",
"(",
"ctxt",
")",
":",
"def",
"decorator_fn",
"(",
"*",
"outer_args",
",",
"*",
"*",
"outer_kwargs",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapper... | Converts a context manager into a decorator.
This decorator will run the decorated function in the context of the
manager.
:param ctxt: Context to run the function in.
:return: Wrapper around the original function. | [
"Converts",
"a",
"context",
"manager",
"into",
"a",
"decorator",
"."
] | python | train |
hugapi/hug | examples/html_serve.py | https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/examples/html_serve.py#L10-L15 | def nagiosCommandHelp(**kwargs):
"""
Returns command help document when no command is specified
"""
with open(os.path.join(DIRECTORY, 'document.html')) as document:
return document.read() | [
"def",
"nagiosCommandHelp",
"(",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DIRECTORY",
",",
"'document.html'",
")",
")",
"as",
"document",
":",
"return",
"document",
".",
"read",
"(",
")"
] | Returns command help document when no command is specified | [
"Returns",
"command",
"help",
"document",
"when",
"no",
"command",
"is",
"specified"
] | python | train |
f3at/feat | src/feat/extern/log/log.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/extern/log/log.py#L377-L382 | def warningObject(object, cat, format, *args):
"""
Log a warning message in the given category.
This is used for non-fatal problems.
"""
doLog(WARN, object, cat, format, args) | [
"def",
"warningObject",
"(",
"object",
",",
"cat",
",",
"format",
",",
"*",
"args",
")",
":",
"doLog",
"(",
"WARN",
",",
"object",
",",
"cat",
",",
"format",
",",
"args",
")"
] | Log a warning message in the given category.
This is used for non-fatal problems. | [
"Log",
"a",
"warning",
"message",
"in",
"the",
"given",
"category",
".",
"This",
"is",
"used",
"for",
"non",
"-",
"fatal",
"problems",
"."
] | python | train |
juju/charm-helpers | charmhelpers/contrib/openstack/amulet/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1101-L1120 | def get_ceph_pool_sample(self, sentry_unit, pool_id=0):
"""Take a sample of attributes of a ceph pool, returning ceph
pool name, object count and disk space used for the specified
pool ID number.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:param pool_id: C... | [
"def",
"get_ceph_pool_sample",
"(",
"self",
",",
"sentry_unit",
",",
"pool_id",
"=",
"0",
")",
":",
"df",
"=",
"self",
".",
"get_ceph_df",
"(",
"sentry_unit",
")",
"for",
"pool",
"in",
"df",
"[",
"'pools'",
"]",
":",
"if",
"pool",
"[",
"'id'",
"]",
"... | Take a sample of attributes of a ceph pool, returning ceph
pool name, object count and disk space used for the specified
pool ID number.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:param pool_id: Ceph pool ID
:returns: List of pool name, object count, kb d... | [
"Take",
"a",
"sample",
"of",
"attributes",
"of",
"a",
"ceph",
"pool",
"returning",
"ceph",
"pool",
"name",
"object",
"count",
"and",
"disk",
"space",
"used",
"for",
"the",
"specified",
"pool",
"ID",
"number",
"."
] | python | train |
jantman/pypi-download-stats | pypi_download_stats/projectstats.py | https://github.com/jantman/pypi-download-stats/blob/44a7a6bbcd61a9e7f02bd02c52584a98183f80c5/pypi_download_stats/projectstats.py#L208-L222 | def per_version_data(self):
"""
Return download data by version.
:return: dict of cache data; keys are datetime objects, values are
dict of version (str) to count (int)
:rtype: dict
"""
ret = {}
for cache_date in self.cache_dates:
data = sel... | [
"def",
"per_version_data",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"cache_date",
"in",
"self",
".",
"cache_dates",
":",
"data",
"=",
"self",
".",
"_cache_get",
"(",
"cache_date",
")",
"if",
"len",
"(",
"data",
"[",
"'by_version'",
"]",
")",... | Return download data by version.
:return: dict of cache data; keys are datetime objects, values are
dict of version (str) to count (int)
:rtype: dict | [
"Return",
"download",
"data",
"by",
"version",
"."
] | python | train |
santoshphilip/eppy | eppy/simpleread.py | https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/simpleread.py#L37-L53 | def idf2txt(txt):
"""convert the idf text to a simple text"""
astr = nocomment(txt)
objs = astr.split(';')
objs = [obj.split(',') for obj in objs]
objs = [[line.strip() for line in obj] for obj in objs]
objs = [[_tofloat(line) for line in obj] for obj in objs]
objs = [tuple(obj) for obj in o... | [
"def",
"idf2txt",
"(",
"txt",
")",
":",
"astr",
"=",
"nocomment",
"(",
"txt",
")",
"objs",
"=",
"astr",
".",
"split",
"(",
"';'",
")",
"objs",
"=",
"[",
"obj",
".",
"split",
"(",
"','",
")",
"for",
"obj",
"in",
"objs",
"]",
"objs",
"=",
"[",
... | convert the idf text to a simple text | [
"convert",
"the",
"idf",
"text",
"to",
"a",
"simple",
"text"
] | python | train |
quantopian/pyfolio | pyfolio/round_trips.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/round_trips.py#L322-L346 | def apply_sector_mappings_to_round_trips(round_trips, sector_mappings):
"""
Translates round trip symbols to sectors.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanation in round_trips.extract_round_trips
sector_ma... | [
"def",
"apply_sector_mappings_to_round_trips",
"(",
"round_trips",
",",
"sector_mappings",
")",
":",
"sector_round_trips",
"=",
"round_trips",
".",
"copy",
"(",
")",
"sector_round_trips",
".",
"symbol",
"=",
"sector_round_trips",
".",
"symbol",
".",
"apply",
"(",
"l... | Translates round trip symbols to sectors.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanation in round_trips.extract_round_trips
sector_mappings : dict or pd.Series, optional
Security identifier to sector mapping.
... | [
"Translates",
"round",
"trip",
"symbols",
"to",
"sectors",
"."
] | python | valid |
Kozea/cairocffi | cairocffi/patterns.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/patterns.py#L43-L61 | def _from_pointer(pointer, incref):
"""Wrap an existing :c:type:`cairo_pattern_t *` cdata pointer.
:type incref: bool
:param incref:
Whether increase the :ref:`reference count <refcounting>` now.
:return:
A new instance of :class:`Pattern` or one of its sub-class... | [
"def",
"_from_pointer",
"(",
"pointer",
",",
"incref",
")",
":",
"if",
"pointer",
"==",
"ffi",
".",
"NULL",
":",
"raise",
"ValueError",
"(",
"'Null pointer'",
")",
"if",
"incref",
":",
"cairo",
".",
"cairo_pattern_reference",
"(",
"pointer",
")",
"self",
"... | Wrap an existing :c:type:`cairo_pattern_t *` cdata pointer.
:type incref: bool
:param incref:
Whether increase the :ref:`reference count <refcounting>` now.
:return:
A new instance of :class:`Pattern` or one of its sub-classes,
depending on the pattern’s type... | [
"Wrap",
"an",
"existing",
":",
"c",
":",
"type",
":",
"cairo_pattern_t",
"*",
"cdata",
"pointer",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.