nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
xcmyz/FastSpeech
d8bd89790100542fda836b8f3f9342b64ad67e39
dataset.py
python
BufferDataset.__len__
(self)
return self.length_dataset
[]
def __len__(self): return self.length_dataset
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "length_dataset" ]
https://github.com/xcmyz/FastSpeech/blob/d8bd89790100542fda836b8f3f9342b64ad67e39/dataset.py#L55-L56
theislab/anndata
664e32b0aa6625fe593370d37174384c05abfd4e
anndata/experimental/multi_files/_anncollection.py
python
_harmonize_types
(attrs_keys, adatas)
return attrs_keys_types
[]
def _harmonize_types(attrs_keys, adatas): attrs_keys_types = {} def check_type(attr, key=None): arrs = [] for a in adatas: attr_arr = getattr(a, attr) if key is not None: attr_arr = attr_arr[key] arrs.append(attr_arr) # hacky but numpy find_common_type doesn't work with categoricals try: dtype = _merge([arr[:1] for arr in arrs]).dtype except ValueError: dtype = _merge([arr[:1, :1] for arr in arrs]).dtype return dtype for attr, keys in attrs_keys.items(): if len(keys) == 0: continue attrs_keys_types[attr] = {} for key in keys: attrs_keys_types[attr][key] = check_type(attr, key) attrs_keys_types["X"] = check_type("X") return attrs_keys_types
[ "def", "_harmonize_types", "(", "attrs_keys", ",", "adatas", ")", ":", "attrs_keys_types", "=", "{", "}", "def", "check_type", "(", "attr", ",", "key", "=", "None", ")", ":", "arrs", "=", "[", "]", "for", "a", "in", "adatas", ":", "attr_arr", "=", "g...
https://github.com/theislab/anndata/blob/664e32b0aa6625fe593370d37174384c05abfd4e/anndata/experimental/multi_files/_anncollection.py#L40-L66
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/connectable_component.py
python
ConnectableComponent.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/connectable_component.py#L227-L231
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pkg_resources.py
python
ensure_directory
(path)
Ensure that the parent directory of `path` exists
Ensure that the parent directory of `path` exists
[ "Ensure", "that", "the", "parent", "directory", "of", "path", "exists" ]
def ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
[ "def", "ensure_directory", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pkg_resources.py#L2657-L2661
JDAI-CV/Partial-Person-ReID
fb94dbfbec1105bbc22a442702bc6e385427d416
fastreid/utils/file_io.py
python
PathHandler._get_supported_prefixes
(self)
Returns: List[str]: the list of URI prefixes this PathHandler can support
Returns: List[str]: the list of URI prefixes this PathHandler can support
[ "Returns", ":", "List", "[", "str", "]", ":", "the", "list", "of", "URI", "prefixes", "this", "PathHandler", "can", "support" ]
def _get_supported_prefixes(self) -> List[str]: """ Returns: List[str]: the list of URI prefixes this PathHandler can support """ raise NotImplementedError()
[ "def", "_get_supported_prefixes", "(", "self", ")", "->", "List", "[", "str", "]", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/JDAI-CV/Partial-Person-ReID/blob/fb94dbfbec1105bbc22a442702bc6e385427d416/fastreid/utils/file_io.py#L67-L72
pyansys/pymapdl
c07291fc062b359abf0e92b95a92d753a95ef3d7
ansys/mapdl/core/post.py
python
PostProcessing._set_log_level
(self, level)
return self._mapdl._set_log_level(level)
alias for mapdl._set_log_level
alias for mapdl._set_log_level
[ "alias", "for", "mapdl", ".", "_set_log_level" ]
def _set_log_level(self, level): """alias for mapdl._set_log_level""" return self._mapdl._set_log_level(level)
[ "def", "_set_log_level", "(", "self", ",", "level", ")", ":", "return", "self", ".", "_mapdl", ".", "_set_log_level", "(", "level", ")" ]
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/post.py#L132-L134
tensorflow/tfx
b4a6b83269815ed12ba9df9e9154c7376fef2ea0
tfx/types/artifact.py
python
Artifact.artifact_type
(self)
return self._artifact_type
Type of the underlying mlmd artifact.
Type of the underlying mlmd artifact.
[ "Type", "of", "the", "underlying", "mlmd", "artifact", "." ]
def artifact_type(self): """Type of the underlying mlmd artifact.""" return self._artifact_type
[ "def", "artifact_type", "(", "self", ")", ":", "return", "self", ".", "_artifact_type" ]
https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/types/artifact.py#L443-L445
isce-framework/isce2
0e5114a8bede3caf1d533d98e44dfe4b983e3f48
components/isceobj/Alos2Proc/runRectRangeOffset.py
python
runRectRangeOffset
(self)
rectify range offset
rectify range offset
[ "rectify", "range", "offset" ]
def runRectRangeOffset(self): '''rectify range offset ''' if hasattr(self, 'doInSAR'): if not self.doInSAR: return catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name) self.updateParamemetersFromUser() referenceTrack = self._insar.loadTrack(reference=True) secondaryTrack = self._insar.loadTrack(reference=False) insarDir = 'insar' os.makedirs(insarDir, exist_ok=True) os.chdir(insarDir) #rectify rgoff = isceobj.createImage() rgoff.load(self._insar.rangeOffset+'.xml') if self._insar.radarDemAffineTransform == [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]: if not os.path.isfile(self._insar.rectRangeOffset): os.symlink(self._insar.rangeOffset, self._insar.rectRangeOffset) create_xml(self._insar.rectRangeOffset, rgoff.width, rgoff.length, 'float') else: rect_with_looks(self._insar.rangeOffset, self._insar.rectRangeOffset, rgoff.width, rgoff.length, rgoff.width, rgoff.length, self._insar.radarDemAffineTransform[0], self._insar.radarDemAffineTransform[1], self._insar.radarDemAffineTransform[2], self._insar.radarDemAffineTransform[3], self._insar.radarDemAffineTransform[4], self._insar.radarDemAffineTransform[5], self._insar.numberRangeLooksSim*self._insar.numberRangeLooks1, self._insar.numberAzimuthLooksSim*self._insar.numberAzimuthLooks1, self._insar.numberRangeLooks1, self._insar.numberAzimuthLooks1, 'REAL', 'Bilinear') create_xml(self._insar.rectRangeOffset, rgoff.width, rgoff.length, 'float') os.chdir('../') catalog.printToLog(logger, "runRectRangeOffset") self._insar.procDoc.addAllFromCatalog(catalog)
[ "def", "runRectRangeOffset", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'doInSAR'", ")", ":", "if", "not", "self", ".", "doInSAR", ":", "return", "catalog", "=", "isceobj", ".", "Catalog", ".", "createCatalog", "(", "self", ".", "_insar",...
https://github.com/isce-framework/isce2/blob/0e5114a8bede3caf1d533d98e44dfe4b983e3f48/components/isceobj/Alos2Proc/runRectRangeOffset.py#L15-L58
zigpy/zigpy
db10b078874d93ad1c546ec810706c2e5dc33d7f
zigpy/appdb.py
python
PersistingListener._load_relays
(self)
[]
async def _load_relays(self) -> None: async with self.execute(f"SELECT * FROM relays{DB_V}") as cursor: async for (ieee, value) in cursor: dev = self._application.get_device(ieee) dev.relays, _ = t.Relays.deserialize(value)
[ "async", "def", "_load_relays", "(", "self", ")", "->", "None", ":", "async", "with", "self", ".", "execute", "(", "f\"SELECT * FROM relays{DB_V}\"", ")", "as", "cursor", ":", "async", "for", "(", "ieee", ",", "value", ")", "in", "cursor", ":", "dev", "=...
https://github.com/zigpy/zigpy/blob/db10b078874d93ad1c546ec810706c2e5dc33d7f/zigpy/appdb.py#L583-L587
pycontribs/pyrax
a0c022981f76a4cba96a22ecc19bb52843ac4fbe
pyrax/cloudloadbalancers.py
python
CloudLoadBalancerClient.update_metadata_for_node
(self, loadbalancer, node, metadata)
return loadbalancer.update_metadata_for_node(node, metadata)
Updates the existing metadata for the specified node with the supplied dictionary.
Updates the existing metadata for the specified node with the supplied dictionary.
[ "Updates", "the", "existing", "metadata", "for", "the", "specified", "node", "with", "the", "supplied", "dictionary", "." ]
def update_metadata_for_node(self, loadbalancer, node, metadata): """ Updates the existing metadata for the specified node with the supplied dictionary. """ return loadbalancer.update_metadata_for_node(node, metadata)
[ "def", "update_metadata_for_node", "(", "self", ",", "loadbalancer", ",", "node", ",", "metadata", ")", ":", "return", "loadbalancer", ".", "update_metadata_for_node", "(", "node", ",", "metadata", ")" ]
https://github.com/pycontribs/pyrax/blob/a0c022981f76a4cba96a22ecc19bb52843ac4fbe/pyrax/cloudloadbalancers.py#L1563-L1568
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/_internal/antlr3/streams.py
python
ANTLRInputStream.__init__
(self, file, encoding=None)
@param file A file-like object holding your input. Only the read() method must be implemented. @param encoding If you set the optional encoding argument, then the data will be decoded on the fly.
@param file A file-like object holding your input. Only the read() method must be implemented.
[ "@param", "file", "A", "file", "-", "like", "object", "holding", "your", "input", ".", "Only", "the", "read", "()", "method", "must", "be", "implemented", "." ]
def __init__(self, file, encoding=None): """ @param file A file-like object holding your input. Only the read() method must be implemented. @param encoding If you set the optional encoding argument, then the data will be decoded on the fly. """ if encoding is not None: # wrap input in a decoding reader reader = codecs.lookup(encoding)[2] file = reader(file) data = file.read() ANTLRStringStream.__init__(self, data)
[ "def", "__init__", "(", "self", ",", "file", ",", "encoding", "=", "None", ")", ":", "if", "encoding", "is", "not", "None", ":", "# wrap input in a decoding reader", "reader", "=", "codecs", ".", "lookup", "(", "encoding", ")", "[", "2", "]", "file", "="...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/_internal/antlr3/streams.py#L560-L577
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/gui/controls/ultimatelistctrl.py
python
UltimateListMainWindow.GetColumnWidth
(self, col)
return column.GetWidth()
Returns the column width for the input column. :param `col`: an integer specifying the column index.
Returns the column width for the input column.
[ "Returns", "the", "column", "width", "for", "the", "input", "column", "." ]
def GetColumnWidth(self, col): """ Returns the column width for the input column. :param `col`: an integer specifying the column index. """ column = self._columns[col] return column.GetWidth()
[ "def", "GetColumnWidth", "(", "self", ",", "col", ")", ":", "column", "=", "self", ".", "_columns", "[", "col", "]", "return", "column", ".", "GetWidth", "(", ")" ]
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/controls/ultimatelistctrl.py#L8715-L8723
horazont/aioxmpp
c701e6399c90a6bb9bec0349018a03bd7b644cde
aioxmpp/stanza.py
python
Error.as_application_condition
(cls, other_cls)
return other_cls
Register `other_cls` as child class for the :attr:`application_condition` attribute. Doing so will allows the class to be parsed instead of being discarded. .. seealso:: :func:`make_application_error` --- creates and automatically registers a new application error condition.
Register `other_cls` as child class for the :attr:`application_condition` attribute. Doing so will allows the class to be parsed instead of being discarded.
[ "Register", "other_cls", "as", "child", "class", "for", "the", ":", "attr", ":", "application_condition", "attribute", ".", "Doing", "so", "will", "allows", "the", "class", "to", "be", "parsed", "instead", "of", "being", "discarded", "." ]
def as_application_condition(cls, other_cls): """ Register `other_cls` as child class for the :attr:`application_condition` attribute. Doing so will allows the class to be parsed instead of being discarded. .. seealso:: :func:`make_application_error` --- creates and automatically registers a new application error condition. """ cls.register_child(cls.application_condition, other_cls) return other_cls
[ "def", "as_application_condition", "(", "cls", ",", "other_cls", ")", ":", "cls", ".", "register_child", "(", "cls", ".", "application_condition", ",", "other_cls", ")", "return", "other_cls" ]
https://github.com/horazont/aioxmpp/blob/c701e6399c90a6bb9bec0349018a03bd7b644cde/aioxmpp/stanza.py#L406-L420
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/imaplib.py
python
IMAP4.setacl
(self, mailbox, who, what)
return self._simple_command('SETACL', mailbox, who, what)
Set a mailbox acl. (typ, [data]) = <instance>.setacl(mailbox, who, what)
Set a mailbox acl.
[ "Set", "a", "mailbox", "acl", "." ]
def setacl(self, mailbox, who, what): """Set a mailbox acl. (typ, [data]) = <instance>.setacl(mailbox, who, what) """ return self._simple_command('SETACL', mailbox, who, what)
[ "def", "setacl", "(", "self", ",", "mailbox", ",", "who", ",", "what", ")", ":", "return", "self", ".", "_simple_command", "(", "'SETACL'", ",", "mailbox", ",", "who", ",", "what", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/imaplib.py#L663-L668
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/schema.py
python
Constraint.__init__
(self, name=None, deferrable=None, initially=None, _create_rule=None)
Create a SQL constraint. :param name: Optional, the in-database name of this ``Constraint``. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param _create_rule: a callable which is passed the DDLCompiler object during compilation. Returns True or False to signal inline generation of this Constraint. The AddConstraint and DropConstraint DDL constructs provide DDLElement's more comprehensive "conditional DDL" approach that is passed a database connection when DDL is being issued. _create_rule is instead called during any CREATE TABLE compilation, where there may not be any transaction/connection in progress. However, it allows conditional compilation of the constraint even for backends which do not support addition of constraints through ALTER TABLE, which currently includes SQLite. _create_rule is used by some types to create constraints. Currently, its call signature is subject to change at any time.
Create a SQL constraint.
[ "Create", "a", "SQL", "constraint", "." ]
def __init__(self, name=None, deferrable=None, initially=None, _create_rule=None): """Create a SQL constraint. :param name: Optional, the in-database name of this ``Constraint``. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param _create_rule: a callable which is passed the DDLCompiler object during compilation. Returns True or False to signal inline generation of this Constraint. The AddConstraint and DropConstraint DDL constructs provide DDLElement's more comprehensive "conditional DDL" approach that is passed a database connection when DDL is being issued. _create_rule is instead called during any CREATE TABLE compilation, where there may not be any transaction/connection in progress. However, it allows conditional compilation of the constraint even for backends which do not support addition of constraints through ALTER TABLE, which currently includes SQLite. _create_rule is used by some types to create constraints. Currently, its call signature is subject to change at any time. """ self.name = name self.deferrable = deferrable self.initially = initially self._create_rule = _create_rule
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "deferrable", "=", "None", ",", "initially", "=", "None", ",", "_create_rule", "=", "None", ")", ":", "self", ".", "name", "=", "name", "self", ".", "deferrable", "=", "deferrable", "self",...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/schema.py#L1507-L1544
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/nexml/_nexml.py
python
TreeNode.insert_meta
(self, index, value)
[]
def insert_meta(self, index, value): self.meta[index] = value
[ "def", "insert_meta", "(", "self", ",", "index", ",", "value", ")", ":", "self", ".", "meta", "[", "index", "]", "=", "value" ]
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L8135-L8135
microsoft/nni
31f11f51249660930824e888af0d4e022823285c
nni/algorithms/compression/v2/pytorch/pruning/tools/base.py
python
TaskGenerator.get_best_result
(self)
return None
Returns ------- Optional[Tuple[int, Module, Dict[str, Dict[str, Tensor]], float, List[Dict]]] If self._best_task_id is not None, return best task id, best compact model, masks on the compact model, score, config list used in this task.
Returns ------- Optional[Tuple[int, Module, Dict[str, Dict[str, Tensor]], float, List[Dict]]] If self._best_task_id is not None, return best task id, best compact model, masks on the compact model, score, config list used in this task.
[ "Returns", "-------", "Optional", "[", "Tuple", "[", "int", "Module", "Dict", "[", "str", "Dict", "[", "str", "Tensor", "]]", "float", "List", "[", "Dict", "]]]", "If", "self", ".", "_best_task_id", "is", "not", "None", "return", "best", "task", "id", ...
def get_best_result(self) -> Optional[Tuple[int, Module, Dict[str, Dict[str, Tensor]], float, List[Dict]]]: """ Returns ------- Optional[Tuple[int, Module, Dict[str, Dict[str, Tensor]], float, List[Dict]]] If self._best_task_id is not None, return best task id, best compact model, masks on the compact model, score, config list used in this task. """ if self._best_task_id is not None: compact_model = torch.load(Path(self._log_dir_root, 'best_result', 'model.pth')) compact_model_masks = torch.load(Path(self._log_dir_root, 'best_result', 'masks.pth')) with Path(self._log_dir_root, 'best_result', 'config_list.json').open('r') as f: config_list = json_tricks.load(f) return self._best_task_id, compact_model, compact_model_masks, self._best_score, config_list return None
[ "def", "get_best_result", "(", "self", ")", "->", "Optional", "[", "Tuple", "[", "int", ",", "Module", ",", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Tensor", "]", "]", ",", "float", ",", "List", "[", "Dict", "]", "]", "]", ":", "if", ...
https://github.com/microsoft/nni/blob/31f11f51249660930824e888af0d4e022823285c/nni/algorithms/compression/v2/pytorch/pruning/tools/base.py#L564-L578
Robot-Will/Stino
a94831cd1bf40a59587a7b6cc2e9b5c4306b1bf2
StinoCommands.py
python
StinoRefreshLibrariesCommand.run
(self)
.
.
[ "." ]
def run(self): """.""" if stino.arduino_info['init_done']: stino.do_action.put(stino.st_menu.update_library_menu, stino.arduino_info)
[ "def", "run", "(", "self", ")", ":", "if", "stino", ".", "arduino_info", "[", "'init_done'", "]", ":", "stino", ".", "do_action", ".", "put", "(", "stino", ".", "st_menu", ".", "update_library_menu", ",", "stino", ".", "arduino_info", ")" ]
https://github.com/Robot-Will/Stino/blob/a94831cd1bf40a59587a7b6cc2e9b5c4306b1bf2/StinoCommands.py#L358-L362
sunnyxiaohu/R-C3D.pytorch
e8731af7b95f1dc934f6604f9c09e3c4ead74db5
lib/tf_model_zoo/models/textsum/seq2seq_attention_decode.py
python
BSDecoder.DecodeLoop
(self)
Decoding loop for long running process.
Decoding loop for long running process.
[ "Decoding", "loop", "for", "long", "running", "process", "." ]
def DecodeLoop(self): """Decoding loop for long running process.""" sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) step = 0 while step < FLAGS.max_decode_steps: time.sleep(DECODE_LOOP_DELAY_SECS) if not self._Decode(self._saver, sess): continue step += 1
[ "def", "DecodeLoop", "(", "self", ")", ":", "sess", "=", "tf", ".", "Session", "(", "config", "=", "tf", ".", "ConfigProto", "(", "allow_soft_placement", "=", "True", ")", ")", "step", "=", "0", "while", "step", "<", "FLAGS", ".", "max_decode_steps", "...
https://github.com/sunnyxiaohu/R-C3D.pytorch/blob/e8731af7b95f1dc934f6604f9c09e3c4ead74db5/lib/tf_model_zoo/models/textsum/seq2seq_attention_decode.py#L95-L103
facebookincubator/FCR
d5a629d062060cfa859b848ff54867e7450c04fd
external/common/fb303/py/gen-py/fb303_asyncio/fb303/FacebookService.py
python
Client.getStatusDetails
(self, )
return fut
User friendly description of status, such as why the service is in the dead or warning state, or what is being started or stopped.
User friendly description of status, such as why the service is in the dead or warning state, or what is being started or stopped.
[ "User", "friendly", "description", "of", "status", "such", "as", "why", "the", "service", "is", "in", "the", "dead", "or", "warning", "state", "or", "what", "is", "being", "started", "or", "stopped", "." ]
def getStatusDetails(self, ): """ User friendly description of status, such as why the service is in the dead or warning state, or what is being started or stopped. """ self._seqid += 1 fut = self._futures[self._seqid] = asyncio.Future(loop=self._loop) self.send_getStatusDetails() return fut
[ "def", "getStatusDetails", "(", "self", ",", ")", ":", "self", ".", "_seqid", "+=", "1", "fut", "=", "self", ".", "_futures", "[", "self", ".", "_seqid", "]", "=", "asyncio", ".", "Future", "(", "loop", "=", "self", ".", "_loop", ")", "self", ".", ...
https://github.com/facebookincubator/FCR/blob/d5a629d062060cfa859b848ff54867e7450c04fd/external/common/fb303/py/gen-py/fb303_asyncio/fb303/FacebookService.py#L2406-L2414
microsoft/ptvsd
99c8513921021d2cc7cd82e132b65c644c256768
src/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/window.py
python
Window._as_parameter_
(self)
return self.get_handle()
Compatibility with ctypes. Allows passing transparently a Window object to an API call.
Compatibility with ctypes. Allows passing transparently a Window object to an API call.
[ "Compatibility", "with", "ctypes", ".", "Allows", "passing", "transparently", "a", "Window", "object", "to", "an", "API", "call", "." ]
def _as_parameter_(self): """ Compatibility with ctypes. Allows passing transparently a Window object to an API call. """ return self.get_handle()
[ "def", "_as_parameter_", "(", "self", ")", ":", "return", "self", ".", "get_handle", "(", ")" ]
https://github.com/microsoft/ptvsd/blob/99c8513921021d2cc7cd82e132b65c644c256768/src/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/window.py#L141-L146
PyFilesystem/pyfilesystem
7dfe14ae6c3b9c53543c1c3890232d9f37579f34
fs/path.py
python
dirname
(path)
return pathsplit(path)[0]
Returns the parent directory of a path. This is always equivalent to the 'head' component of the value returned by pathsplit(path). :param path: A FS path >>> dirname('foo/bar/baz') 'foo/bar' >>> dirname('/foo/bar') '/foo' >>> dirname('/foo') '/'
Returns the parent directory of a path.
[ "Returns", "the", "parent", "directory", "of", "a", "path", "." ]
def dirname(path): """Returns the parent directory of a path. This is always equivalent to the 'head' component of the value returned by pathsplit(path). :param path: A FS path >>> dirname('foo/bar/baz') 'foo/bar' >>> dirname('/foo/bar') '/foo' >>> dirname('/foo') '/' """ return pathsplit(path)[0]
[ "def", "dirname", "(", "path", ")", ":", "return", "pathsplit", "(", "path", ")", "[", "0", "]" ]
https://github.com/PyFilesystem/pyfilesystem/blob/7dfe14ae6c3b9c53543c1c3890232d9f37579f34/fs/path.py#L287-L305
santatic/web2attack
44b6e481a3d56cf0d98073ae0fb69833dda563d9
w2a/lib/searcher/filter.py
python
filter
(domain, contents, type, delay=2)
return (result_subdomains, result_emails)
[]
def filter(domain, contents, type, delay=2): result_subdomains = [] result_emails = [] total = len(contents) current = 0 for i in contents: current += 1 percent = int(current*100/total) print_process(percent) i['data'] = unquote(i['data']) d = domain_filter(domain, unquote(i['url'])) d += domain_filter(domain, i['data']) e = email_filter(domain, i['data']) d = sorted(list(set(real_domain(d)))) e = sorted(list(set(real_email(e)))) if len(d) >= type or len(e) >= type: try: data = get_link(i['url']) d += domain_filter(domain, data) e += email_filter(domain, data) except Exception as error: pass sleep(delay) result_subdomains += sorted(list(set(real_domain(d)))) result_emails += sorted(list(set(real_email(e)))) print_line('') return (result_subdomains, result_emails)
[ "def", "filter", "(", "domain", ",", "contents", ",", "type", ",", "delay", "=", "2", ")", ":", "result_subdomains", "=", "[", "]", "result_emails", "=", "[", "]", "total", "=", "len", "(", "contents", ")", "current", "=", "0", "for", "i", "in", "c...
https://github.com/santatic/web2attack/blob/44b6e481a3d56cf0d98073ae0fb69833dda563d9/w2a/lib/searcher/filter.py#L11-L46
johannfaouzi/pyts
1e584877bc3f06194ceb530a156d8a10e32c12a5
pyts/metrics/dtw.py
python
_dtw_multiscale
(x, y, dist='square', resolution=2, radius=0, return_cost=False, return_accumulated=False, return_path=False)
return res
Multiscale Dynamic Time Warping (DTW) distance. This version of DTW builds an adaptive constraint region. First both time series are downsampled, with the sizes of the original times series being divided by ``resolution``. Then the optimal path between the two downsampled time series is computed. Finally this optimal path is projected on the orginal scale and used as the constraint region. Options ------- resolution : int (default = 2) The resolution level. radius : int (default = 0) The radius used to expand the constraint region. The optimal path computed at the resolution level is expanded with `radius` cells to the top, bottom, left and right of every cell belonging to the optimal path. It is computed at the resolution level. References ---------- .. [1] M. Müller, H. Mattes and F. Kurth, "An efficient multiscale approach to audio synchronization". International Conference on Music Information Retrieval, 6(1), 192-197 (2006).
Multiscale Dynamic Time Warping (DTW) distance.
[ "Multiscale", "Dynamic", "Time", "Warping", "(", "DTW", ")", "distance", "." ]
def _dtw_multiscale(x, y, dist='square', resolution=2, radius=0, return_cost=False, return_accumulated=False, return_path=False): """Multiscale Dynamic Time Warping (DTW) distance. This version of DTW builds an adaptive constraint region. First both time series are downsampled, with the sizes of the original times series being divided by ``resolution``. Then the optimal path between the two downsampled time series is computed. Finally this optimal path is projected on the orginal scale and used as the constraint region. Options ------- resolution : int (default = 2) The resolution level. radius : int (default = 0) The radius used to expand the constraint region. The optimal path computed at the resolution level is expanded with `radius` cells to the top, bottom, left and right of every cell belonging to the optimal path. It is computed at the resolution level. References ---------- .. [1] M. Müller, H. Mattes and F. Kurth, "An efficient multiscale approach to audio synchronization". International Conference on Music Information Retrieval, 6(1), 192-197 (2006). """ x, y, precomputed_cost, n_timestamps_1, n_timestamps_2 = \ _check_input_dtw(x, y, precomputed_cost=None, dist=dist, method="multiscale") region = _multiscale_region(x, y, dist, resolution=resolution, radius=radius) cost_mat = cost_matrix(x, y, dist=dist, region=region) acc_cost_mat = accumulated_cost_matrix(cost_mat, region=region) dtw_dist = acc_cost_mat[-1, -1] if dist == 'square': dtw_dist = sqrt(dtw_dist) res = _return_results(dtw_dist, cost_mat, acc_cost_mat, return_cost, return_accumulated, return_path) return res
[ "def", "_dtw_multiscale", "(", "x", ",", "y", ",", "dist", "=", "'square'", ",", "resolution", "=", "2", ",", "radius", "=", "0", ",", "return_cost", "=", "False", ",", "return_accumulated", "=", "False", ",", "return_path", "=", "False", ")", ":", "x"...
https://github.com/johannfaouzi/pyts/blob/1e584877bc3f06194ceb530a156d8a10e32c12a5/pyts/metrics/dtw.py#L770-L813
pact-foundation/pact-python
c431b4f2b90f096b17c5ec68f13369ed7127e1d4
examples/consumer/src/consumer.py
python
UserConsumer.__init__
(self, base_uri: str)
Initialise the Consumer, in this case we only need to know the URI. :param base_uri: The full URI, including port of the Provider to connect to
Initialise the Consumer, in this case we only need to know the URI.
[ "Initialise", "the", "Consumer", "in", "this", "case", "we", "only", "need", "to", "know", "the", "URI", "." ]
def __init__(self, base_uri: str): """Initialise the Consumer, in this case we only need to know the URI. :param base_uri: The full URI, including port of the Provider to connect to """ self.base_uri = base_uri
[ "def", "__init__", "(", "self", ",", "base_uri", ":", "str", ")", ":", "self", ".", "base_uri", "=", "base_uri" ]
https://github.com/pact-foundation/pact-python/blob/c431b4f2b90f096b17c5ec68f13369ed7127e1d4/examples/consumer/src/consumer.py#L19-L24
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iotvideo/v20191126/models.py
python
ModifyProductResponse.__init__
(self)
r""" :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): r""" :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iotvideo/v20191126/models.py#L3520-L3525
catalyst-team/catalyst
678dc06eda1848242df010b7f34adb572def2598
catalyst/contrib/data/sampler_inbatch.py
python
IInbatchTripletSampler.sample
(self, features: Tensor, labels: TLabels)
This method includes the logic of sampling/selecting triplets. Args: features: tensor of features labels: labels of the samples in the batch, list or Tensor of shape (batch_size;) Returns: the batch of triplets Raises: NotImplementedError: you should implement it
This method includes the logic of sampling/selecting triplets.
[ "This", "method", "includes", "the", "logic", "of", "sampling", "/", "selecting", "triplets", "." ]
def sample(self, features: Tensor, labels: TLabels) -> TTriplets: """ This method includes the logic of sampling/selecting triplets. Args: features: tensor of features labels: labels of the samples in the batch, list or Tensor of shape (batch_size;) Returns: the batch of triplets Raises: NotImplementedError: you should implement it """ raise NotImplementedError()
[ "def", "sample", "(", "self", ",", "features", ":", "Tensor", ",", "labels", ":", "TLabels", ")", "->", "TTriplets", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/catalyst-team/catalyst/blob/678dc06eda1848242df010b7f34adb572def2598/catalyst/contrib/data/sampler_inbatch.py#L41-L55
jantman/misc-scripts
dba5680bafbc5c5d2d9d4abcc305c57df373cd26
cm600_to_graphite.py
python
CM600StatsGetter.get_stats
(self)
return res
Get statistics from modem; return a dict :return: stats :rtype: dict
Get statistics from modem; return a dict
[ "Get", "statistics", "from", "modem", ";", "return", "a", "dict" ]
def get_stats(self): """ Get statistics from modem; return a dict :return: stats :rtype: dict """ r = requests.get(self.url, auth=(self.username, self.password)) r.raise_for_status() tree = etree.HTML(r.text) res = {} res.update(self._do_ds(tree.xpath('//table[@id="dsTable"]')[0])) res.update(self._do_us(tree.xpath('//table[@id="usTable"]')[0])) return res
[ "def", "get_stats", "(", "self", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "url", ",", "auth", "=", "(", "self", ".", "username", ",", "self", ".", "password", ")", ")", "r", ".", "raise_for_status", "(", ")", "tree", "=", "et...
https://github.com/jantman/misc-scripts/blob/dba5680bafbc5c5d2d9d4abcc305c57df373cd26/cm600_to_graphite.py#L219-L232
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/email/utils.py
python
encode_rfc2231
(s, charset=None, language=None)
return "%s'%s'%s" % (charset, language, s)
Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language.
Encode string according to RFC 2231.
[ "Encode", "string", "according", "to", "RFC", "2231", "." ]
def encode_rfc2231(s, charset=None, language=None): """Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. """ import urllib s = urllib.quote(s, safe='') if charset is None and language is None: return s if language is None: language = '' return "%s'%s'%s" % (charset, language, s)
[ "def", "encode_rfc2231", "(", "s", ",", "charset", "=", "None", ",", "language", "=", "None", ")", ":", "import", "urllib", "s", "=", "urllib", ".", "quote", "(", "s", ",", "safe", "=", "''", ")", "if", "charset", "is", "None", "and", "language", "...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/email/utils.py#L242-L255
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/autotvm/task/space.py
python
ConfigSpace.get
(self, index)
return ret
Get a config entity with detailed parameters from this space Parameters ---------- index: int index in the space
Get a config entity with detailed parameters from this space
[ "Get", "a", "config", "entity", "with", "detailed", "parameters", "from", "this", "space" ]
def get(self, index): """Get a config entity with detailed parameters from this space Parameters ---------- index: int index in the space """ if index < 0 or index >= len(self): raise IndexError("Index out of range: size {}, got index {}".format(len(self), index)) entities = OrderedDict() t = index for name, space in self.space_map.items(): entities[name] = space[t % len(space)] t //= len(space) ret = ConfigEntity(index, self.code_hash, entities, self._constraints) return ret
[ "def", "get", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", "or", "index", ">=", "len", "(", "self", ")", ":", "raise", "IndexError", "(", "\"Index out of range: size {}, got index {}\"", ".", "format", "(", "len", "(", "self", ")", ",", ...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/autotvm/task/space.py#L846-L862
mrjoes/flask-admin
402b56ea844dc5b215f6293e7dc63f39a6723692
flask_admin/form/fields.py
python
DateTimeField.__init__
(self, label=None, validators=None, format=None, **kwargs)
Constructor :param label: Label :param validators: Field validators :param format: Format for text to date conversion. Defaults to '%Y-%m-%d %H:%M:%S' :param kwargs: Any additional parameters
Constructor
[ "Constructor" ]
def __init__(self, label=None, validators=None, format=None, **kwargs): """ Constructor :param label: Label :param validators: Field validators :param format: Format for text to date conversion. Defaults to '%Y-%m-%d %H:%M:%S' :param kwargs: Any additional parameters """ super(DateTimeField, self).__init__(label, validators, **kwargs) self.format = format or '%Y-%m-%d %H:%M:%S'
[ "def", "__init__", "(", "self", ",", "label", "=", "None", ",", "validators", "=", "None", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "DateTimeField", ",", "self", ")", ".", "__init__", "(", "label", ",", "validators...
https://github.com/mrjoes/flask-admin/blob/402b56ea844dc5b215f6293e7dc63f39a6723692/flask_admin/form/fields.py#L21-L36
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
examples/advanced_operations/add_ad_customizer.py
python
_create_ad_customizer_mapping
( client, customer_id, ad_customizer_feed_resource_name, feed_details, )
Creates a feed mapping for a given feed. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. ad_customizer_feed_resource_name: the resource name of the ad customizer feed. feed_details: a dict mapping feed attribute names to their IDs.
Creates a feed mapping for a given feed.
[ "Creates", "a", "feed", "mapping", "for", "a", "given", "feed", "." ]
def _create_ad_customizer_mapping( client, customer_id, ad_customizer_feed_resource_name, feed_details, ): """Creates a feed mapping for a given feed. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. ad_customizer_feed_resource_name: the resource name of the ad customizer feed. feed_details: a dict mapping feed attribute names to their IDs. """ placeholder_field_enum = client.enums.AdCustomizerPlaceholderFieldEnum # Map the feed attributes to ad customizer placeholder fields. For a full # list of ad customizer placeholder fields, see: # https://developers.google.com/google-ads/api/reference/rpc/latest/AdCustomizerPlaceholderFieldEnum.AdCustomizerPlaceholderField name_field_mapping = client.get_type("AttributeFieldMapping") name_field_mapping.feed_attribute_id = feed_details["Name"] name_field_mapping.ad_customizer_field = placeholder_field_enum.STRING price_field_mapping = client.get_type("AttributeFieldMapping") price_field_mapping.feed_attribute_id = feed_details["Price"] price_field_mapping.ad_customizer_field = placeholder_field_enum.PRICE date_field_mapping = client.get_type("AttributeFieldMapping") date_field_mapping.feed_attribute_id = feed_details["Date"] date_field_mapping.ad_customizer_field = placeholder_field_enum.DATE feed_mapping_op = client.get_type("FeedMappingOperation") feed_mapping = feed_mapping_op.create feed_mapping.feed = ad_customizer_feed_resource_name feed_mapping.placeholder_type = ( client.enums.PlaceholderTypeEnum.AD_CUSTOMIZER ) feed_mapping.attribute_field_mappings.extend( [name_field_mapping, price_field_mapping, date_field_mapping] ) feed_mapping_service = client.get_service("FeedMappingService") response = feed_mapping_service.mutate_feed_mappings( customer_id=customer_id, operations=[feed_mapping_op] ) for result in response.results: print( "Created feed mapping with resource name " f"{result.resource_name}" )
[ "def", "_create_ad_customizer_mapping", "(", "client", ",", "customer_id", ",", "ad_customizer_feed_resource_name", ",", "feed_details", ",", ")", ":", "placeholder_field_enum", "=", "client", ".", "enums", ".", "AdCustomizerPlaceholderFieldEnum", "# Map the feed attributes t...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/examples/advanced_operations/add_ad_customizer.py#L159-L210
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/tools/rotomask.py
python
RotoMaskEditor._move_mode_clicked
(self, move_button)
[]
def _move_mode_clicked(self, move_button): if self.roto_mask_layer.edit_mode == vieweditorlayer.ROTO_MOVE_MODE and move_button.get_active() == False: move_button.set_active(True) # we untoggled by clicking which is not allowed, untoggle happens whenthe other mode is selected. We set the untoggled button back to being active. elif move_button.get_active() == False: pass # this event is redundant, we always get two events when changing modes elif self.roto_mask_layer.edit_mode != vieweditorlayer.ROTO_MOVE_MODE: self.roto_mask_layer.edit_mode = vieweditorlayer.ROTO_MOVE_MODE self.kf_mode_button.set_active(False)
[ "def", "_move_mode_clicked", "(", "self", ",", "move_button", ")", ":", "if", "self", ".", "roto_mask_layer", ".", "edit_mode", "==", "vieweditorlayer", ".", "ROTO_MOVE_MODE", "and", "move_button", ".", "get_active", "(", ")", "==", "False", ":", "move_button", ...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/tools/rotomask.py#L303-L310
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugins/bitbox02/bitbox02.py
python
BitBox02_KeyStore.sign_message
(self, sequence, message, password)
return client.sign_message(keypath, message.encode("utf-8"), xtype)
[]
def sign_message(self, sequence, message, password): if password: raise Exception("BitBox02 does not accept a password from the host") client = self.get_client() keypath = self.get_derivation_prefix() + "/%d/%d" % sequence xtype = self.get_bip32_node_for_xpub().xtype return client.sign_message(keypath, message.encode("utf-8"), xtype)
[ "def", "sign_message", "(", "self", ",", "sequence", ",", "message", ",", "password", ")", ":", "if", "password", ":", "raise", "Exception", "(", "\"BitBox02 does not accept a password from the host\"", ")", "client", "=", "self", ".", "get_client", "(", ")", "k...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugins/bitbox02/bitbox02.py#L583-L589
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_vendor/pyparsing.py
python
StringStart.parseImpl
( self, instring, loc, doActions=True )
return loc, []
[]
def parseImpl( self, instring, loc, doActions=True ): if loc != 0: # see if entire string up to here is just whitespace and ignoreables if loc != self.preParse( instring, 0 ): raise ParseException(instring, loc, self.errmsg, self) return loc, []
[ "def", "parseImpl", "(", "self", ",", "instring", ",", "loc", ",", "doActions", "=", "True", ")", ":", "if", "loc", "!=", "0", ":", "# see if entire string up to here is just whitespace and ignoreables", "if", "loc", "!=", "self", ".", "preParse", "(", "instring...
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/pyparsing.py#L3188-L3193
llimllib/limbo
2e33a11e73f1ab13f24c06c8a76d1c9bfcf81afb
limbo/plugins/emoji.py
python
EmojiCache.update
(self)
[]
def update(self): self.emoji = list(emojiCodeDict.keys()) emoji_res = json.loads(self.server.slack.api_call("emoji.list")) for emo in emoji_res["emoji"]: url = emoji_res["emoji"][emo] emoji = ":{}:".format(emo) # duplicate emoji will start with "alias:" instead of an "http"; we # don't want to include dupes in our list so we don't bias towards them # https://api.slack.com/methods/emoji.list if url.startswith("http") and emoji not in emojiCodeDict: self.emoji.append(emoji)
[ "def", "update", "(", "self", ")", ":", "self", ".", "emoji", "=", "list", "(", "emojiCodeDict", ".", "keys", "(", ")", ")", "emoji_res", "=", "json", ".", "loads", "(", "self", ".", "server", ".", "slack", ".", "api_call", "(", "\"emoji.list\"", ")"...
https://github.com/llimllib/limbo/blob/2e33a11e73f1ab13f24c06c8a76d1c9bfcf81afb/limbo/plugins/emoji.py#L33-L43
houtianze/bypy
10fd0f18378174a775a05a366cc20ba6609f96c6
bypy/util.py
python
jsonload_no_exception
(filename)
[]
def jsonload_no_exception(filename): try: jsonload(filename) # In `python 3`, the exception when failing to parse is `json.JSONDecodeError` (subclass of `ValueError`) # but in `python 2`, it's just `ValueError` except Exception as ex: perr("Fail to load '{}' as json, exception:\n{}".format(filename, formatex(ex))) return {}
[ "def", "jsonload_no_exception", "(", "filename", ")", ":", "try", ":", "jsonload", "(", "filename", ")", "# In `python 3`, the exception when failing to parse is `json.JSONDecodeError` (subclass of `ValueError`)", "# but in `python 2`, it's just `ValueError`", "except", "Exception", ...
https://github.com/houtianze/bypy/blob/10fd0f18378174a775a05a366cc20ba6609f96c6/bypy/util.py#L259-L266
DistrictDataLabs/yellowbrick
2eb8e3edfbe6f3f22c595b38989a23ba7cea40cf
yellowbrick/features/rankd.py
python
RankDBase.finalize
(self, **kwargs)
Sets a title on the RankD plot. Parameters ---------- kwargs: generic keyword arguments. Notes ----- Generally this method is called from show and not directly by the user.
Sets a title on the RankD plot.
[ "Sets", "a", "title", "on", "the", "RankD", "plot", "." ]
def finalize(self, **kwargs): """ Sets a title on the RankD plot. Parameters ---------- kwargs: generic keyword arguments. Notes ----- Generally this method is called from show and not directly by the user. """ # There is a known bug in matplotlib 3.1.1 that affects RankD plots # See #912 and #914 for details. if mpl.__version__ == "3.1.1": msg = ( "RankD plots may be clipped when using matplotlib v3.1.1, " "upgrade to matplotlib v3.1.2 or later to fix the plots." ) warnings.warn(msg, YellowbrickWarning) # Set the title for all RankD visualizations. self.set_title( "{} Ranking of {} Features".format( self.ranking_.title(), len(self.features_) ) )
[ "def", "finalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# There is a known bug in matplotlib 3.1.1 that affects RankD plots", "# See #912 and #914 for details.", "if", "mpl", ".", "__version__", "==", "\"3.1.1\"", ":", "msg", "=", "(", "\"RankD plots may be cl...
https://github.com/DistrictDataLabs/yellowbrick/blob/2eb8e3edfbe6f3f22c595b38989a23ba7cea40cf/yellowbrick/features/rankd.py#L197-L223
OffensivePython/Nscan
4a507ca97a9f8b7f3fa4766c835f108671dbbcd6
stable/startup.py
python
nscanif.preloaded
(self)
return iface
Checks if a nscan interface is pre-loaded
Checks if a nscan interface is pre-loaded
[ "Checks", "if", "a", "nscan", "interface", "is", "pre", "-", "loaded" ]
def preloaded(self): ''' Checks if a nscan interface is pre-loaded ''' interfaces = open('/etc/network/interfaces', 'r') content = interfaces.read() interfaces.close() pattern = self.conf.format(self.ifname, '(.+?)') iface = re.search(pattern, content) if iface: iface = iface.group(1) return iface
[ "def", "preloaded", "(", "self", ")", ":", "interfaces", "=", "open", "(", "'/etc/network/interfaces'", ",", "'r'", ")", "content", "=", "interfaces", ".", "read", "(", ")", "interfaces", ".", "close", "(", ")", "pattern", "=", "self", ".", "conf", ".", ...
https://github.com/OffensivePython/Nscan/blob/4a507ca97a9f8b7f3fa4766c835f108671dbbcd6/stable/startup.py#L140-L151
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/decimal.py
python
Decimal._round_down
(self, prec)
Also known as round-towards-0, truncate.
Also known as round-towards-0, truncate.
[ "Also", "known", "as", "round", "-", "towards", "-", "0", "truncate", "." ]
def _round_down(self, prec): """Also known as round-towards-0, truncate.""" if _all_zeros(self._int, prec): return 0 else: return -1
[ "def", "_round_down", "(", "self", ",", "prec", ")", ":", "if", "_all_zeros", "(", "self", ".", "_int", ",", "prec", ")", ":", "return", "0", "else", ":", "return", "-", "1" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/decimal.py#L1742-L1747
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_5.9/paramiko/transport.py
python
Transport._set_forward_agent_handler
(self, handler)
[]
def _set_forward_agent_handler(self, handler): if handler is None: def default_handler(channel): self._queue_incoming_channel(channel) self._forward_agent_handler = default_handler else: self._forward_agent_handler = handler
[ "def", "_set_forward_agent_handler", "(", "self", ",", "handler", ")", ":", "if", "handler", "is", "None", ":", "def", "default_handler", "(", "channel", ")", ":", "self", ".", "_queue_incoming_channel", "(", "channel", ")", "self", ".", "_forward_agent_handler"...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_5.9/paramiko/transport.py#L1504-L1510
korcankaraokcu/PINCE
ecd8d5d92214592d47d46f16112d000c7834fab6
libpince/SysUtils.py
python
get_referenced_jumps_file
(pid)
return get_PINCE_IPC_directory(pid) + "/referenced_jumps_dict.txt"
Get the path of referenced jumps dict file for given pid Args: pid (int,str): PID of the process Returns: str: Path of referenced jumps dict file
Get the path of referenced jumps dict file for given pid
[ "Get", "the", "path", "of", "referenced", "jumps", "dict", "file", "for", "given", "pid" ]
def get_referenced_jumps_file(pid): """Get the path of referenced jumps dict file for given pid Args: pid (int,str): PID of the process Returns: str: Path of referenced jumps dict file """ return get_PINCE_IPC_directory(pid) + "/referenced_jumps_dict.txt"
[ "def", "get_referenced_jumps_file", "(", "pid", ")", ":", "return", "get_PINCE_IPC_directory", "(", "pid", ")", "+", "\"/referenced_jumps_dict.txt\"" ]
https://github.com/korcankaraokcu/PINCE/blob/ecd8d5d92214592d47d46f16112d000c7834fab6/libpince/SysUtils.py#L489-L498
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/zipapp.py
python
_write_file_prefix
(f, interpreter)
Write a shebang line.
Write a shebang line.
[ "Write", "a", "shebang", "line", "." ]
def _write_file_prefix(f, interpreter): """Write a shebang line.""" if interpreter: shebang = b'#!' + interpreter.encode(shebang_encoding) + b'\n' f.write(shebang)
[ "def", "_write_file_prefix", "(", "f", ",", "interpreter", ")", ":", "if", "interpreter", ":", "shebang", "=", "b'#!'", "+", "interpreter", ".", "encode", "(", "shebang_encoding", ")", "+", "b'\\n'", "f", ".", "write", "(", "shebang", ")" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/zipapp.py#L46-L50
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/xmpp/SleekXMPP/sleekxmpp/xmlstream/stanzabase.py
python
StanzaBase.get_payload
(self)
return list(self.xml)
Return a list of XML objects contained in the stanza.
Return a list of XML objects contained in the stanza.
[ "Return", "a", "list", "of", "XML", "objects", "contained", "in", "the", "stanza", "." ]
def get_payload(self): """Return a list of XML objects contained in the stanza.""" return list(self.xml)
[ "def", "get_payload", "(", "self", ")", ":", "return", "list", "(", "self", ".", "xml", ")" ]
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/xmpp/SleekXMPP/sleekxmpp/xmlstream/stanzabase.py#L1503-L1505
wangheda/youtube-8m
07e54b387ee027cb58b0c14f5eb7c88cfa516d58
youtube-8m-ensemble/train.py
python
Trainer.start_server_if_distributed
(self)
return (target, device_fn)
Starts a server if the execution is distributed.
Starts a server if the execution is distributed.
[ "Starts", "a", "server", "if", "the", "execution", "is", "distributed", "." ]
def start_server_if_distributed(self): """Starts a server if the execution is distributed.""" if self.cluster: logging.info("%s: Starting trainer within cluster %s.", task_as_string(self.task), self.cluster.as_dict()) server = start_server(self.cluster, self.task) target = server.target device_fn = tf.train.replica_device_setter( ps_device="/job:ps", worker_device="/job:%s/task:%d" % (self.task.type, self.task.index), cluster=self.cluster) else: target = "" device_fn = "" return (target, device_fn)
[ "def", "start_server_if_distributed", "(", "self", ")", ":", "if", "self", ".", "cluster", ":", "logging", ".", "info", "(", "\"%s: Starting trainer within cluster %s.\"", ",", "task_as_string", "(", "self", ".", "task", ")", ",", "self", ".", "cluster", ".", ...
https://github.com/wangheda/youtube-8m/blob/07e54b387ee027cb58b0c14f5eb7c88cfa516d58/youtube-8m-ensemble/train.py#L488-L503
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/data/staircase.py
python
MultiStairHandler.__init__
(self, stairType='simple', method='random', conditions=None, nTrials=50, randomSeed=None, originPath=None, name='', autoLog=True)
A Handler to allow easy interleaved staircase procedures (simple or QUEST). Parameters for the staircases, as used by the relevant :class:`StairHandler` or :class:`QuestHandler` (e.g. the `startVal`, `minVal`, `maxVal`...) should be specified in the `conditions` list and may vary between each staircase. In particular, the conditions **must** include a `startVal` (because this is a required argument to the above handlers), a `label` to tag the staircase and a `startValSd` (only for QUEST staircases). Any parameters not specified in the conditions file will revert to the default for that individual handler. If you need to customize the behaviour further you may want to look at the recipe on :ref:`interleavedStairs`. :params: stairType: 'simple', 'quest', or 'questplus' Use a :class:`StairHandler`, a :class:`QuestHandler`, or a :class:`QuestPlusHandler`. method: 'random', 'fullRandom', or 'sequential' If `random`, stairs are shuffled in each repeat but not randomized more than that (so you can't have 3 repeats of the same staircase in a row unless it's the only one still running). If `fullRandom`, the staircase order is "fully" randomized, meaning that, theoretically, a large number of subsequent trials could invoke the same staircase repeatedly. If `sequential`, don't perform any randomization. conditions: a list of dictionaries specifying conditions Can be used to control parameters for the different staircases. Can be imported from an Excel file using `psychopy.data.importConditions` MUST include keys providing, 'startVal', 'label' and 'startValSd' (QUEST only). The 'label' will be used in data file saving so should be unique. See Example Usage below. nTrials=50 Minimum trials to run (but may take more if the staircase hasn't also met its minimal reversals. See :class:`~psychopy.data.StairHandler` randomSeed : int or None The seed with which to initialize the random number generator (RNG). If `None` (default), do not initialize the RNG with a specific value. Example usage:: conditions=[ {'label':'low', 'startVal': 0.1, 'ori':45}, {'label':'high','startVal': 0.8, 'ori':45}, {'label':'low', 'startVal': 0.1, 'ori':90}, {'label':'high','startVal': 0.8, 'ori':90}, ] stairs = data.MultiStairHandler(conditions=conditions, nTrials=50) for thisIntensity, thisCondition in stairs: thisOri = thisCondition['ori'] # do something with thisIntensity and thisOri stairs.addResponse(correctIncorrect) # this is ESSENTIAL # save data as multiple formats stairs.saveDataAsExcel(fileName) # easy to browse stairs.saveAsPickle(fileName) # contains more info Raises ------ ValueError If an unknown randomization option was passed via the `method` keyword argument.
A Handler to allow easy interleaved staircase procedures (simple or QUEST).
[ "A", "Handler", "to", "allow", "easy", "interleaved", "staircase", "procedures", "(", "simple", "or", "QUEST", ")", "." ]
def __init__(self, stairType='simple', method='random', conditions=None, nTrials=50, randomSeed=None, originPath=None, name='', autoLog=True): """A Handler to allow easy interleaved staircase procedures (simple or QUEST). Parameters for the staircases, as used by the relevant :class:`StairHandler` or :class:`QuestHandler` (e.g. the `startVal`, `minVal`, `maxVal`...) should be specified in the `conditions` list and may vary between each staircase. In particular, the conditions **must** include a `startVal` (because this is a required argument to the above handlers), a `label` to tag the staircase and a `startValSd` (only for QUEST staircases). Any parameters not specified in the conditions file will revert to the default for that individual handler. If you need to customize the behaviour further you may want to look at the recipe on :ref:`interleavedStairs`. :params: stairType: 'simple', 'quest', or 'questplus' Use a :class:`StairHandler`, a :class:`QuestHandler`, or a :class:`QuestPlusHandler`. method: 'random', 'fullRandom', or 'sequential' If `random`, stairs are shuffled in each repeat but not randomized more than that (so you can't have 3 repeats of the same staircase in a row unless it's the only one still running). If `fullRandom`, the staircase order is "fully" randomized, meaning that, theoretically, a large number of subsequent trials could invoke the same staircase repeatedly. If `sequential`, don't perform any randomization. conditions: a list of dictionaries specifying conditions Can be used to control parameters for the different staircases. Can be imported from an Excel file using `psychopy.data.importConditions` MUST include keys providing, 'startVal', 'label' and 'startValSd' (QUEST only). The 'label' will be used in data file saving so should be unique. See Example Usage below. nTrials=50 Minimum trials to run (but may take more if the staircase hasn't also met its minimal reversals. See :class:`~psychopy.data.StairHandler` randomSeed : int or None The seed with which to initialize the random number generator (RNG). If `None` (default), do not initialize the RNG with a specific value. Example usage:: conditions=[ {'label':'low', 'startVal': 0.1, 'ori':45}, {'label':'high','startVal': 0.8, 'ori':45}, {'label':'low', 'startVal': 0.1, 'ori':90}, {'label':'high','startVal': 0.8, 'ori':90}, ] stairs = data.MultiStairHandler(conditions=conditions, nTrials=50) for thisIntensity, thisCondition in stairs: thisOri = thisCondition['ori'] # do something with thisIntensity and thisOri stairs.addResponse(correctIncorrect) # this is ESSENTIAL # save data as multiple formats stairs.saveDataAsExcel(fileName) # easy to browse stairs.saveAsPickle(fileName) # contains more info Raises ------ ValueError If an unknown randomization option was passed via the `method` keyword argument. """ self.name = name self.autoLog = autoLog self.type = stairType self.method = method self.randomSeed = randomSeed self._rng = np.random.RandomState(seed=randomSeed) self.conditions = conditions self.nTrials = nTrials self.finished = False self.totalTrials = 0 self._checkArguments() # create staircases self.staircases = [] # all staircases self.runningStaircases = [] # staircases that haven't finished yet self.thisPassRemaining = [] # staircases to run this pass self._createStairs() # fetch first staircase/value (without altering/advancing it) self._startNewPass() self.currentStaircase = self.thisPassRemaining[0] # take the first # gets updated by self.addData() self._nextIntensity = self.currentStaircase._nextIntensity # store the origin file and its path self.originPath, self.origin = self.getOriginPathAndFile(originPath) self._exp = None
[ "def", "__init__", "(", "self", ",", "stairType", "=", "'simple'", ",", "method", "=", "'random'", ",", "conditions", "=", "None", ",", "nTrials", "=", "50", ",", "randomSeed", "=", "None", ",", "originPath", "=", "None", ",", "name", "=", "''", ",", ...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/data/staircase.py#L1733-L1840
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/pyreadline/modes/emacs.py
python
EmacsMode.prefix_meta
(self, e)
Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f.
Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f.
[ "Metafy", "the", "next", "character", "typed", ".", "This", "is", "for", "keyboards", "without", "a", "meta", "key", ".", "Typing", "ESC", "f", "is", "equivalent", "to", "typing", "M", "-", "f", "." ]
def prefix_meta(self, e): # (ESC) '''Metafy the next character typed. This is for keyboards without a meta key. Typing ESC f is equivalent to typing M-f. ''' self.next_meta = True self.finalize()
[ "def", "prefix_meta", "(", "self", ",", "e", ")", ":", "# (ESC)", "self", ".", "next_meta", "=", "True", "self", ".", "finalize", "(", ")" ]
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/pyreadline/modes/emacs.py#L538-L542
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/views/generic/dates.py
python
BaseDateListView.get_date_list_period
(self)
return self.date_list_period
Get the aggregation period for the list of dates: 'year', 'month', or 'day'.
Get the aggregation period for the list of dates: 'year', 'month', or 'day'.
[ "Get", "the", "aggregation", "period", "for", "the", "list", "of", "dates", ":", "year", "month", "or", "day", "." ]
def get_date_list_period(self): """ Get the aggregation period for the list of dates: 'year', 'month', or 'day'. """ return self.date_list_period
[ "def", "get_date_list_period", "(", "self", ")", ":", "return", "self", ".", "date_list_period" ]
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/views/generic/dates.py#L344-L349
siegfried415/portia-dashboard
b1e116ea95afd736caf55df5d16e6da28c124eec
slybot/slybot/plugins/scrapely_annotations/processors.py
python
ItemProcessor.dump
(self, include_meta=False, validate=False)
Dump processed fields into a new item.
Dump processed fields into a new item.
[ "Dump", "processed", "fields", "into", "a", "new", "item", "." ]
def dump(self, include_meta=False, validate=False): """Dump processed fields into a new item.""" try: return self._dump(include_meta, validate) except (MissingRequiredError, ItemNotValidError): return {}
[ "def", "dump", "(", "self", ",", "include_meta", "=", "False", ",", "validate", "=", "False", ")", ":", "try", ":", "return", "self", ".", "_dump", "(", "include_meta", ",", "validate", ")", "except", "(", "MissingRequiredError", ",", "ItemNotValidError", ...
https://github.com/siegfried415/portia-dashboard/blob/b1e116ea95afd736caf55df5d16e6da28c124eec/slybot/slybot/plugins/scrapely_annotations/processors.py#L297-L302
Scifabric/pybossa
fd87953c067a94ae211cd8771d4eead130ef3c64
pybossa/view/admin.py
python
update_category
(id)
Update a category.
Update a category.
[ "Update", "a", "category", "." ]
def update_category(id): """Update a category.""" try: category = project_repo.get_category(id) if category: ensure_authorized_to('update', category) form = CategoryForm(obj=category) form.populate_obj(category) if request.method == 'GET': response = dict(template='admin/update_category.html', title=gettext('Update Category'), category=category, form=form) return handle_content_type(response) if request.method == 'POST': form = CategoryForm(request.body) if form.validate(): slug = form.name.data.lower().replace(" ", "") new_category = Category(id=form.id.data, name=form.name.data, short_name=slug) project_repo.update_category(new_category) cached_cat.reset() msg = gettext("Category updated") flash(msg, 'success') return redirect_content_type(url_for(".categories")) else: msg = gettext("Please correct the errors") flash(msg, 'success') response = dict(template='admin/update_category.html', title=gettext('Update Category'), category=category, form=form) return handle_content_type(response) else: abort(404) except HTTPException: raise except Exception as e: # pragma: no cover current_app.logger.error(e) return abort(500)
[ "def", "update_category", "(", "id", ")", ":", "try", ":", "category", "=", "project_repo", ".", "get_category", "(", "id", ")", "if", "category", ":", "ensure_authorized_to", "(", "'update'", ",", "category", ")", "form", "=", "CategoryForm", "(", "obj", ...
https://github.com/Scifabric/pybossa/blob/fd87953c067a94ae211cd8771d4eead130ef3c64/pybossa/view/admin.py#L333-L373
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/locations/views.py
python
BaseLocationView.section_url
(self)
return reverse(LocationsListView.urlname, args=[self.domain])
[]
def section_url(self): return reverse(LocationsListView.urlname, args=[self.domain])
[ "def", "section_url", "(", "self", ")", ":", "return", "reverse", "(", "LocationsListView", ".", "urlname", ",", "args", "=", "[", "self", ".", "domain", "]", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/locations/views.py#L171-L172
unsky/focal-loss
f238924eabc566e98d3c72ad1c9c40f72922bc3f
faster_rcnn_mxnet/lib/dataset/pascal_voc.py
python
PascalVOC.load_image_set_index
(self)
return image_set_index
find out which indexes correspond to given image set (train or val) :return:
find out which indexes correspond to given image set (train or val) :return:
[ "find", "out", "which", "indexes", "correspond", "to", "given", "image", "set", "(", "train", "or", "val", ")", ":", "return", ":" ]
def load_image_set_index(self): """ find out which indexes correspond to given image set (train or val) :return: """ image_set_index_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt') assert os.path.exists(image_set_index_file), 'Path does not exist: {}'.format(image_set_index_file) with open(image_set_index_file) as f: image_set_index = [x.strip() for x in f.readlines()] return image_set_index
[ "def", "load_image_set_index", "(", "self", ")", ":", "image_set_index_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_path", ",", "'ImageSets'", ",", "'Main'", ",", "self", ".", "image_set", "+", "'.txt'", ")", "assert", "os", ".", "...
https://github.com/unsky/focal-loss/blob/f238924eabc566e98d3c72ad1c9c40f72922bc3f/faster_rcnn_mxnet/lib/dataset/pascal_voc.py#L61-L70
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/alexa/capabilities.py
python
AlexaPowerLevelController.properties_supported
(self)
return [{"name": "powerLevel"}]
Return what properties this entity supports.
Return what properties this entity supports.
[ "Return", "what", "properties", "this", "entity", "supports", "." ]
def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "powerLevel"}]
[ "def", "properties_supported", "(", "self", ")", ":", "return", "[", "{", "\"name\"", ":", "\"powerLevel\"", "}", "]" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/alexa/capabilities.py#L1145-L1147
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/core/grr_response_core/lib/parsers/config_file.py
python
KeyValueParser.EndKeyField
(self, **_)
[]
def EndKeyField(self, **_): self.key_field = self.field self.field = ""
[ "def", "EndKeyField", "(", "self", ",", "*", "*", "_", ")", ":", "self", ".", "key_field", "=", "self", ".", "field", "self", ".", "field", "=", "\"\"" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/core/grr_response_core/lib/parsers/config_file.py#L297-L299
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/nexml/_nexml.py
python
RNAPolymorphicStateSet.add_member
(self, value)
[]
def add_member(self, value): self.member.append(value)
[ "def", "add_member", "(", "self", ",", "value", ")", ":", "self", ".", "member", ".", "append", "(", "value", ")" ]
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L14824-L14824
kozec/syncthing-gtk
01eeeb9ed485232e145bf39d90142832e1c9751e
syncthing_gtk/daemon.py
python
Daemon.read_config
(self, callback, error_callback=None, *calbackdata)
Asynchronously reads last configuration version from daemon (even if this version is not currently used). Calls callback(config) with data decoded from json on success, error_callback(exception) on failure
Asynchronously reads last configuration version from daemon (even if this version is not currently used). Calls callback(config) with data decoded from json on success, error_callback(exception) on failure
[ "Asynchronously", "reads", "last", "configuration", "version", "from", "daemon", "(", "even", "if", "this", "version", "is", "not", "currently", "used", ")", ".", "Calls", "callback", "(", "config", ")", "with", "data", "decoded", "from", "json", "on", "succ...
def read_config(self, callback, error_callback=None, *calbackdata): """ Asynchronously reads last configuration version from daemon (even if this version is not currently used). Calls callback(config) with data decoded from json on success, error_callback(exception) on failure """ RESTRequest(self, "system/config", callback, error_callback, *calbackdata).start()
[ "def", "read_config", "(", "self", ",", "callback", ",", "error_callback", "=", "None", ",", "*", "calbackdata", ")", ":", "RESTRequest", "(", "self", ",", "\"system/config\"", ",", "callback", ",", "error_callback", ",", "*", "calbackdata", ")", ".", "start...
https://github.com/kozec/syncthing-gtk/blob/01eeeb9ed485232e145bf39d90142832e1c9751e/syncthing_gtk/daemon.py#L876-L883
glouppe/info8006-introduction-to-ai
8360cc9a8c418559e402be1454ec885b6c1062d7
projects/project2/pacman_module/ghostAgents.py
python
ScaredGhost.getDistribution
(self, state)
return dist
Given a ghost game state, returns a discrete probability distribution over legal moves Arguments: ---------- - `state`: the current game state. See FAQ and class `pacman.GameState`. Return: ------- - A `util.Counter` object which represents a discrete probability distribution over legal moves.
Given a ghost game state, returns a discrete probability distribution over legal moves
[ "Given", "a", "ghost", "game", "state", "returns", "a", "discrete", "probability", "distribution", "over", "legal", "moves" ]
def getDistribution(self, state): """ Given a ghost game state, returns a discrete probability distribution over legal moves Arguments: ---------- - `state`: the current game state. See FAQ and class `pacman.GameState`. Return: ------- - A `util.Counter` object which represents a discrete probability distribution over legal moves. """ dist = util.Counter() legal = state.getLegalActions(self.index) if Directions.STOP in legal: legal.remove(Directions.STOP) pacman_position = state.getPacmanPosition() ghost_current_position = state.getGhostPosition(self.index) current_distance = manhattanDistance( ghost_current_position, pacman_position) for a in legal: succ_state = state.generateSuccessor(self.index, a) ghost_succ_position = succ_state.getGhostPosition(self.index) succ_distance = manhattanDistance( ghost_succ_position, pacman_position) dist[a] = 2**3 if succ_distance >= current_distance else 1 dist.normalize() return dist
[ "def", "getDistribution", "(", "self", ",", "state", ")", ":", "dist", "=", "util", ".", "Counter", "(", ")", "legal", "=", "state", ".", "getLegalActions", "(", "self", ".", "index", ")", "if", "Directions", ".", "STOP", "in", "legal", ":", "legal", ...
https://github.com/glouppe/info8006-introduction-to-ai/blob/8360cc9a8c418559e402be1454ec885b6c1062d7/projects/project2/pacman_module/ghostAgents.py#L147-L178
zerodha/pykiteconnect
3d26164051e97062ee6377016a675cbf83963582
kiteconnect/connect.py
python
KiteConnect.cancel_order
(self, variety, order_id, parent_order_id=None)
return self._delete("order.cancel", url_args={"variety": variety, "order_id": order_id}, params={"parent_order_id": parent_order_id})["order_id"]
Cancel an order.
Cancel an order.
[ "Cancel", "an", "order", "." ]
def cancel_order(self, variety, order_id, parent_order_id=None): """Cancel an order.""" return self._delete("order.cancel", url_args={"variety": variety, "order_id": order_id}, params={"parent_order_id": parent_order_id})["order_id"]
[ "def", "cancel_order", "(", "self", ",", "variety", ",", "order_id", ",", "parent_order_id", "=", "None", ")", ":", "return", "self", ".", "_delete", "(", "\"order.cancel\"", ",", "url_args", "=", "{", "\"variety\"", ":", "variety", ",", "\"order_id\"", ":",...
https://github.com/zerodha/pykiteconnect/blob/3d26164051e97062ee6377016a675cbf83963582/kiteconnect/connect.py#L381-L385
pimoroni/inky
4e1005b9396e5043f08c0cb7ea4c838109ba671d
library/inky/mock.py
python
InkyMock.__init__
(self, colour, h_flip=False, v_flip=False)
Initialise an Inky pHAT Display. :param colour: one of red, black or yellow, default: black
Initialise an Inky pHAT Display.
[ "Initialise", "an", "Inky", "pHAT", "Display", "." ]
def __init__(self, colour, h_flip=False, v_flip=False): """Initialise an Inky pHAT Display. :param colour: one of red, black or yellow, default: black """ global tkinter, ImageTk, Image try: import tkinter except ImportError: raise ImportError('Simulation requires tkinter') try: from PIL import ImageTk, Image except ImportError: raise ImportError('Simulation requires PIL ImageTk and Image') resolution = (self.WIDTH, self.HEIGHT) if resolution not in inky._RESOLUTION.keys(): raise ValueError('Resolution {}x{} not supported!'.format(*resolution)) self.resolution = resolution self.width, self.height = resolution self.cols, self.rows, self.rotation = inky._RESOLUTION[resolution] self.buf = numpy.zeros((self.height, self.width), dtype=numpy.uint8) if colour not in ('red', 'black', 'yellow', 'multi'): raise ValueError('Colour {} is not supported!'.format(colour)) self.colour = colour self.h_flip = h_flip self.v_flip = v_flip impression_palette = [57, 48, 57, # black 255, 255, 255, # white 58, 91, 70, # green 61, 59, 94, # blue 156, 72, 75, # red 208, 190, 71, # yellow 177, 106, 73, # orange 255, 255, 255] # clear bw_inky_palette = [255, 255, 255, # 0 = white 0, 0, 0] # 1 = black red_inky_palette = [255, 255, 255, # 0 = white 0, 0, 0, # 1 = black 255, 0, 0] # index 2 is red ylw_inky_palette = [255, 255, 255, # 0 = white 0, 0, 0, # 1 = black 223, 204, 16] # index 2 is yellow # yellow color value: screen capture from # https://www.thoughtsmakethings.com/Pimoroni-Inky-pHAT self.c_palette = {'black': bw_inky_palette, 'red': red_inky_palette, 'yellow': ylw_inky_palette, 'multi': impression_palette} self._tk_done = False self.tk_root = tkinter.Tk() self.tk_root.title('Inky Preview') self.tk_root.geometry('{}x{}'.format(self.WIDTH, self.HEIGHT)) self.tk_root.aspect(self.WIDTH, self.HEIGHT, self.WIDTH, self.HEIGHT) self.tk_root.protocol('WM_DELETE_WINDOW', self._close_window) self.cv = None self.cvh = self.HEIGHT self.cvw = self.WIDTH
[ "def", "__init__", "(", "self", ",", "colour", ",", "h_flip", "=", "False", ",", "v_flip", "=", "False", ")", ":", "global", "tkinter", ",", "ImageTk", ",", "Image", "try", ":", "import", "tkinter", "except", "ImportError", ":", "raise", "ImportError", "...
https://github.com/pimoroni/inky/blob/4e1005b9396e5043f08c0cb7ea4c838109ba671d/library/inky/mock.py#L12-L84
carla-simulator/scenario_runner
f4d00d88eda4212a1e119515c96281a4be5c234e
srunner/scenariomanager/scenarioatomics/atomic_criteria.py
python
MaxVelocityTest.__init__
(self, actor, max_velocity_allowed, optional=False, name="CheckMaximumVelocity")
Setup actor and maximum allowed velovity
Setup actor and maximum allowed velovity
[ "Setup", "actor", "and", "maximum", "allowed", "velovity" ]
def __init__(self, actor, max_velocity_allowed, optional=False, name="CheckMaximumVelocity"): """ Setup actor and maximum allowed velovity """ super(MaxVelocityTest, self).__init__(name, actor, max_velocity_allowed, None, optional)
[ "def", "__init__", "(", "self", ",", "actor", ",", "max_velocity_allowed", ",", "optional", "=", "False", ",", "name", "=", "\"CheckMaximumVelocity\"", ")", ":", "super", "(", "MaxVelocityTest", ",", "self", ")", ".", "__init__", "(", "name", ",", "actor", ...
https://github.com/carla-simulator/scenario_runner/blob/f4d00d88eda4212a1e119515c96281a4be5c234e/srunner/scenariomanager/scenarioatomics/atomic_criteria.py#L94-L98
behave/behave
e6364fe3d62c2befe34bc56471cfb317a218cd01
behave/fixture.py
python
iscoroutinefunction
(func)
return (getattr(func, "_is_coroutine", False) or (hasattr(inspect, "iscoroutinefunction") and inspect.iscoroutinefunction(func)))
Checks if a function is a coroutine-function, like: * ``async def f(): ...`` (since Python 3.5) * ``@asyncio.coroutine def f(): ...`` (since Python3) .. note:: Compatibility helper Avoids to import :mod:`asyncio` module directly (since Python3), which in turns initializes the :mod:`logging` module as side-effect. :param func: Function to check. :return: True, if function is a coroutine function. False, otherwise.
Checks if a function is a coroutine-function, like:
[ "Checks", "if", "a", "function", "is", "a", "coroutine", "-", "function", "like", ":" ]
def iscoroutinefunction(func): """Checks if a function is a coroutine-function, like: * ``async def f(): ...`` (since Python 3.5) * ``@asyncio.coroutine def f(): ...`` (since Python3) .. note:: Compatibility helper Avoids to import :mod:`asyncio` module directly (since Python3), which in turns initializes the :mod:`logging` module as side-effect. :param func: Function to check. :return: True, if function is a coroutine function. False, otherwise. """ # -- NOTE: inspect.iscoroutinefunction() is available since Python 3.5 # Checks also if @asyncio.coroutine decorator is not used. # pylint: disable=no-member return (getattr(func, "_is_coroutine", False) or (hasattr(inspect, "iscoroutinefunction") and inspect.iscoroutinefunction(func)))
[ "def", "iscoroutinefunction", "(", "func", ")", ":", "# -- NOTE: inspect.iscoroutinefunction() is available since Python 3.5", "# Checks also if @asyncio.coroutine decorator is not used.", "# pylint: disable=no-member", "return", "(", "getattr", "(", "func", ",", "\"_is_coroutine\""...
https://github.com/behave/behave/blob/e6364fe3d62c2befe34bc56471cfb317a218cd01/behave/fixture.py#L90-L110
Amulet-Team/Amulet-Core
a57aeaa4216806401ff35a2dba38782a35abc42e
amulet/api/selection/abstract_selection.py
python
AbstractBaseSelection.__eq__
(self, other)
Is the selection equal to the other selection. >>> selection1 == selection2 True :param other: The other selection to test. :return: True if the selections are the same, False otherwise.
Is the selection equal to the other selection.
[ "Is", "the", "selection", "equal", "to", "the", "other", "selection", "." ]
def __eq__(self, other) -> bool: """ Is the selection equal to the other selection. >>> selection1 == selection2 True :param other: The other selection to test. :return: True if the selections are the same, False otherwise. """ raise NotImplementedError
[ "def", "__eq__", "(", "self", ",", "other", ")", "->", "bool", ":", "raise", "NotImplementedError" ]
https://github.com/Amulet-Team/Amulet-Core/blob/a57aeaa4216806401ff35a2dba38782a35abc42e/amulet/api/selection/abstract_selection.py#L43-L53
pencil1/ApiTestManage
851a54d5629456b7e967e15186244409ddf783cc
app/util/tool_func.py
python
TraverseDict.__init__
(self)
[]
def __init__(self): self.d_list = []
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "d_list", "=", "[", "]" ]
https://github.com/pencil1/ApiTestManage/blob/851a54d5629456b7e967e15186244409ddf783cc/app/util/tool_func.py#L35-L36
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/beetsplug/ftintitle.py
python
contains_feat
(title)
return bool(re.search(plugins.feat_tokens(), title, flags=re.IGNORECASE))
Determine whether the title contains a "featured" marker.
Determine whether the title contains a "featured" marker.
[ "Determine", "whether", "the", "title", "contains", "a", "featured", "marker", "." ]
def contains_feat(title): """Determine whether the title contains a "featured" marker. """ return bool(re.search(plugins.feat_tokens(), title, flags=re.IGNORECASE))
[ "def", "contains_feat", "(", "title", ")", ":", "return", "bool", "(", "re", ".", "search", "(", "plugins", ".", "feat_tokens", "(", ")", ",", "title", ",", "flags", "=", "re", ".", "IGNORECASE", ")", ")" ]
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/beetsplug/ftintitle.py#L42-L45
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/nlp/models/intent_slot_classification/intent_slot_classification_model.py
python
IntentSlotClassificationModel.test_epoch_end
(self, outputs)
return self.validation_epoch_end(outputs)
Called at the end of test to aggregate outputs. :param outputs: list of individual outputs of each test step.
Called at the end of test to aggregate outputs. :param outputs: list of individual outputs of each test step.
[ "Called", "at", "the", "end", "of", "test", "to", "aggregate", "outputs", ".", ":", "param", "outputs", ":", "list", "of", "individual", "outputs", "of", "each", "test", "step", "." ]
def test_epoch_end(self, outputs): """ Called at the end of test to aggregate outputs. :param outputs: list of individual outputs of each test step. """ return self.validation_epoch_end(outputs)
[ "def", "test_epoch_end", "(", "self", ",", "outputs", ")", ":", "return", "self", ".", "validation_epoch_end", "(", "outputs", ")" ]
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/nlp/models/intent_slot_classification/intent_slot_classification_model.py#L329-L334
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/mps/v20190612/mps_client.py
python
MpsClient.DeleteSnapshotByTimeOffsetTemplate
(self, request)
删除用户自定义指定时间点截图模板。 :param request: Request instance for DeleteSnapshotByTimeOffsetTemplate. :type request: :class:`tencentcloud.mps.v20190612.models.DeleteSnapshotByTimeOffsetTemplateRequest` :rtype: :class:`tencentcloud.mps.v20190612.models.DeleteSnapshotByTimeOffsetTemplateResponse`
删除用户自定义指定时间点截图模板。
[ "删除用户自定义指定时间点截图模板。" ]
def DeleteSnapshotByTimeOffsetTemplate(self, request): """删除用户自定义指定时间点截图模板。 :param request: Request instance for DeleteSnapshotByTimeOffsetTemplate. :type request: :class:`tencentcloud.mps.v20190612.models.DeleteSnapshotByTimeOffsetTemplateRequest` :rtype: :class:`tencentcloud.mps.v20190612.models.DeleteSnapshotByTimeOffsetTemplateResponse` """ try: params = request._serialize() body = self.call("DeleteSnapshotByTimeOffsetTemplate", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteSnapshotByTimeOffsetTemplateResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DeleteSnapshotByTimeOffsetTemplate", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DeleteSnapshotByTimeOffsetTemplate\"", ",", "params", ")", "response"...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/mps/v20190612/mps_client.py#L630-L655
openai/imitation
8a2ed905e2ac54bda0f71e5ee364e90568e6d031
policyopt/__init__.py
python
FiniteSpace.size
(self)
return self._size
[]
def size(self): return self._size
[ "def", "size", "(", "self", ")", ":", "return", "self", ".", "_size" ]
https://github.com/openai/imitation/blob/8a2ed905e2ac54bda0f71e5ee364e90568e6d031/policyopt/__init__.py#L23-L23
explosion/spaCy
a784b12eff48df9281b184cb7005e66bbd2e3aca
spacy/language.py
python
Language.pipe_names
(self)
return SimpleFrozenList(names, error=Errors.E926.format(attr="pipe_names"))
Get names of available active pipeline components. RETURNS (List[str]): List of component name strings, in order.
Get names of available active pipeline components.
[ "Get", "names", "of", "available", "active", "pipeline", "components", "." ]
def pipe_names(self) -> List[str]: """Get names of available active pipeline components. RETURNS (List[str]): List of component name strings, in order. """ names = [pipe_name for pipe_name, _ in self.pipeline] return SimpleFrozenList(names, error=Errors.E926.format(attr="pipe_names"))
[ "def", "pipe_names", "(", "self", ")", "->", "List", "[", "str", "]", ":", "names", "=", "[", "pipe_name", "for", "pipe_name", ",", "_", "in", "self", ".", "pipeline", "]", "return", "SimpleFrozenList", "(", "names", ",", "error", "=", "Errors", ".", ...
https://github.com/explosion/spaCy/blob/a784b12eff48df9281b184cb7005e66bbd2e3aca/spacy/language.py#L335-L341
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
haproxy/datadog_checks/haproxy/legacy/haproxy.py
python
HAProxyCheckLegacy._decode_response
(response)
[]
def _decode_response(response): # it only needs additional decoding in py3, so skip it if it's py2 if PY2: return response.content.splitlines() else: content = response.content # If the content is a string, it can't be decoded again # But if it's bytes, it can be decoded. # So, check if it has the decode method decode_fn = getattr(content, "decode", None) if callable(decode_fn): content = content.decode('utf-8') return content.splitlines()
[ "def", "_decode_response", "(", "response", ")", ":", "# it only needs additional decoding in py3, so skip it if it's py2", "if", "PY2", ":", "return", "response", ".", "content", ".", "splitlines", "(", ")", "else", ":", "content", "=", "response", ".", "content", ...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/haproxy/datadog_checks/haproxy/legacy/haproxy.py#L117-L131
microsoft/NimbusML
f6be39ce9359786976429bab0ccd837e849b4ba5
src/python/nimbusml/internal/entrypoints/models_binaryensemble.py
python
models_binaryensemble
( models, predictor_model=None, model_combiner='Median', validate_pipelines=True, **params)
return entrypoint
**Description** Combine binary classifiers into an ensemble :param models: The models to combine into an ensemble (inputs). :param model_combiner: The combiner used to combine the scores (inputs). :param validate_pipelines: Whether to validate that all the pipelines are identical (inputs). :param predictor_model: The trained model (outputs).
**Description** Combine binary classifiers into an ensemble
[ "**", "Description", "**", "Combine", "binary", "classifiers", "into", "an", "ensemble" ]
def models_binaryensemble( models, predictor_model=None, model_combiner='Median', validate_pipelines=True, **params): """ **Description** Combine binary classifiers into an ensemble :param models: The models to combine into an ensemble (inputs). :param model_combiner: The combiner used to combine the scores (inputs). :param validate_pipelines: Whether to validate that all the pipelines are identical (inputs). :param predictor_model: The trained model (outputs). """ entrypoint_name = 'Models.BinaryEnsemble' inputs = {} outputs = {} if models is not None: inputs['Models'] = try_set( obj=models, none_acceptable=False, is_of_type=list) if model_combiner is not None: inputs['ModelCombiner'] = try_set( obj=model_combiner, none_acceptable=True, is_of_type=str, values=[ 'Median', 'Average', 'Vote']) if validate_pipelines is not None: inputs['ValidatePipelines'] = try_set( obj=validate_pipelines, none_acceptable=True, is_of_type=bool) if predictor_model is not None: outputs['PredictorModel'] = try_set( obj=predictor_model, none_acceptable=False, is_of_type=str) input_variables = { x for x in unlist(inputs.values()) if isinstance(x, str) and x.startswith("$")} output_variables = { x for x in unlist(outputs.values()) if isinstance(x, str) and x.startswith("$")} entrypoint = EntryPoint( name=entrypoint_name, inputs=inputs, outputs=outputs, input_variables=input_variables, output_variables=output_variables) return entrypoint
[ "def", "models_binaryensemble", "(", "models", ",", "predictor_model", "=", "None", ",", "model_combiner", "=", "'Median'", ",", "validate_pipelines", "=", "True", ",", "*", "*", "params", ")", ":", "entrypoint_name", "=", "'Models.BinaryEnsemble'", "inputs", "=",...
https://github.com/microsoft/NimbusML/blob/f6be39ce9359786976429bab0ccd837e849b4ba5/src/python/nimbusml/internal/entrypoints/models_binaryensemble.py#L11-L65
allegro/ralph
1e4a9e1800d5f664abaef2624b8bf7512df279ce
src/ralph/lib/permissions/models.py
python
PermByFieldMixin.allowed_fields
(cls, user, action='change')
return result
Returns a list with the names of the fields to which the user has permission. :Example: >> user = User.objects.get(username='root') >> model.allowed_fields(user, 'change') ['parent', 'remarks', 'service_env'] :param user: User object :type user: django User object :param action: permission action (change/view) :type action: str :return: List of field names :rtype: list
Returns a list with the names of the fields to which the user has permission.
[ "Returns", "a", "list", "with", "the", "names", "of", "the", "fields", "to", "which", "the", "user", "has", "permission", "." ]
def allowed_fields(cls, user, action='change'): """ Returns a list with the names of the fields to which the user has permission. :Example: >> user = User.objects.get(username='root') >> model.allowed_fields(user, 'change') ['parent', 'remarks', 'service_env'] :param user: User object :type user: django User object :param action: permission action (change/view) :type action: str :return: List of field names :rtype: list """ result = set() blacklist = cls._permissions.blacklist for field in (cls._meta.fields + cls._meta.many_to_many): if ( field.name not in blacklist and cls.has_access_to_field(field.name, user, action) ): result.add(field.name) # If the user does not have rights to view, # but has the right to change he can view the field if action == 'view': result |= cls.allowed_fields(user, 'change') return result
[ "def", "allowed_fields", "(", "cls", ",", "user", ",", "action", "=", "'change'", ")", ":", "result", "=", "set", "(", ")", "blacklist", "=", "cls", ".", "_permissions", ".", "blacklist", "for", "field", "in", "(", "cls", ".", "_meta", ".", "fields", ...
https://github.com/allegro/ralph/blob/1e4a9e1800d5f664abaef2624b8bf7512df279ce/src/ralph/lib/permissions/models.py#L227-L259
Arachnid/bloggart
ba2b60417102fe14a77b1bcd809b9b801d3a96e2
lib/docutils/statemachine.py
python
State.runtime_init
(self)
Initialize this `State` before running the state machine; called from `self.state_machine.run()`.
Initialize this `State` before running the state machine; called from `self.state_machine.run()`.
[ "Initialize", "this", "State", "before", "running", "the", "state", "machine", ";", "called", "from", "self", ".", "state_machine", ".", "run", "()", "." ]
def runtime_init(self): """ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. """ pass
[ "def", "runtime_init", "(", "self", ")", ":", "pass" ]
https://github.com/Arachnid/bloggart/blob/ba2b60417102fe14a77b1bcd809b9b801d3a96e2/lib/docutils/statemachine.py#L595-L600
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/splitter.py
python
SplitInfo.__init__
(self, sitename=consts.GUEST, best_fid=None, best_bid=None, sum_grad=0, sum_hess=0, gain=None, missing_dir=1, mask_id=None, sample_count=-1)
[]
def __init__(self, sitename=consts.GUEST, best_fid=None, best_bid=None, sum_grad=0, sum_hess=0, gain=None, missing_dir=1, mask_id=None, sample_count=-1): self.sitename = sitename self.best_fid = best_fid self.best_bid = best_bid self.sum_grad = sum_grad self.sum_hess = sum_hess self.gain = gain self.missing_dir = missing_dir self.mask_id = mask_id self.sample_count = sample_count
[ "def", "__init__", "(", "self", ",", "sitename", "=", "consts", ".", "GUEST", ",", "best_fid", "=", "None", ",", "best_bid", "=", "None", ",", "sum_grad", "=", "0", ",", "sum_hess", "=", "0", ",", "gain", "=", "None", ",", "missing_dir", "=", "1", ...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/splitter.py#L42-L53
gpodder/gpodder
40fd34b14ab0127ed4263f86ce15d379d0114968
tools/mac-osx/make_cert_pem.py
python
get_certs
(openssl)
extract System's certificates then filter them by validity and return a list of text of valid certs
extract System's certificates then filter them by validity and return a list of text of valid certs
[ "extract", "System", "s", "certificates", "then", "filter", "them", "by", "validity", "and", "return", "a", "list", "of", "text", "of", "valid", "certs" ]
def get_certs(openssl): """ extract System's certificates then filter them by validity and return a list of text of valid certs """ cmd = ["security", "find-certificate", "-a", "-p", "/System/Library/Keychains/SystemRootCertificates.keychain"] cert_re = re.compile(b"^-----BEGIN CERTIFICATE-----$" + b".+?" + b"^-----END CERTIFICATE-----$", re.M | re.S) try: certs_str = subprocess.check_output(cmd) all_certs = cert_re.findall(certs_str) print("I: extracted %i certificates" % len(all_certs)) valid_certs = [cert for cert in all_certs if is_valid_cert(openssl, cert)] print("I: of which %i are valid certificates" % len(valid_certs)) return valid_certs except OSError: print("E: extracting certificates using %r" % cmd) traceback.print_exc() except CalledProcessError as err: print(("E: extracting certificates using %r, exit=%i" % (cmd, err.returncode)))
[ "def", "get_certs", "(", "openssl", ")", ":", "cmd", "=", "[", "\"security\"", ",", "\"find-certificate\"", ",", "\"-a\"", ",", "\"-p\"", ",", "\"/System/Library/Keychains/SystemRootCertificates.keychain\"", "]", "cert_re", "=", "re", ".", "compile", "(", "b\"^-----...
https://github.com/gpodder/gpodder/blob/40fd34b14ab0127ed4263f86ce15d379d0114968/tools/mac-osx/make_cert_pem.py#L28-L51
INK-USC/KagNet
b386661ac5841774b9d17cc132e991a7bef3c5ef
models/csqa_dataset.py
python
data_with_graphs.__init__
(self, statement_json_file, graph_ngx_file, pretrained_sent_vecs, num_choice=5, start=0, end=None, reload=True)
[]
def __init__(self, statement_json_file, graph_ngx_file, pretrained_sent_vecs, num_choice=5, start=0, end=None, reload=True): self.qids = [] self.statements = [] self.correct_labels = [] statement_json_data = [] print("loading statements from %s" % statement_json_file) with open(statement_json_file, "r") as fp: for line in fp.readlines(): statement_data = json.loads(line.strip()) statement_json_data.append(statement_data) print("Done!") print("loading sent_vecs from %s" % pretrained_sent_vecs) self.input_sent_vecs = np.load(pretrained_sent_vecs) print("Done!") self.qa_text = [] statement_id = 0 # load all statements for question_id in range(len(statement_json_data)): statements = [] qa_text_cur = [] self.qids.append([statement_json_data[question_id]["id"]]) for k, s in enumerate(statement_json_data[question_id]["statements"]): assert len(statement_json_data[question_id]["statements"]) == num_choice # 5 qa_text_cur.append((s["statement"], s['label'])) if s["label"] is True: # true of false self.correct_labels.append(k) # the truth id [0,1,2,3,4] statements.append(self.input_sent_vecs[statement_id]) statement_id += 1 self.statements.append(np.array(statements)) self.qa_text.append(qa_text_cur) self.nxgs = [] self.dgs = [] start_time = timeit.default_timer() print("loading paths from %s" % graph_ngx_file) with open(graph_ngx_file, 'r') as fr: for line in fr.readlines(): line = line.strip() self.nxgs.append(line) print('\t Done! Time: ', "{0:.2f} sec".format(float(timeit.default_timer() - start_time))) save_file = graph_ngx_file + ".dgl.pk" if reload and os.path.exists(save_file): import gc print("loading pickle for the dgl", save_file) start_time = timeit.default_timer() with open(save_file, 'rb') as handle: gc.disable() self.dgs = pickle.load(handle) gc.enable() print("finished loading in %.3f secs" % (float(timeit.default_timer() - start_time))) else: for index, nxg_str in tqdm(enumerate(self.nxgs), total=len(self.nxgs)): nxg = nx.node_link_graph(json.loads(nxg_str)) dg = dgl.DGLGraph(multigraph=True) # dg.from_networkx(nxg, edge_attrs=["rel"]) dg.from_networkx(nxg) cids = [nxg.nodes[n_id]['cid']+1 for n_id in range(len(dg))] # -1 --> 0 and 0 stands for a palceholder concept # rel_types = [nxg.edges[u, v, r]["rel"] + 1 for u, v, r in nxg.edges] # 0 is used for # print(line) # node_types = [mapping_type[nxg.nodes[n_id]['type']] for n_id in range(len(dg))] # edge_weights = [nxg.edges[u, v].get("weight", 0.0) for u, v in nxg.edges] # -1 is used for the unk edges # dg.edata.update({'weights': torch.FloatTensor(edge_weights)}) # dg.edata.update({'rel_types': torch.LongTensor(rel_types)}) dg.ndata.update({'cncpt_ids': torch.LongTensor(cids)}) self.dgs.append(dg) save_file = graph_ngx_file + ".dgl.pk" print("saving pickle for the dgl", save_file) with open(save_file, 'wb') as handle: pickle.dump(self.dgs, handle, protocol=pickle.HIGHEST_PROTOCOL) # self.qa_pair_data = list(zip(*(iter(self.qa_pair_data),) * num_choice)) self.nxgs = list(zip(*(iter(self.nxgs),) * num_choice)) self.dgs = list(zip(*(iter(self.dgs),) * num_choice)) # slicing dataset self.statements = self.statements[start:end] self.correct_labels = self.correct_labels[start:end] self.qids = self.qids[start:end] self.nxgs = self.nxgs[start:end] self.dgs = self.dgs[start:end] assert len(self.statements) == len(self.correct_labels) == len(self.qids) self.n_samples = len(self.statements)
[ "def", "__init__", "(", "self", ",", "statement_json_file", ",", "graph_ngx_file", ",", "pretrained_sent_vecs", ",", "num_choice", "=", "5", ",", "start", "=", "0", ",", "end", "=", "None", ",", "reload", "=", "True", ")", ":", "self", ".", "qids", "=", ...
https://github.com/INK-USC/KagNet/blob/b386661ac5841774b9d17cc132e991a7bef3c5ef/models/csqa_dataset.py#L136-L233
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
vta/python/vta/top/op.py
python
compute_clip_vta
(attrs, inputs, output_type)
return [x]
Clip operator.
Clip operator.
[ "Clip", "operator", "." ]
def compute_clip_vta(attrs, inputs, output_type): """Clip operator.""" x = inputs[0] a_min = attrs.a_min a_max = attrs.a_max const_min = tvm.tir.const(a_min, x.dtype) const_max = tvm.tir.const(a_max, x.dtype) with tvm.te.tag_scope(topi.tag.ELEMWISE): x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name="clipA") x = te.compute(x.shape, lambda *i: tvm.te.max(x(*i), const_min), name="clipB") return [x]
[ "def", "compute_clip_vta", "(", "attrs", ",", "inputs", ",", "output_type", ")", ":", "x", "=", "inputs", "[", "0", "]", "a_min", "=", "attrs", ".", "a_min", "a_max", "=", "attrs", ".", "a_max", "const_min", "=", "tvm", ".", "tir", ".", "const", "(",...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/vta/python/vta/top/op.py#L43-L53
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
research/object_detection/meta_architectures/faster_rcnn_meta_arch.py
python
FasterRCNNKerasFeatureExtractor.preprocess
(self, resized_inputs)
Feature-extractor specific preprocessing (minus image resizing).
Feature-extractor specific preprocessing (minus image resizing).
[ "Feature", "-", "extractor", "specific", "preprocessing", "(", "minus", "image", "resizing", ")", "." ]
def preprocess(self, resized_inputs): """Feature-extractor specific preprocessing (minus image resizing).""" pass
[ "def", "preprocess", "(", "self", ",", "resized_inputs", ")", ":", "pass" ]
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py#L249-L251
weewx/weewx
cb594fce224560bd8696050fc5c7843c7839320e
bin/weewx/accum.py
python
FirstLastAccum.getStatsTuple
(self)
return self.first, self.firsttime, self.last, self.lasttime
Return a stats-tuple. That is, a tuple containing the gathered statistics. This tuple can be used to update the stats database
Return a stats-tuple. That is, a tuple containing the gathered statistics. This tuple can be used to update the stats database
[ "Return", "a", "stats", "-", "tuple", ".", "That", "is", "a", "tuple", "containing", "the", "gathered", "statistics", ".", "This", "tuple", "can", "be", "used", "to", "update", "the", "stats", "database" ]
def getStatsTuple(self): """Return a stats-tuple. That is, a tuple containing the gathered statistics. This tuple can be used to update the stats database""" return self.first, self.firsttime, self.last, self.lasttime
[ "def", "getStatsTuple", "(", "self", ")", ":", "return", "self", ".", "first", ",", "self", ".", "firsttime", ",", "self", ".", "last", ",", "self", ".", "lasttime" ]
https://github.com/weewx/weewx/blob/cb594fce224560bd8696050fc5c7843c7839320e/bin/weewx/accum.py#L363-L366
jwlodek/py_cui
bc2de6a30cfc894348306531db94d7edbdbf17f3
py_cui/ui.py
python
TextBoxImplementation.get
(self)
return self._text
Gets value of the text in the textbox Returns ------- text : str The current textbox test
Gets value of the text in the textbox
[ "Gets", "value", "of", "the", "text", "in", "the", "textbox" ]
def get(self) -> str: """Gets value of the text in the textbox Returns ------- text : str The current textbox test """ return self._text
[ "def", "get", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_text" ]
https://github.com/jwlodek/py_cui/blob/bc2de6a30cfc894348306531db94d7edbdbf17f3/py_cui/ui.py#L571-L580
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/gui/qt_files/QVTKRenderWindowInteractor.py
python
QVTKRenderWindowInteractor.ShowCursor
(self)
Shows the cursor.
Shows the cursor.
[ "Shows", "the", "cursor", "." ]
def ShowCursor(self): """Shows the cursor.""" vtk_cursor = self._Iren.GetRenderWindow().GetCurrentCursor() qt_cursor = self._CURSOR_MAP.get(vtk_cursor, Qt.ArrowCursor) self.setCursor(qt_cursor)
[ "def", "ShowCursor", "(", "self", ")", ":", "vtk_cursor", "=", "self", ".", "_Iren", ".", "GetRenderWindow", "(", ")", ".", "GetCurrentCursor", "(", ")", "qt_cursor", "=", "self", ".", "_CURSOR_MAP", ".", "get", "(", "vtk_cursor", ",", "Qt", ".", "ArrowC...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/gui/qt_files/QVTKRenderWindowInteractor.py#L286-L290
idapython/src
839d93ac969bc1a152982464907445bc0d18a1f8
python/idc.py
python
expand_struc
(sid, offset, delta, recalc)
return ida_struct.expand_struc(s, offset, delta, recalc)
Expand or shrink a structure type @param id: structure type ID @param offset: offset in the structure @param delta: how many bytes to add or remove @param recalc: recalculate the locations where the structure type is used @return: != 0 - ok
Expand or shrink a structure type
[ "Expand", "or", "shrink", "a", "structure", "type" ]
def expand_struc(sid, offset, delta, recalc): """ Expand or shrink a structure type @param id: structure type ID @param offset: offset in the structure @param delta: how many bytes to add or remove @param recalc: recalculate the locations where the structure type is used @return: != 0 - ok """ s = ida_struct.get_struc(sid) if not s: return 0 return ida_struct.expand_struc(s, offset, delta, recalc)
[ "def", "expand_struc", "(", "sid", ",", "offset", ",", "delta", ",", "recalc", ")", ":", "s", "=", "ida_struct", ".", "get_struc", "(", "sid", ")", "if", "not", "s", ":", "return", "0", "return", "ida_struct", ".", "expand_struc", "(", "s", ",", "off...
https://github.com/idapython/src/blob/839d93ac969bc1a152982464907445bc0d18a1f8/python/idc.py#L4004-L4018
dbt-labs/dbt-core
e943b9fc842535e958ef4fd0b8703adc91556bc6
core/dbt/tracking.py
python
TimeoutEmitter.handle_failure
(num_ok, unsent)
[]
def handle_failure(num_ok, unsent): # num_ok will always be 0, unsent will always be 1 entry long, because # the buffer is length 1, so not much to talk about fire_event(DisableTracking()) disable_tracking()
[ "def", "handle_failure", "(", "num_ok", ",", "unsent", ")", ":", "# num_ok will always be 0, unsent will always be 1 entry long, because", "# the buffer is length 1, so not much to talk about", "fire_event", "(", "DisableTracking", "(", ")", ")", "disable_tracking", "(", ")" ]
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/tracking.py#L54-L58
GoogleCloudPlatform/gsutil
5be882803e76608e2fd29cf8c504ccd1fe0a7746
gslib/utils/parallelism_framework_util.py
python
CheckMultiprocessingAvailableAndInit
(logger=None)
return MultiprocessingIsAvailableResult( is_available=_cached_multiprocessing_is_available, stack_trace=_cached_multiprocessing_check_stack_trace)
Checks if multiprocessing is available, and if so performs initialization. There are some environments in which there is no way to use multiprocessing logic that's built into Python (e.g., if /dev/shm is not available, then we can't create semaphores). This simply tries out a few things that will be needed to make sure the environment can support the pieces of the multiprocessing module that we need. See gslib.command.InitializeMultiprocessingVariables for an explanation of why this is necessary. Args: logger: (logging.Logger) Logger to use for debug output. Returns: (MultiprocessingIsAvailableResult) A namedtuple with the following attrs: - multiprocessing_is_available: True iff the multiprocessing module is available for use. - stack_trace: The stack trace generated by the call we tried that failed.
Checks if multiprocessing is available, and if so performs initialization.
[ "Checks", "if", "multiprocessing", "is", "available", "and", "if", "so", "performs", "initialization", "." ]
def CheckMultiprocessingAvailableAndInit(logger=None): """Checks if multiprocessing is available, and if so performs initialization. There are some environments in which there is no way to use multiprocessing logic that's built into Python (e.g., if /dev/shm is not available, then we can't create semaphores). This simply tries out a few things that will be needed to make sure the environment can support the pieces of the multiprocessing module that we need. See gslib.command.InitializeMultiprocessingVariables for an explanation of why this is necessary. Args: logger: (logging.Logger) Logger to use for debug output. Returns: (MultiprocessingIsAvailableResult) A namedtuple with the following attrs: - multiprocessing_is_available: True iff the multiprocessing module is available for use. - stack_trace: The stack trace generated by the call we tried that failed. """ # pylint: disable=global-variable-undefined global _cached_multiprocessing_is_available global _cached_multiprocessing_check_stack_trace global _cached_multiprocessing_is_available_message if _cached_multiprocessing_is_available is not None: if logger: logger.debug(_cached_multiprocessing_check_stack_trace) logger.warn(_cached_multiprocessing_is_available_message) return MultiprocessingIsAvailableResult( is_available=_cached_multiprocessing_is_available, stack_trace=_cached_multiprocessing_check_stack_trace) should_prohibit_multiprocessing, os_name = ShouldProhibitMultiprocessing() if should_prohibit_multiprocessing: message = """ Multiple processes are not supported on %s. Operations requesting parallelism will be executed with multiple threads in a single process only. """ % os_name if logger: logger.warn(message) return MultiprocessingIsAvailableResult(is_available=False, stack_trace=None) stack_trace = None multiprocessing_is_available = True message = """ You have requested multiple processes for an operation, but the required functionality of Python\'s multiprocessing module is not available. Operations requesting parallelism will be executed with multiple threads in a single process only. """ try: # Fails if /dev/shm (or some equivalent thereof) is not available for use # (e.g., there's no implementation, or we can't write to it, etc.). try: multiprocessing_context.Value('i', 0) except: message += """ Please ensure that you have write access to both /dev/shm and /run/shm. """ raise # We'll handle this in one place below. global top_level_manager # pylint: disable=global-variable-undefined top_level_manager = multiprocessing_context.Manager() # Check that the max number of open files is reasonable. Always check this # after we're sure that the basic multiprocessing functionality is # available, since this won't matter unless that's true. limit = -1 if _HAS_RESOURCE_MODULE: # Try to set this with both resource names - RLIMIT_NOFILE for most Unix # platforms, and RLIMIT_OFILE for BSD. Ignore AttributeError because the # "resource" module is not guaranteed to know about these names. try: limit = max( limit, _IncreaseSoftLimitForResource( resource.RLIMIT_NOFILE, constants.MIN_ACCEPTABLE_OPEN_FILES_LIMIT)) except AttributeError: pass try: limit = max( limit, _IncreaseSoftLimitForResource( resource.RLIMIT_OFILE, constants.MIN_ACCEPTABLE_OPEN_FILES_LIMIT)) except AttributeError: pass if limit < constants.MIN_ACCEPTABLE_OPEN_FILES_LIMIT: message += (""" Your max number of open files, %s, is too low to allow safe multiprocessing. On Linux you can fix this by adding something like "ulimit -n 10000" to your ~/.bashrc or equivalent file and opening a new terminal. On macOS, you may also need to run a command like this once (in addition to the above instructions), which might require a restart of your system to take effect: launchctl limit maxfiles 10000 Alternatively, edit /etc/launchd.conf with something like: limit maxfiles 10000 10000 """ % limit) raise Exception('Max number of open files, %s, is too low.' % limit) except: # pylint: disable=bare-except stack_trace = traceback.format_exc() multiprocessing_is_available = False if logger is not None: logger.debug(stack_trace) logger.warn(message) # Set the cached values so that we never need to do this check again. _cached_multiprocessing_is_available = multiprocessing_is_available _cached_multiprocessing_check_stack_trace = stack_trace _cached_multiprocessing_is_available_message = message return MultiprocessingIsAvailableResult( is_available=_cached_multiprocessing_is_available, stack_trace=_cached_multiprocessing_check_stack_trace)
[ "def", "CheckMultiprocessingAvailableAndInit", "(", "logger", "=", "None", ")", ":", "# pylint: disable=global-variable-undefined", "global", "_cached_multiprocessing_is_available", "global", "_cached_multiprocessing_check_stack_trace", "global", "_cached_multiprocessing_is_available_mes...
https://github.com/GoogleCloudPlatform/gsutil/blob/5be882803e76608e2fd29cf8c504ccd1fe0a7746/gslib/utils/parallelism_framework_util.py#L288-L410
blinktrade/bitex
a4896e7faef9c4aa0ca5325f18b77db67003764e
libs/ws4py/manager.py
python
SelectPoller.unregister
(self, fd)
Unregister the given file descriptor.
Unregister the given file descriptor.
[ "Unregister", "the", "given", "file", "descriptor", "." ]
def unregister(self, fd): """ Unregister the given file descriptor. """ if fd in self._fds: self._fds.remove(fd)
[ "def", "unregister", "(", "self", ",", "fd", ")", ":", "if", "fd", "in", "self", ".", "_fds", ":", "self", ".", "_fds", ".", "remove", "(", "fd", ")" ]
https://github.com/blinktrade/bitex/blob/a4896e7faef9c4aa0ca5325f18b77db67003764e/libs/ws4py/manager.py#L80-L85
tetrakai/ssh_client
58e8d17c67ce602aa37c91197dab94a307ee068e
utils.py
python
parse_byte
(data, start_index)
return (start_index + 1, struct.unpack('B', data[start_index])[0])
[]
def parse_byte(data, start_index): return (start_index + 1, struct.unpack('B', data[start_index])[0])
[ "def", "parse_byte", "(", "data", ",", "start_index", ")", ":", "return", "(", "start_index", "+", "1", ",", "struct", ".", "unpack", "(", "'B'", ",", "data", "[", "start_index", "]", ")", "[", "0", "]", ")" ]
https://github.com/tetrakai/ssh_client/blob/58e8d17c67ce602aa37c91197dab94a307ee068e/utils.py#L38-L39
slackapi/python-slack-sdk
2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7
slack_sdk/web/client.py
python
WebClient.usergroups_disable
( self, *, usergroup: str, include_count: Optional[bool] = None, team_id: Optional[str] = None, **kwargs, )
return self.api_call("usergroups.disable", params=kwargs)
Disable an existing User Group https://api.slack.com/methods/usergroups.disable
Disable an existing User Group https://api.slack.com/methods/usergroups.disable
[ "Disable", "an", "existing", "User", "Group", "https", ":", "//", "api", ".", "slack", ".", "com", "/", "methods", "/", "usergroups", ".", "disable" ]
def usergroups_disable( self, *, usergroup: str, include_count: Optional[bool] = None, team_id: Optional[str] = None, **kwargs, ) -> SlackResponse: """Disable an existing User Group https://api.slack.com/methods/usergroups.disable """ kwargs.update( {"usergroup": usergroup, "include_count": include_count, "team_id": team_id} ) return self.api_call("usergroups.disable", params=kwargs)
[ "def", "usergroups_disable", "(", "self", ",", "*", ",", "usergroup", ":", "str", ",", "include_count", ":", "Optional", "[", "bool", "]", "=", "None", ",", "team_id", ":", "Optional", "[", "str", "]", "=", "None", ",", "*", "*", "kwargs", ",", ")", ...
https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/web/client.py#L3887-L3901
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/inspect.py
python
getgeneratorlocals
(generator)
Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.
Get the mapping of generator local variables to their current values.
[ "Get", "the", "mapping", "of", "generator", "local", "variables", "to", "their", "current", "values", "." ]
def getgeneratorlocals(generator): """ Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.""" if not isgenerator(generator): raise TypeError("'{!r}' is not a Python generator".format(generator)) frame = getattr(generator, "gi_frame", None) if frame is not None: return generator.gi_frame.f_locals else: return {}
[ "def", "getgeneratorlocals", "(", "generator", ")", ":", "if", "not", "isgenerator", "(", "generator", ")", ":", "raise", "TypeError", "(", "\"'{!r}' is not a Python generator\"", ".", "format", "(", "generator", ")", ")", "frame", "=", "getattr", "(", "generato...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/inspect.py#L1568-L1582
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/parse/recursivedescent.py
python
RecursiveDescentParser._production_to_tree
(self, production)
return Tree(production.lhs().symbol(), children)
:rtype: Tree :return: The Tree that is licensed by ``production``. In particular, given the production ``[lhs -> elt[1] ... elt[n]]`` return a tree that has a node ``lhs.symbol``, and ``n`` children. For each nonterminal element ``elt[i]`` in the production, the tree token has a childless subtree with node value ``elt[i].symbol``; and for each terminal element ``elt[j]``, the tree token has a leaf token with type ``elt[j]``. :param production: The CFG production that licenses the tree token that should be returned. :type production: Production
:rtype: Tree :return: The Tree that is licensed by ``production``. In particular, given the production ``[lhs -> elt[1] ... elt[n]]`` return a tree that has a node ``lhs.symbol``, and ``n`` children. For each nonterminal element ``elt[i]`` in the production, the tree token has a childless subtree with node value ``elt[i].symbol``; and for each terminal element ``elt[j]``, the tree token has a leaf token with type ``elt[j]``.
[ ":", "rtype", ":", "Tree", ":", "return", ":", "The", "Tree", "that", "is", "licensed", "by", "production", ".", "In", "particular", "given", "the", "production", "[", "lhs", "-", ">", "elt", "[", "1", "]", "...", "elt", "[", "n", "]]", "return", "...
def _production_to_tree(self, production): """ :rtype: Tree :return: The Tree that is licensed by ``production``. In particular, given the production ``[lhs -> elt[1] ... elt[n]]`` return a tree that has a node ``lhs.symbol``, and ``n`` children. For each nonterminal element ``elt[i]`` in the production, the tree token has a childless subtree with node value ``elt[i].symbol``; and for each terminal element ``elt[j]``, the tree token has a leaf token with type ``elt[j]``. :param production: The CFG production that licenses the tree token that should be returned. :type production: Production """ children = [] for elt in production.rhs(): if isinstance(elt, Nonterminal): children.append(Tree(elt.symbol(), [])) else: # This will be matched. children.append(elt) return Tree(production.lhs().symbol(), children)
[ "def", "_production_to_tree", "(", "self", ",", "production", ")", ":", "children", "=", "[", "]", "for", "elt", "in", "production", ".", "rhs", "(", ")", ":", "if", "isinstance", "(", "elt", ",", "Nonterminal", ")", ":", "children", ".", "append", "("...
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/parse/recursivedescent.py#L229-L252
Emptyset110/dHydra
8ec44994ff4dda8bf1ec40e38dd068b757945933
dHydra/Vendor/CtpTraderApi/CtpTraderApi.py
python
RequestInputOrder.check_args
(self)
return True
[]
def check_args(self): # 检查instrument_id参数 if isinstance(self.instrument_id, str): self.instrument_id = self.instrument_id.encode() # 检查direction参数 if self.direction in self.__trader__.direction_map: self.direction = self.__trader__.direction_map[self.direction] elif self.direction not in self.__trader__.direction_map.values(): return ValueError("direction Error: {}".format(self.direction)) # 检查offset_flag参数 if self.offset_flag in self.__trader__.offset_flag_map: self.offset_flag = self.__trader__.offset_flag_map[self.offset_flag] elif self.offset_flag not in self.__trader__.offset_flag_map: return ValueError("offset_flag Error: {}".format(self.offset_flag)) return True
[ "def", "check_args", "(", "self", ")", ":", "# 检查instrument_id参数", "if", "isinstance", "(", "self", ".", "instrument_id", ",", "str", ")", ":", "self", ".", "instrument_id", "=", "self", ".", "instrument_id", ".", "encode", "(", ")", "# 检查direction参数", "if",...
https://github.com/Emptyset110/dHydra/blob/8ec44994ff4dda8bf1ec40e38dd068b757945933/dHydra/Vendor/CtpTraderApi/CtpTraderApi.py#L333-L349
rtqichen/torchdiffeq
5a819e471c15cac5e4ec97a0e472b1569a1a872b
examples/odenet_mnist.py
python
ODEfunc.__init__
(self, dim)
[]
def __init__(self, dim): super(ODEfunc, self).__init__() self.norm1 = norm(dim) self.relu = nn.ReLU(inplace=True) self.conv1 = ConcatConv2d(dim, dim, 3, 1, 1) self.norm2 = norm(dim) self.conv2 = ConcatConv2d(dim, dim, 3, 1, 1) self.norm3 = norm(dim) self.nfe = 0
[ "def", "__init__", "(", "self", ",", "dim", ")", ":", "super", "(", "ODEfunc", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "norm1", "=", "norm", "(", "dim", ")", "self", ".", "relu", "=", "nn", ".", "ReLU", "(", "inplace", "=", "T...
https://github.com/rtqichen/torchdiffeq/blob/5a819e471c15cac5e4ec97a0e472b1569a1a872b/examples/odenet_mnist.py#L94-L102
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/html5lib/_tokenizer.py
python
HTMLTokenizer.__init__
(self, stream, parser=None, **kwargs)
[]
def __init__(self, stream, parser=None, **kwargs): self.stream = HTMLInputStream(stream, **kwargs) self.parser = parser # Setup the initial tokenizer state self.escapeFlag = False self.lastFourChars = [] self.state = self.dataState self.escape = False # The current token being created self.currentToken = None super(HTMLTokenizer, self).__init__()
[ "def", "__init__", "(", "self", ",", "stream", ",", "parser", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "stream", "=", "HTMLInputStream", "(", "stream", ",", "*", "*", "kwargs", ")", "self", ".", "parser", "=", "parser", "# Setup t...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/html5lib/_tokenizer.py#L40-L53
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/gui/base/MarkupParser.py
python
unescape
(string_)
return xml.sax.saxutils.unescape(string_, dic_inv)
replace the values on dic_inv keys with the values
replace the values on dic_inv keys with the values
[ "replace", "the", "values", "on", "dic_inv", "keys", "with", "the", "values" ]
def unescape(string_): '''replace the values on dic_inv keys with the values''' return xml.sax.saxutils.unescape(string_, dic_inv)
[ "def", "unescape", "(", "string_", ")", ":", "return", "xml", ".", "sax", ".", "saxutils", ".", "unescape", "(", "string_", ",", "dic_inv", ")" ]
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/gui/base/MarkupParser.py#L119-L121
liyibo/text-classification-demos
2bc3f56e0eb2b028565881c91db26a589b050db8
bert/run_classifier.py
python
XnliProcessor.__init__
(self)
[]
def __init__(self): self.language = "zh"
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "language", "=", "\"zh\"" ]
https://github.com/liyibo/text-classification-demos/blob/2bc3f56e0eb2b028565881c91db26a589b050db8/bert/run_classifier.py#L193-L194
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/bot/fuzzers/ml/rnn/utils.py
python
validate_model_path
(model_path)
return model_exists
RNN model consists of two files. This validates if they all exist.
RNN model consists of two files. This validates if they all exist.
[ "RNN", "model", "consists", "of", "two", "files", ".", "This", "validates", "if", "they", "all", "exist", "." ]
def validate_model_path(model_path): """RNN model consists of two files. This validates if they all exist.""" model_exists = ( os.path.exists(model_path + constants.MODEL_DATA_SUFFIX) and os.path.exists(model_path + constants.MODEL_INDEX_SUFFIX)) return model_exists
[ "def", "validate_model_path", "(", "model_path", ")", ":", "model_exists", "=", "(", "os", ".", "path", ".", "exists", "(", "model_path", "+", "constants", ".", "MODEL_DATA_SUFFIX", ")", "and", "os", ".", "path", ".", "exists", "(", "model_path", "+", "con...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/bot/fuzzers/ml/rnn/utils.py#L63-L68
ctpbee/ctpbee
c504e141c0a6fb2c5509bb6a77494c592997c0d4
ctpbee/record.py
python
Recorder.get_main_contract_by_code
(self, code: str)
根据code取相应的主力合约
根据code取相应的主力合约
[ "根据code取相应的主力合约" ]
def get_main_contract_by_code(self, code: str): """ 根据code取相应的主力合约 """ d = self.main_contract_mapping.get(code.upper(), None) if not d: return None else: now = sorted(d, key=lambda x: x.open_interest, reverse=True)[0] pre = sorted(d, key=lambda x: x.pre_open_interest, reverse=True)[0] if pre.local_symbol == now.local_symbol: return pre else: return now
[ "def", "get_main_contract_by_code", "(", "self", ",", "code", ":", "str", ")", ":", "d", "=", "self", ".", "main_contract_mapping", ".", "get", "(", "code", ".", "upper", "(", ")", ",", "None", ")", "if", "not", "d", ":", "return", "None", "else", ":...
https://github.com/ctpbee/ctpbee/blob/c504e141c0a6fb2c5509bb6a77494c592997c0d4/ctpbee/record.py#L249-L260
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/explorer/widgets/explorer.py
python
DirView.filter_files
(self, name_filters=None)
Filter files given the defined list of filters.
Filter files given the defined list of filters.
[ "Filter", "files", "given", "the", "defined", "list", "of", "filters", "." ]
def filter_files(self, name_filters=None): """Filter files given the defined list of filters.""" if name_filters is None: name_filters = self.get_conf('name_filters') if self.filter_on: self.fsmodel.setNameFilters(name_filters) else: self.fsmodel.setNameFilters([])
[ "def", "filter_files", "(", "self", ",", "name_filters", "=", "None", ")", ":", "if", "name_filters", "is", "None", ":", "name_filters", "=", "self", ".", "get_conf", "(", "'name_filters'", ")", "if", "self", ".", "filter_on", ":", "self", ".", "fsmodel", ...
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/explorer/widgets/explorer.py#L1428-L1436
xjsender/haoide
717dd706db1169bfc41e818ac6fc6cd9a0aef12d
requests/packages/urllib3/packages/six.py
python
_import_module
(name)
return sys.modules[name]
Import module, returning the module after the last dot.
Import module, returning the module after the last dot.
[ "Import", "module", "returning", "the", "module", "after", "the", "last", "dot", "." ]
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
[ "def", "_import_module", "(", "name", ")", ":", "__import__", "(", "name", ")", "return", "sys", ".", "modules", "[", "name", "]" ]
https://github.com/xjsender/haoide/blob/717dd706db1169bfc41e818ac6fc6cd9a0aef12d/requests/packages/urllib3/packages/six.py#L72-L75
jupyterhub/repo2docker
a37a205c0e8a59240933d20c1c4fb80767e71db2
repo2docker/__main__.py
python
get_argparser
()
return argparser
Get arguments that may be used by repo2docker
Get arguments that may be used by repo2docker
[ "Get", "arguments", "that", "may", "be", "used", "by", "repo2docker" ]
def get_argparser(): """Get arguments that may be used by repo2docker""" argparser = argparse.ArgumentParser( description="Fetch a repository and build a container image" ) argparser.add_argument( "--config", default="repo2docker_config.py", help="Path to config file for repo2docker", ) argparser.add_argument( "--json-logs", default=False, action="store_true", help="Emit JSON logs instead of human readable logs", ) argparser.add_argument( "repo", help=( "Path to repository that should be built. Could be " "local path or a git URL." ), ) argparser.add_argument( "--image-name", help=("Name of image to be built. If unspecified will be " "autogenerated"), type=validate_image_name, ) argparser.add_argument( "--ref", help=( "Reference to build instead of default reference. For example" " branch name or commit for a Git repository." ), ) argparser.add_argument("--debug", help="Turn on debug logging", action="store_true") argparser.add_argument( "--no-build", dest="build", action="store_false", help=( "Do not actually build the image. Useful in conjunction " "with --debug." ), ) argparser.add_argument( "--build-memory-limit", help="Total Memory that can be used by the docker build process", ) argparser.add_argument( "cmd", nargs=argparse.REMAINDER, help="Custom command to run after building container", ) argparser.add_argument( "--no-run", dest="run", action="store_false", help="Do not run container after it has been built", ) argparser.add_argument( "--publish", "-p", dest="ports", action="append", help=( "Specify port mappings for the image. Needs a command to " "run in the container." ), ) argparser.add_argument( "--publish-all", "-P", dest="all_ports", action="store_true", help="Publish all exposed ports to random host ports.", ) argparser.add_argument( "--no-clean", dest="clean", action="store_false", help="Don't clean up remote checkouts after we are done", ) argparser.add_argument( "--push", dest="push", action="store_true", help="Push docker image to repository", ) argparser.add_argument( "--volume", "-v", dest="volumes", action="append", help="Volumes to mount inside the container, in form src:dest", default=[], ) argparser.add_argument( "--user-id", help="User ID of the primary user in the image", type=int ) argparser.add_argument( "--user-name", help="Username of the primary user in the image" ) # Process the environment options the same way that docker does, as # they are passed directly to docker as the environment to use. This # requires a custom action for argparse. argparser.add_argument( "--env", "-e", dest="environment", action=MimicDockerEnvHandling, help="Environment variables to define at container run time", default=[], ) argparser.add_argument( "--editable", "-E", dest="editable", action="store_true", help="Use the local repository in edit mode", ) argparser.add_argument("--target-repo-dir", help=Repo2Docker.target_repo_dir.help) argparser.add_argument("--appendix", type=str, help=Repo2Docker.appendix.help) argparser.add_argument( "--label", dest="labels", action="append", help="Extra label to set on the image, in form name=value", default=[], ) argparser.add_argument( "--build-arg", dest="build_args", action="append", help="Extra build arg to pass to the build process, in form name=value", default=[], ) argparser.add_argument("--subdir", type=str, help=Repo2Docker.subdir.help) argparser.add_argument( "--version", dest="version", action="store_true", help="Print the repo2docker version and exit.", ) argparser.add_argument( "--cache-from", action="append", default=[], help=Repo2Docker.cache_from.help ) argparser.add_argument("--engine", help="Name of the container engine") return argparser
[ "def", "get_argparser", "(", ")", ":", "argparser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Fetch a repository and build a container image\"", ")", "argparser", ".", "add_argument", "(", "\"--config\"", ",", "default", "=", "\"repo2docker_con...
https://github.com/jupyterhub/repo2docker/blob/a37a205c0e8a59240933d20c1c4fb80767e71db2/repo2docker/__main__.py#L63-L238
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/RiskSense/Integrations/RiskSense/RiskSense.py
python
get_unique_open_finding_hr
(unique_open_finding)
return { 'Title': unique_open_finding.get('title', ''), 'Severity': unique_open_finding.get('severity', ''), 'Asset Count': unique_open_finding.get('hostCount', ''), 'Source': unique_open_finding.get('source', ''), 'Source ID': unique_open_finding.get('sourceId', '') }
Prepare open findings dictionary for human readable data. This method is used in 'risksense-get-unique-open-findings' command. :param unique_open_finding: Dictionary representing open host findings. :return: None.
Prepare open findings dictionary for human readable data. This method is used in 'risksense-get-unique-open-findings' command.
[ "Prepare", "open", "findings", "dictionary", "for", "human", "readable", "data", ".", "This", "method", "is", "used", "in", "risksense", "-", "get", "-", "unique", "-", "open", "-", "findings", "command", "." ]
def get_unique_open_finding_hr(unique_open_finding): """ Prepare open findings dictionary for human readable data. This method is used in 'risksense-get-unique-open-findings' command. :param unique_open_finding: Dictionary representing open host findings. :return: None. """ return { 'Title': unique_open_finding.get('title', ''), 'Severity': unique_open_finding.get('severity', ''), 'Asset Count': unique_open_finding.get('hostCount', ''), 'Source': unique_open_finding.get('source', ''), 'Source ID': unique_open_finding.get('sourceId', '') }
[ "def", "get_unique_open_finding_hr", "(", "unique_open_finding", ")", ":", "return", "{", "'Title'", ":", "unique_open_finding", ".", "get", "(", "'title'", ",", "''", ")", ",", "'Severity'", ":", "unique_open_finding", ".", "get", "(", "'severity'", ",", "''", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/RiskSense/Integrations/RiskSense/RiskSense.py#L774-L788
inpanel/inpanel
be53d86a72e30dd5476780ed5ba334315a23004b
lib/pexpect.py
python
spawn.__init__
(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None)
This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example:: child = pexpect.spawn ('/usr/bin/ftp') child = pexpect.spawn ('/usr/bin/ssh user@example.com') child = pexpect.spawn ('ls -latr /tmp') You may also construct it with a list of arguments like so:: child = pexpect.spawn ('/usr/bin/ftp', []) child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com']) child = pexpect.spawn ('ls', ['-latr', '/tmp']) After this the child application will be created and will be ready to talk to. For normal use, see expect() and send() and sendline(). Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell. For example:: child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"') child.expect(pexpect.EOF) The second form of spawn (where you pass a list of arguments) is useful in situations where you wish to spawn a command and pass it its own argument list. This can make syntax more clear. For example, the following is equivalent to the previous example:: shell_cmd = 'ls -l | grep LOG > log_list.txt' child = pexpect.spawn('/bin/bash', ['-c', shell_cmd]) child.expect(pexpect.EOF) The maxread attribute sets the read buffer size. This is maximum number of bytes that Pexpect will try to read from a TTY at one time. Setting the maxread size to 1 will turn off buffering. Setting the maxread value higher may help performance in cases where large amounts of output are read back from the child. This feature is useful in conjunction with searchwindowsize. The searchwindowsize attribute sets the how far back in the incomming seach buffer Pexpect will search for pattern matches. Every time Pexpect reads some data from the child it will append the data to the incomming buffer. The default is to search from the beginning of the imcomming buffer each time new data is read from the child. But this is very inefficient if you are running a command that generates a large amount of data where you want to match The searchwindowsize does not effect the size of the incomming data buffer. You will still have access to the full buffer after expect() returns. The logfile member turns on or off logging. All input and output will be copied to the given file object. Set logfile to None to stop logging. This is the default. Set logfile to sys.stdout to echo everything to standard output. The logfile is flushed after each write. Example log input and output to a file:: child = pexpect.spawn('some_command') fout = file('mylog.txt','w') child.logfile = fout Example log to stdout:: child = pexpect.spawn('some_command') child.logfile = sys.stdout The logfile_read and logfile_send members can be used to separately log the input from the child and output sent to the child. Sometimes you don't want to see everything you write to the child. You only want to log what the child sends back. For example:: child = pexpect.spawn('some_command') child.logfile_read = sys.stdout To separately log output sent to the child use logfile_send:: self.logfile_send = fout The delaybeforesend helps overcome a weird behavior that many users were experiencing. The typical problem was that a user would expect() a "Password:" prompt and then immediately call sendline() to send the password. The user would then see that their password was echoed back to them. Passwords don't normally echo. The problem is caused by the fact that most applications print out the "Password" prompt and then turn off stdin echo, but if you send your password before the application turned off echo, then you get your password echoed. Normally this wouldn't be a problem when interacting with a human at a real keyboard. If you introduce a slight delay just before writing then this seems to clear up the problem. This was such a common problem for many users that I decided that the default pexpect behavior should be to sleep just before writing to the child application. 1/20th of a second (50 ms) seems to be enough to clear up the problem. You can set delaybeforesend to 0 to return to the old behavior. Most Linux machines don't like this to be below 0.03. I don't know why. Note that spawn is clever about finding commands on your path. It uses the same logic that "which" uses to find executables. If you wish to get the exit status of the child you must call the close() method. The exit or signal status of the child will be stored in self.exitstatus or self.signalstatus. If the child exited normally then exitstatus will store the exit return code and signalstatus will be None. If the child was terminated abnormally with a signal then signalstatus will store the signal value and exitstatus will be None. If you need more detail you can also read the self.status member which stores the status returned by os.waitpid. You can interpret this using os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example::
[ "This", "is", "the", "constructor", ".", "The", "command", "parameter", "may", "be", "a", "string", "that", "includes", "a", "command", "and", "any", "arguments", "to", "the", "command", ".", "For", "example", "::" ]
def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None): """This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example:: child = pexpect.spawn ('/usr/bin/ftp') child = pexpect.spawn ('/usr/bin/ssh user@example.com') child = pexpect.spawn ('ls -latr /tmp') You may also construct it with a list of arguments like so:: child = pexpect.spawn ('/usr/bin/ftp', []) child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com']) child = pexpect.spawn ('ls', ['-latr', '/tmp']) After this the child application will be created and will be ready to talk to. For normal use, see expect() and send() and sendline(). Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell. For example:: child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"') child.expect(pexpect.EOF) The second form of spawn (where you pass a list of arguments) is useful in situations where you wish to spawn a command and pass it its own argument list. This can make syntax more clear. For example, the following is equivalent to the previous example:: shell_cmd = 'ls -l | grep LOG > log_list.txt' child = pexpect.spawn('/bin/bash', ['-c', shell_cmd]) child.expect(pexpect.EOF) The maxread attribute sets the read buffer size. This is maximum number of bytes that Pexpect will try to read from a TTY at one time. Setting the maxread size to 1 will turn off buffering. Setting the maxread value higher may help performance in cases where large amounts of output are read back from the child. This feature is useful in conjunction with searchwindowsize. The searchwindowsize attribute sets the how far back in the incomming seach buffer Pexpect will search for pattern matches. Every time Pexpect reads some data from the child it will append the data to the incomming buffer. The default is to search from the beginning of the imcomming buffer each time new data is read from the child. But this is very inefficient if you are running a command that generates a large amount of data where you want to match The searchwindowsize does not effect the size of the incomming data buffer. You will still have access to the full buffer after expect() returns. The logfile member turns on or off logging. All input and output will be copied to the given file object. Set logfile to None to stop logging. This is the default. Set logfile to sys.stdout to echo everything to standard output. The logfile is flushed after each write. Example log input and output to a file:: child = pexpect.spawn('some_command') fout = file('mylog.txt','w') child.logfile = fout Example log to stdout:: child = pexpect.spawn('some_command') child.logfile = sys.stdout The logfile_read and logfile_send members can be used to separately log the input from the child and output sent to the child. Sometimes you don't want to see everything you write to the child. You only want to log what the child sends back. For example:: child = pexpect.spawn('some_command') child.logfile_read = sys.stdout To separately log output sent to the child use logfile_send:: self.logfile_send = fout The delaybeforesend helps overcome a weird behavior that many users were experiencing. The typical problem was that a user would expect() a "Password:" prompt and then immediately call sendline() to send the password. The user would then see that their password was echoed back to them. Passwords don't normally echo. The problem is caused by the fact that most applications print out the "Password" prompt and then turn off stdin echo, but if you send your password before the application turned off echo, then you get your password echoed. Normally this wouldn't be a problem when interacting with a human at a real keyboard. If you introduce a slight delay just before writing then this seems to clear up the problem. This was such a common problem for many users that I decided that the default pexpect behavior should be to sleep just before writing to the child application. 1/20th of a second (50 ms) seems to be enough to clear up the problem. You can set delaybeforesend to 0 to return to the old behavior. Most Linux machines don't like this to be below 0.03. I don't know why. Note that spawn is clever about finding commands on your path. It uses the same logic that "which" uses to find executables. If you wish to get the exit status of the child you must call the close() method. The exit or signal status of the child will be stored in self.exitstatus or self.signalstatus. If the child exited normally then exitstatus will store the exit return code and signalstatus will be None. If the child was terminated abnormally with a signal then signalstatus will store the signal value and exitstatus will be None. If you need more detail you can also read the self.status member which stores the status returned by os.waitpid. You can interpret this using os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """ self.STDIN_FILENO = pty.STDIN_FILENO self.STDOUT_FILENO = pty.STDOUT_FILENO self.STDERR_FILENO = pty.STDERR_FILENO self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.searcher = None self.ignorecase = False self.before = None self.after = None self.match = None self.match_index = None self.terminated = True self.exitstatus = None self.signalstatus = None self.status = None # status returned by os.waitpid self.flag_eof = False self.pid = None self.child_fd = -1 # initially closed self.timeout = timeout self.delimiter = EOF self.logfile = logfile self.logfile_read = None # input from child (read_nonblocking) self.logfile_send = None # output to send (send, sendline) self.maxread = maxread # max bytes to read at one time into buffer self.buffer = '' # This is the read buffer. See maxread. self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms). self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds. self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds. self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds. self.softspace = False # File-like object. self.name = '<' + repr(self) + '>' # File-like object. self.encoding = None # File-like object. self.closed = True # File-like object. self.cwd = cwd self.env = env self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix # Solaris uses internal __fork_pty(). All others use pty.fork(). if (sys.platform.lower().find('solaris')>=0) or (sys.platform.lower().find('sunos5')>=0): self.use_native_pty_fork = False else: self.use_native_pty_fork = True # allow dummy instances for subclasses that may not use command or args. if command is None: self.command = None self.args = None self.name = '<pexpect factory incomplete>' else: self._spawn (command, args)
[ "def", "__init__", "(", "self", ",", "command", ",", "args", "=", "[", "]", ",", "timeout", "=", "30", ",", "maxread", "=", "2000", ",", "searchwindowsize", "=", "None", ",", "logfile", "=", "None", ",", "cwd", "=", "None", ",", "env", "=", "None",...
https://github.com/inpanel/inpanel/blob/be53d86a72e30dd5476780ed5ba334315a23004b/lib/pexpect.py#L267-L429