repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
djungelorm/sphinx-tabs
sphinx_tabs/tabs.py
https://github.com/djungelorm/sphinx-tabs/blob/2f17b5ca82a91613b42d58d01aafbd484525915c/sphinx_tabs/tabs.py#L97-L163
def run(self): """ Parse a tab directive """ self.assert_has_content() env = self.state.document.settings.env tabs_id = env.temp_data['tabs_stack'][-1] tabs_key = 'tabs_%d' % tabs_id args = self.content[0].strip() if args.startswith('{'): try: ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "assert_has_content", "(", ")", "env", "=", "self", ".", "state", ".", "document", ".", "settings", ".", "env", "tabs_id", "=", "env", ".", "temp_data", "[", "'tabs_stack'", "]", "[", "-", "1", "]", ...
Parse a tab directive
[ "Parse", "a", "tab", "directive" ]
python
train
Workiva/furious
furious/batcher.py
https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L141-L157
def to_task(self): """Return a task object representing this MessageProcessor job.""" task_args = self.get_task_args() # check for name in task args name = task_args.get('name', MESSAGE_PROCESSOR_NAME) # if the countdown isn't in the task_args set it to the frequency if...
[ "def", "to_task", "(", "self", ")", ":", "task_args", "=", "self", ".", "get_task_args", "(", ")", "# check for name in task args", "name", "=", "task_args", ".", "get", "(", "'name'", ",", "MESSAGE_PROCESSOR_NAME", ")", "# if the countdown isn't in the task_args set ...
Return a task object representing this MessageProcessor job.
[ "Return", "a", "task", "object", "representing", "this", "MessageProcessor", "job", "." ]
python
train
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1413-L1444
def __update_existing(self, msg, req): """Propagate changes based on type of message. MUST be called within self.__requests lock. Performs additional actions when solicited messages arrive.""" req._messages.append(msg) payload = msg[M_PAYLOAD] if msg[M_TYPE] in _RSP_TYPE_CREA...
[ "def", "__update_existing", "(", "self", ",", "msg", ",", "req", ")", ":", "req", ".", "_messages", ".", "append", "(", "msg", ")", "payload", "=", "msg", "[", "M_PAYLOAD", "]", "if", "msg", "[", "M_TYPE", "]", "in", "_RSP_TYPE_CREATION", ":", "if", ...
Propagate changes based on type of message. MUST be called within self.__requests lock. Performs additional actions when solicited messages arrive.
[ "Propagate", "changes", "based", "on", "type", "of", "message", ".", "MUST", "be", "called", "within", "self", ".", "__requests", "lock", ".", "Performs", "additional", "actions", "when", "solicited", "messages", "arrive", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/abinit/nodes.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/nodes.py#L916-L931
def send_signal(self, signal): """ Send signal from this node to all connected receivers unless the node is in spectator mode. signal -- (hashable) signal value, see `dispatcher` connect for details Return a list of tuple pairs [(receiver, response), ... ] or None if the node i...
[ "def", "send_signal", "(", "self", ",", "signal", ")", ":", "if", "self", ".", "in_spectator_mode", ":", "return", "None", "logger", ".", "debug", "(", "\"Node %s broadcasts signal %s\"", "%", "(", "self", ",", "signal", ")", ")", "dispatcher", ".", "send", ...
Send signal from this node to all connected receivers unless the node is in spectator mode. signal -- (hashable) signal value, see `dispatcher` connect for details Return a list of tuple pairs [(receiver, response), ... ] or None if the node is in spectator mode. if any receiver raise...
[ "Send", "signal", "from", "this", "node", "to", "all", "connected", "receivers", "unless", "the", "node", "is", "in", "spectator", "mode", "." ]
python
train
ptmcg/littletable
littletable.py
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1075-L1085
def join_on(self, attr): """Creates a JoinTerm in preparation for joining with another table, to indicate what attribute should be used in the join. Only indexed attributes may be used in a join. @param attr: attribute name to join from this table (may be different ...
[ "def", "join_on", "(", "self", ",", "attr", ")", ":", "if", "attr", "not", "in", "self", ".", "_indexes", ":", "raise", "ValueError", "(", "\"can only join on indexed attributes\"", ")", "return", "JoinTerm", "(", "self", ",", "attr", ")" ]
Creates a JoinTerm in preparation for joining with another table, to indicate what attribute should be used in the join. Only indexed attributes may be used in a join. @param attr: attribute name to join from this table (may be different from the attribute name in the t...
[ "Creates", "a", "JoinTerm", "in", "preparation", "for", "joining", "with", "another", "table", "to", "indicate", "what", "attribute", "should", "be", "used", "in", "the", "join", ".", "Only", "indexed", "attributes", "may", "be", "used", "in", "a", "join", ...
python
train
bioidiap/gridtk
gridtk/models.py
https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/models.py#L224-L228
def get_command_line(self): """Returns the command line for the job.""" # In python 2, the command line is unicode, which needs to be converted to string before pickling; # In python 3, the command line is bytes, which can be pickled directly return loads(self.command_line) if isinstance(self.command_li...
[ "def", "get_command_line", "(", "self", ")", ":", "# In python 2, the command line is unicode, which needs to be converted to string before pickling;", "# In python 3, the command line is bytes, which can be pickled directly", "return", "loads", "(", "self", ".", "command_line", ")", "...
Returns the command line for the job.
[ "Returns", "the", "command", "line", "for", "the", "job", "." ]
python
train
gem/oq-engine
openquake/hazardlib/gsim/kotha_2019.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kotha_2019.py#L332-L344
def get_site_amplification(self, C, sites): """ Returns the linear site amplification term depending on whether the Vs30 is observed of inferred """ ampl = np.zeros(sites.vs30.shape) # For observed vs30 sites ampl[sites.vs30measured] = (C["d0_obs"] + C["d1_obs"] *...
[ "def", "get_site_amplification", "(", "self", ",", "C", ",", "sites", ")", ":", "ampl", "=", "np", ".", "zeros", "(", "sites", ".", "vs30", ".", "shape", ")", "# For observed vs30 sites", "ampl", "[", "sites", ".", "vs30measured", "]", "=", "(", "C", "...
Returns the linear site amplification term depending on whether the Vs30 is observed of inferred
[ "Returns", "the", "linear", "site", "amplification", "term", "depending", "on", "whether", "the", "Vs30", "is", "observed", "of", "inferred" ]
python
train
gitpython-developers/GitPython
git/objects/submodule/base.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/submodule/base.py#L215-L219
def _sio_modules(cls, parent_commit): """:return: Configuration file as BytesIO - we only access it through the respective blob's data""" sio = BytesIO(parent_commit.tree[cls.k_modules_file].data_stream.read()) sio.name = cls.k_modules_file return sio
[ "def", "_sio_modules", "(", "cls", ",", "parent_commit", ")", ":", "sio", "=", "BytesIO", "(", "parent_commit", ".", "tree", "[", "cls", ".", "k_modules_file", "]", ".", "data_stream", ".", "read", "(", ")", ")", "sio", ".", "name", "=", "cls", ".", ...
:return: Configuration file as BytesIO - we only access it through the respective blob's data
[ ":", "return", ":", "Configuration", "file", "as", "BytesIO", "-", "we", "only", "access", "it", "through", "the", "respective", "blob", "s", "data" ]
python
train
apache/incubator-mxnet
example/gluon/lipnet/utils/preprocess_data.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/preprocess_data.py#L175-L181
def get_video_frames(self, path): """ Get video frames """ videogen = skvideo.io.vreader(path) frames = np.array([frame for frame in videogen]) return frames
[ "def", "get_video_frames", "(", "self", ",", "path", ")", ":", "videogen", "=", "skvideo", ".", "io", ".", "vreader", "(", "path", ")", "frames", "=", "np", ".", "array", "(", "[", "frame", "for", "frame", "in", "videogen", "]", ")", "return", "frame...
Get video frames
[ "Get", "video", "frames" ]
python
train
apache/incubator-heron
heron/tools/tracker/src/python/tracker.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L537-L580
def extract_packing_plan(self, topology): """ Returns the representation of packing plan that will be returned from Tracker. """ packingPlan = { "id": "", "container_plans": [] } if not topology.packing_plan: return packingPlan container_plans = topology.packing_p...
[ "def", "extract_packing_plan", "(", "self", ",", "topology", ")", ":", "packingPlan", "=", "{", "\"id\"", ":", "\"\"", ",", "\"container_plans\"", ":", "[", "]", "}", "if", "not", "topology", ".", "packing_plan", ":", "return", "packingPlan", "container_plans"...
Returns the representation of packing plan that will be returned from Tracker.
[ "Returns", "the", "representation", "of", "packing", "plan", "that", "will", "be", "returned", "from", "Tracker", "." ]
python
valid
mfitzp/padua
padua/io.py
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L188-L203
def write_r(df, f, sep=",", index_join="@", columns_join="."): """ Export dataframe in a format easily importable to R Index fields are joined with "@" and column fields by "." by default. :param df: :param f: :param index_join: :param columns_join: :return: """ df = df.copy() ...
[ "def", "write_r", "(", "df", ",", "f", ",", "sep", "=", "\",\"", ",", "index_join", "=", "\"@\"", ",", "columns_join", "=", "\".\"", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "df", ".", "index", "=", "[", "\"@\"", ".", "join", "(", "[",...
Export dataframe in a format easily importable to R Index fields are joined with "@" and column fields by "." by default. :param df: :param f: :param index_join: :param columns_join: :return:
[ "Export", "dataframe", "in", "a", "format", "easily", "importable", "to", "R" ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L118-L128
def updrive(path): """ Make the drive letter (if any) upper case. This is useful because Windows is inconsistent on the case of the drive letter, which can cause inconsistencies when calculating command signatures. """ drive, rest = os.path.splitdrive(path) if drive: path = drive...
[ "def", "updrive", "(", "path", ")", ":", "drive", ",", "rest", "=", "os", ".", "path", ".", "splitdrive", "(", "path", ")", "if", "drive", ":", "path", "=", "drive", ".", "upper", "(", ")", "+", "rest", "return", "path" ]
Make the drive letter (if any) upper case. This is useful because Windows is inconsistent on the case of the drive letter, which can cause inconsistencies when calculating command signatures.
[ "Make", "the", "drive", "letter", "(", "if", "any", ")", "upper", "case", ".", "This", "is", "useful", "because", "Windows", "is", "inconsistent", "on", "the", "case", "of", "the", "drive", "letter", "which", "can", "cause", "inconsistencies", "when", "cal...
python
train
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L630-L641
def delete_group(self, group_id): """ Remove a group from your team :param group_id: Id of group """ url = self.TEAM_GROUPS_ID_URL % group_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
[ "def", "delete_group", "(", "self", ",", "group_id", ")", ":", "url", "=", "self", ".", "TEAM_GROUPS_ID_URL", "%", "group_id", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",...
Remove a group from your team :param group_id: Id of group
[ "Remove", "a", "group", "from", "your", "team", ":", "param", "group_id", ":", "Id", "of", "group" ]
python
train
juju/python-libjuju
juju/client/connector.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/connector.py#L78-L101
async def connect_controller(self, controller_name=None): """Connect to a controller by name. If the name is empty, it connect to the current controller. """ if not controller_name: controller_name = self.jujudata.current_controller() if not controller_name: ...
[ "async", "def", "connect_controller", "(", "self", ",", "controller_name", "=", "None", ")", ":", "if", "not", "controller_name", ":", "controller_name", "=", "self", ".", "jujudata", ".", "current_controller", "(", ")", "if", "not", "controller_name", ":", "r...
Connect to a controller by name. If the name is empty, it connect to the current controller.
[ "Connect", "to", "a", "controller", "by", "name", ".", "If", "the", "name", "is", "empty", "it", "connect", "to", "the", "current", "controller", "." ]
python
train
quandyfactory/dicttoxml
dicttoxml.py
https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L83-L101
def get_xml_type(val): """Returns the data type for the xml type attribute""" if type(val).__name__ in ('str', 'unicode'): return 'str' if type(val).__name__ in ('int', 'long'): return 'int' if type(val).__name__ == 'float': return 'float' if type(val).__name__ == 'bool': ...
[ "def", "get_xml_type", "(", "val", ")", ":", "if", "type", "(", "val", ")", ".", "__name__", "in", "(", "'str'", ",", "'unicode'", ")", ":", "return", "'str'", "if", "type", "(", "val", ")", ".", "__name__", "in", "(", "'int'", ",", "'long'", ")", ...
Returns the data type for the xml type attribute
[ "Returns", "the", "data", "type", "for", "the", "xml", "type", "attribute" ]
python
train
genialis/resolwe
resolwe/flow/executors/local/run.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/local/run.py#L45-L50
async def run_script(self, script): """Execute the script and save results.""" script = os.linesep.join(['set -x', 'set +B', script, 'exit']) + os.linesep self.proc.stdin.write(script.encode('utf-8')) await self.proc.stdin.drain() self.proc.stdin.close()
[ "async", "def", "run_script", "(", "self", ",", "script", ")", ":", "script", "=", "os", ".", "linesep", ".", "join", "(", "[", "'set -x'", ",", "'set +B'", ",", "script", ",", "'exit'", "]", ")", "+", "os", ".", "linesep", "self", ".", "proc", "."...
Execute the script and save results.
[ "Execute", "the", "script", "and", "save", "results", "." ]
python
train
tempodb/tempodb-python
tempodb/protocol/objects.py
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/protocol/objects.py#L33-L57
def from_json(self, json_text): """Deserialize a JSON object into this object. This method will check that the JSON object has the required keys and will set each of the keys in that JSON object as an instance attribute of this object. :param json_text: the JSON text or object ...
[ "def", "from_json", "(", "self", ",", "json_text", ")", ":", "#due to the architecture of response parsing, particularly", "#where the API returns lists, the JSON might have already been", "#parsed by the time it gets here", "if", "type", "(", "json_text", ")", "in", "[", "str", ...
Deserialize a JSON object into this object. This method will check that the JSON object has the required keys and will set each of the keys in that JSON object as an instance attribute of this object. :param json_text: the JSON text or object to deserialize from :type json_text...
[ "Deserialize", "a", "JSON", "object", "into", "this", "object", ".", "This", "method", "will", "check", "that", "the", "JSON", "object", "has", "the", "required", "keys", "and", "will", "set", "each", "of", "the", "keys", "in", "that", "JSON", "object", ...
python
train
epfl-idevelop/epfl-ldap
epflldap/ldap_authenticate.py
https://github.com/epfl-idevelop/epfl-ldap/blob/bebb94da3609d358bd83f31672eeaddcda872c5d/epflldap/ldap_authenticate.py#L34-L55
def authenticate(self, username, password): """ Authenticate the user with a bind on the LDAP server """ if username is None or password is None: return False # check the username if not re.match("^[A-Za-z0-9_-]*$", username): return False ...
[ "def", "authenticate", "(", "self", ",", "username", ",", "password", ")", ":", "if", "username", "is", "None", "or", "password", "is", "None", ":", "return", "False", "# check the username", "if", "not", "re", ".", "match", "(", "\"^[A-Za-z0-9_-]*$\"", ",",...
Authenticate the user with a bind on the LDAP server
[ "Authenticate", "the", "user", "with", "a", "bind", "on", "the", "LDAP", "server" ]
python
train
astooke/gtimer
gtimer/public/report.py
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/report.py#L22-L86
def report(times=None, include_itrs=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the gre...
[ "def", "report", "(", "times", "=", "None", ",", "include_itrs", "=", "True", ",", "include_stats", "=", "True", ",", "delim_mode", "=", "False", ",", "format_options", "=", "None", ")", ":", "if", "times", "is", "None", ":", "if", "f", ".", "root", ...
Produce a formatted report of the current timing data. Notes: When reporting a collection of parallel subdivisions, only the one with the greatest total time is reported on, and the rest are ignored (no branching). To compare parallel subdivisions use compare(). Args: times (T...
[ "Produce", "a", "formatted", "report", "of", "the", "current", "timing", "data", "." ]
python
train
epfl-lts2/pygsp
pygsp/graphs/graph.py
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L408-L469
def extract_components(self): r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ------- graphs : list A list of graph structures. Each having its own node list and weig...
[ "def", "extract_components", "(", "self", ")", ":", "if", "self", ".", "A", ".", "shape", "[", "0", "]", "!=", "self", ".", "A", ".", "shape", "[", "1", "]", ":", "self", ".", "logger", ".", "error", "(", "'Inconsistent shape to extract components. '", ...
r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ------- graphs : list A list of graph structures. Each having its own node list and weight matrix. If the graph is directed, a...
[ "r", "Split", "the", "graph", "into", "connected", "components", "." ]
python
train
apache/spark
python/pyspark/mllib/regression.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/regression.py#L664-L670
def load(cls, sc, path): """Load an IsotonicRegressionModel.""" java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load( sc._jsc.sc(), path) py_boundaries = _java2py(sc, java_model.boundaryVector()).toArray() py_predictions = _java2py(sc, java_mode...
[ "def", "load", "(", "cls", ",", "sc", ",", "path", ")", ":", "java_model", "=", "sc", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "regression", ".", "IsotonicRegressionModel", ".", "load", "(", "sc", ".", "_jsc", ".", "...
Load an IsotonicRegressionModel.
[ "Load", "an", "IsotonicRegressionModel", "." ]
python
train
eddyxu/cpp-coveralls
cpp_coveralls/coverage.py
https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L113-L127
def create_exclude_rules(args): """Creates the exlude rules """ global _cached_exclude_rules if _cached_exclude_rules is not None: return _cached_exclude_rules rules = [] for excl_path in args.exclude: abspath = os.path.abspath(os.path.join(args.root, excl_path)) rules.ap...
[ "def", "create_exclude_rules", "(", "args", ")", ":", "global", "_cached_exclude_rules", "if", "_cached_exclude_rules", "is", "not", "None", ":", "return", "_cached_exclude_rules", "rules", "=", "[", "]", "for", "excl_path", "in", "args", ".", "exclude", ":", "a...
Creates the exlude rules
[ "Creates", "the", "exlude", "rules" ]
python
train
hubo1016/namedstruct
namedstruct/namedstruct.py
https://github.com/hubo1016/namedstruct/blob/5039026e0df4ce23003d212358918dbe1a6e1d76/namedstruct/namedstruct.py#L579-L595
def packvalue(value, *properties): ''' Store a specified value to specified property path. Often used in nstruct "init" parameter. :param value: a fixed value :param properties: specified field name, same as sizefromlen. :returns: a function which takes a NamedStruct as parameter, and...
[ "def", "packvalue", "(", "value", ",", "*", "properties", ")", ":", "def", "func", "(", "namedstruct", ")", ":", "v", "=", "namedstruct", ".", "_target", "for", "p", "in", "properties", "[", ":", "-", "1", "]", ":", "v", "=", "getattr", "(", "v", ...
Store a specified value to specified property path. Often used in nstruct "init" parameter. :param value: a fixed value :param properties: specified field name, same as sizefromlen. :returns: a function which takes a NamedStruct as parameter, and store the value to property path.
[ "Store", "a", "specified", "value", "to", "specified", "property", "path", ".", "Often", "used", "in", "nstruct", "init", "parameter", ".", ":", "param", "value", ":", "a", "fixed", "value", ":", "param", "properties", ":", "specified", "field", "name", "s...
python
train
wandb/client
wandb/vendor/prompt_toolkit/eventloop/win32.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/win32.py#L97-L103
def _ready_for_reading(self, timeout=None): """ Return the handle that is ready for reading or `None` on timeout. """ handles = [self._event, self._console_input_reader.handle] handles.extend(self._read_fds.keys()) return _wait_for_handles(handles, timeout)
[ "def", "_ready_for_reading", "(", "self", ",", "timeout", "=", "None", ")", ":", "handles", "=", "[", "self", ".", "_event", ",", "self", ".", "_console_input_reader", ".", "handle", "]", "handles", ".", "extend", "(", "self", ".", "_read_fds", ".", "key...
Return the handle that is ready for reading or `None` on timeout.
[ "Return", "the", "handle", "that", "is", "ready", "for", "reading", "or", "None", "on", "timeout", "." ]
python
train
dfm/george
george/modeling.py
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L233-L252
def set_parameter_vector(self, vector, include_frozen=False): """ Set the parameter values to the given vector Args: vector (array[vector_size] or array[full_size]): The target parameter vector. This must be in the same order as ``parameter_names`` an...
[ "def", "set_parameter_vector", "(", "self", ",", "vector", ",", "include_frozen", "=", "False", ")", ":", "v", "=", "self", ".", "parameter_vector", "if", "include_frozen", ":", "v", "[", ":", "]", "=", "vector", "else", ":", "v", "[", "self", ".", "un...
Set the parameter values to the given vector Args: vector (array[vector_size] or array[full_size]): The target parameter vector. This must be in the same order as ``parameter_names`` and it should only include frozen parameters if ``include_frozen`` i...
[ "Set", "the", "parameter", "values", "to", "the", "given", "vector" ]
python
train
waqasbhatti/astrobase
astrobase/checkplot/pkl_png.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_png.py#L1133-L1199
def cp2png(checkplotin, extrarows=None): '''This is just a shortened form of the function above for convenience. This only handles pickle files as input. Parameters ---------- checkplotin : str File name of a checkplot pickle file to convert to a PNG. extrarows : list of tuples ...
[ "def", "cp2png", "(", "checkplotin", ",", "extrarows", "=", "None", ")", ":", "if", "checkplotin", ".", "endswith", "(", "'.gz'", ")", ":", "outfile", "=", "checkplotin", ".", "replace", "(", "'.pkl.gz'", ",", "'.png'", ")", "else", ":", "outfile", "=", ...
This is just a shortened form of the function above for convenience. This only handles pickle files as input. Parameters ---------- checkplotin : str File name of a checkplot pickle file to convert to a PNG. extrarows : list of tuples This is a list of 4-element tuples containing...
[ "This", "is", "just", "a", "shortened", "form", "of", "the", "function", "above", "for", "convenience", "." ]
python
valid
leancloud/python-sdk
leancloud/query.py
https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/query.py#L240-L250
def count(self): """ 返回满足查询条件的对象的数量。 :rtype: int """ params = self.dump() params['limit'] = 0 params['count'] = 1 content = self._do_request(params) return content['count']
[ "def", "count", "(", "self", ")", ":", "params", "=", "self", ".", "dump", "(", ")", "params", "[", "'limit'", "]", "=", "0", "params", "[", "'count'", "]", "=", "1", "content", "=", "self", ".", "_do_request", "(", "params", ")", "return", "conten...
返回满足查询条件的对象的数量。 :rtype: int
[ "返回满足查询条件的对象的数量。" ]
python
train
metavee/batchproc
batchproc/util.py
https://github.com/metavee/batchproc/blob/aa084a2ac8ab7950f7a7d3adb54b0cf010c6a935/batchproc/util.py#L29-L52
def get_file_list(): """Return a list of strings corresponding to file names supplied by drag and drop or standard input.""" if len(sys.argv) > 1: file_list = list(sys.argv[1:]) # make copy else: files_str = input('Select the files you want to process and drag and drop them onto this windo...
[ "def", "get_file_list", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "file_list", "=", "list", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "# make copy", "else", ":", "files_str", "=", "input", "(", "'Select the fi...
Return a list of strings corresponding to file names supplied by drag and drop or standard input.
[ "Return", "a", "list", "of", "strings", "corresponding", "to", "file", "names", "supplied", "by", "drag", "and", "drop", "or", "standard", "input", "." ]
python
train
dereneaton/ipyrad
ipyrad/analysis/tetrad.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1776-L1824
def _filter_clades(clade_counts, cutoff): """ A subfunc of consensus_tree(). Removes clades that occur with freq < cutoff. """ ## store clades that pass filter passed = [] clades = np.array([list(i[0]) for i in clade_counts], dtype=np.int8) counts = np.array([i[1] for i in clade_count...
[ "def", "_filter_clades", "(", "clade_counts", ",", "cutoff", ")", ":", "## store clades that pass filter", "passed", "=", "[", "]", "clades", "=", "np", ".", "array", "(", "[", "list", "(", "i", "[", "0", "]", ")", "for", "i", "in", "clade_counts", "]", ...
A subfunc of consensus_tree(). Removes clades that occur with freq < cutoff.
[ "A", "subfunc", "of", "consensus_tree", "()", ".", "Removes", "clades", "that", "occur", "with", "freq", "<", "cutoff", "." ]
python
valid
PythonCharmers/python-future
src/libfuturize/fixer_util.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixer_util.py#L112-L134
def suitify(parent): """ Turn the stuff after the first colon in parent's children into a suite, if it wasn't already """ for node in parent.children: if node.type == syms.suite: # already in the prefered format, do nothing return # One-liners have no suite node,...
[ "def", "suitify", "(", "parent", ")", ":", "for", "node", "in", "parent", ".", "children", ":", "if", "node", ".", "type", "==", "syms", ".", "suite", ":", "# already in the prefered format, do nothing", "return", "# One-liners have no suite node, we have to fake one ...
Turn the stuff after the first colon in parent's children into a suite, if it wasn't already
[ "Turn", "the", "stuff", "after", "the", "first", "colon", "in", "parent", "s", "children", "into", "a", "suite", "if", "it", "wasn", "t", "already" ]
python
train
MatMaul/pynetgear
pynetgear/__init__.py
https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__init__.py#L348-L402
def _make_request(self, service, method, params=None, body="", need_auth=True): """Make an API request to the router.""" # If we have no cookie (v2) or never called login before (v1) # and we need auth, the request will fail for sure. if need_auth and not self.cooki...
[ "def", "_make_request", "(", "self", ",", "service", ",", "method", ",", "params", "=", "None", ",", "body", "=", "\"\"", ",", "need_auth", "=", "True", ")", ":", "# If we have no cookie (v2) or never called login before (v1)", "# and we need auth, the request will fail...
Make an API request to the router.
[ "Make", "an", "API", "request", "to", "the", "router", "." ]
python
valid
secdev/scapy
scapy/contrib/isotp.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/isotp.py#L1287-L1294
def recv(self, timeout=None): """Receive an ISOTP frame, blocking if none is available in the buffer for at most 'timeout' seconds.""" try: return self.rx_queue.get(timeout is None or timeout > 0, timeout) except queue.Empty: return None
[ "def", "recv", "(", "self", ",", "timeout", "=", "None", ")", ":", "try", ":", "return", "self", ".", "rx_queue", ".", "get", "(", "timeout", "is", "None", "or", "timeout", ">", "0", ",", "timeout", ")", "except", "queue", ".", "Empty", ":", "retur...
Receive an ISOTP frame, blocking if none is available in the buffer for at most 'timeout' seconds.
[ "Receive", "an", "ISOTP", "frame", "blocking", "if", "none", "is", "available", "in", "the", "buffer", "for", "at", "most", "timeout", "seconds", "." ]
python
train
ratcave/wavefront_reader
wavefront_reader/writing.py
https://github.com/ratcave/wavefront_reader/blob/c515164a3952d6b85f8044f429406fddd862bfd0/wavefront_reader/writing.py#L107-L137
def from_indexed_arrays(cls, name, verts, normals): """Takes MxNx3 verts, Mx3 normals to build obj file""" # Put header in string wavefront_str = "o {name}\n".format(name=name) new_verts, face_indices = face_index(verts) assert new_verts.shape[1] == 3, "verts should be Nx3 arr...
[ "def", "from_indexed_arrays", "(", "cls", ",", "name", ",", "verts", ",", "normals", ")", ":", "# Put header in string", "wavefront_str", "=", "\"o {name}\\n\"", ".", "format", "(", "name", "=", "name", ")", "new_verts", ",", "face_indices", "=", "face_index", ...
Takes MxNx3 verts, Mx3 normals to build obj file
[ "Takes", "MxNx3", "verts", "Mx3", "normals", "to", "build", "obj", "file" ]
python
train
inasafe/inasafe
safe/messaging/item/abstract_list.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/abstract_list.py#L50-L71
def add(self, item): """add a Text MessageElement to the existing Text Strings can be passed and are automatically converted in to item.Text() :param item: Text text, an element to add to the text """ if self._is_stringable(item) or self._is_qstring(item): ...
[ "def", "add", "(", "self", ",", "item", ")", ":", "if", "self", ".", "_is_stringable", "(", "item", ")", "or", "self", ".", "_is_qstring", "(", "item", ")", ":", "self", ".", "items", ".", "append", "(", "PlainText", "(", "item", ")", ")", "elif", ...
add a Text MessageElement to the existing Text Strings can be passed and are automatically converted in to item.Text() :param item: Text text, an element to add to the text
[ "add", "a", "Text", "MessageElement", "to", "the", "existing", "Text" ]
python
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L431-L459
def iterate_bfs(self): """Generator that yields node, [inputs], [outputs] in breadth first order. This generator will iterate over all nodes in the sensor graph, yielding a 3 tuple for each node with a list of all of the nodes connected to its inputs and all of the nodes connected to it...
[ "def", "iterate_bfs", "(", "self", ")", ":", "working_set", "=", "deque", "(", "self", ".", "roots", ")", "seen", "=", "[", "]", "while", "len", "(", "working_set", ")", ">", "0", ":", "curr", "=", "working_set", ".", "popleft", "(", ")", "# Now buil...
Generator that yields node, [inputs], [outputs] in breadth first order. This generator will iterate over all nodes in the sensor graph, yielding a 3 tuple for each node with a list of all of the nodes connected to its inputs and all of the nodes connected to its output. Returns: ...
[ "Generator", "that", "yields", "node", "[", "inputs", "]", "[", "outputs", "]", "in", "breadth", "first", "order", "." ]
python
train
ralphje/imagemounter
imagemounter/volume.py
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/volume.py#L187-L228
def _get_magic_type(self): """Checks the volume for its magic bytes and returns the magic.""" try: with io.open(self.disk.get_fs_path(), "rb") as file: file.seek(self.offset) fheader = file.read(min(self.size, 4096) if self.size else 4096) except IOEr...
[ "def", "_get_magic_type", "(", "self", ")", ":", "try", ":", "with", "io", ".", "open", "(", "self", ".", "disk", ".", "get_fs_path", "(", ")", ",", "\"rb\"", ")", "as", "file", ":", "file", ".", "seek", "(", "self", ".", "offset", ")", "fheader", ...
Checks the volume for its magic bytes and returns the magic.
[ "Checks", "the", "volume", "for", "its", "magic", "bytes", "and", "returns", "the", "magic", "." ]
python
train
OnroerendErfgoed/crabpy
crabpy/gateway/crab.py
https://github.com/OnroerendErfgoed/crabpy/blob/3a6fd8bc5aca37c2a173e3ea94e4e468b8aa79c1/crabpy/gateway/crab.py#L2090-L2104
def check_lazy_load_huisnummer(f): ''' Decorator function to lazy load a :class:`Huisnummer`. ''' def wrapper(*args): huisnummer = args[0] if ( huisnummer._metadata is None ): log.debug('Lazy loading Huisnummer %d', huisnummer.id) huisnummer.ch...
[ "def", "check_lazy_load_huisnummer", "(", "f", ")", ":", "def", "wrapper", "(", "*", "args", ")", ":", "huisnummer", "=", "args", "[", "0", "]", "if", "(", "huisnummer", ".", "_metadata", "is", "None", ")", ":", "log", ".", "debug", "(", "'Lazy loading...
Decorator function to lazy load a :class:`Huisnummer`.
[ "Decorator", "function", "to", "lazy", "load", "a", ":", "class", ":", "Huisnummer", "." ]
python
train
fabaff/python-mystrom
pymystrom/bulb.py
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/bulb.py#L196-L205
def set_off(self): """Turn the bulb off.""" try: request = requests.post( '{}/{}/{}/'.format(self.resource, URI, self._mac), data={'action': 'off'}, timeout=self.timeout) if request.status_code == 200: pass except requests.e...
[ "def", "set_off", "(", "self", ")", ":", "try", ":", "request", "=", "requests", ".", "post", "(", "'{}/{}/{}/'", ".", "format", "(", "self", ".", "resource", ",", "URI", ",", "self", ".", "_mac", ")", ",", "data", "=", "{", "'action'", ":", "'off'...
Turn the bulb off.
[ "Turn", "the", "bulb", "off", "." ]
python
train
saltstack/salt
salt/modules/boto_iam.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1213-L1239
def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_po...
[ "def", "update_assume_role_policy", "(", "role_name", ",", "policy_document", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", "...
Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}'
[ "Update", "an", "assume", "role", "policy", "for", "a", "role", "." ]
python
train
CalebBell/fluids
fluids/two_phase_voidage.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase_voidage.py#L1682-L1747
def Sun_Duffey_Peng(x, rhol, rhog, sigma, m, D, P, Pc, g=g): r'''Calculates void fraction in two-phase flow according to the model of [1]_ as given in [2]_ and [3]_. .. math:: \alpha = \frac{x}{\rho_g}\left[C_0\left(\frac{x}{\rho_g} + \frac{1-x} {\rho_l}\right) +\frac{v_{gm}}{G} \right...
[ "def", "Sun_Duffey_Peng", "(", "x", ",", "rhol", ",", "rhog", ",", "sigma", ",", "m", ",", "D", ",", "P", ",", "Pc", ",", "g", "=", "g", ")", ":", "G", "=", "m", "/", "(", "pi", "/", "4", "*", "D", "**", "2", ")", "C0", "=", "(", "0.82"...
r'''Calculates void fraction in two-phase flow according to the model of [1]_ as given in [2]_ and [3]_. .. math:: \alpha = \frac{x}{\rho_g}\left[C_0\left(\frac{x}{\rho_g} + \frac{1-x} {\rho_l}\right) +\frac{v_{gm}}{G} \right]^{-1} .. math:: v_{gm} = 1.41\left[\frac{g\...
[ "r", "Calculates", "void", "fraction", "in", "two", "-", "phase", "flow", "according", "to", "the", "model", "of", "[", "1", "]", "_", "as", "given", "in", "[", "2", "]", "_", "and", "[", "3", "]", "_", ".", "..", "math", "::", "\\", "alpha", "...
python
train
angr/angr
angr/knowledge_plugins/functions/function_manager.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/knowledge_plugins/functions/function_manager.py#L319-L354
def function(self, addr=None, name=None, create=False, syscall=False, plt=None): """ Get a function object from the function manager. Pass either `addr` or `name` with the appropriate values. :param int addr: Address of the function. :param str name: Name of the function. ...
[ "def", "function", "(", "self", ",", "addr", "=", "None", ",", "name", "=", "None", ",", "create", "=", "False", ",", "syscall", "=", "False", ",", "plt", "=", "None", ")", ":", "if", "addr", "is", "not", "None", ":", "try", ":", "f", "=", "sel...
Get a function object from the function manager. Pass either `addr` or `name` with the appropriate values. :param int addr: Address of the function. :param str name: Name of the function. :param bool create: Whether to create the function or not if the function does not exist. ...
[ "Get", "a", "function", "object", "from", "the", "function", "manager", "." ]
python
train
codenerix/django-codenerix
codenerix/multiforms.py
https://github.com/codenerix/django-codenerix/blob/1f5527b352141caaee902b37b2648791a06bd57d/codenerix/multiforms.py#L51-L160
def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ # Prepare base if 'pk' in kwargs: self.object = self.get_object() else: self.object = None form_clas...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Prepare base", "if", "'pk'", "in", "kwargs", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "else", ":", "self", ".", "object"...
Handles GET requests and instantiates blank versions of the form and its inline formsets.
[ "Handles", "GET", "requests", "and", "instantiates", "blank", "versions", "of", "the", "form", "and", "its", "inline", "formsets", "." ]
python
train
cloud-custodian/cloud-custodian
tools/c7n_logexporter/c7n_logexporter/exporter.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L171-L251
def subscribe(config, accounts, region, merge, debug): """subscribe accounts log groups to target account log group destination""" config = validate.callback(config) subscription = config.get('subscription') if subscription is None: log.error("config file: logs subscription missing") sy...
[ "def", "subscribe", "(", "config", ",", "accounts", ",", "region", ",", "merge", ",", "debug", ")", ":", "config", "=", "validate", ".", "callback", "(", "config", ")", "subscription", "=", "config", ".", "get", "(", "'subscription'", ")", "if", "subscri...
subscribe accounts log groups to target account log group destination
[ "subscribe", "accounts", "log", "groups", "to", "target", "account", "log", "group", "destination" ]
python
train
assamite/creamas
creamas/grid.py
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/grid.py#L186-L201
def is_full(self): """:class:`GridEnvironment` is full when its **grid** is fully populated with agents. :returns: True if the grid is full, False otherwise. Will also return False for uninitialized grids with (0,0) grid size. """ if len(self.grid) == 0: ...
[ "def", "is_full", "(", "self", ")", ":", "if", "len", "(", "self", ".", "grid", ")", "==", "0", ":", "return", "False", "for", "i", "in", "range", "(", "len", "(", "self", ".", "grid", ")", ")", ":", "for", "j", "in", "range", "(", "len", "("...
:class:`GridEnvironment` is full when its **grid** is fully populated with agents. :returns: True if the grid is full, False otherwise. Will also return False for uninitialized grids with (0,0) grid size.
[ ":", "class", ":", "GridEnvironment", "is", "full", "when", "its", "**", "grid", "**", "is", "fully", "populated", "with", "agents", "." ]
python
train
rkhleics/wagtailmenus
wagtailmenus/models/menus.py
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L203-L220
def prepare_to_render(self, request, contextual_vals, option_vals): """ Before calling ``render_to_template()``, this method is called to give the instance opportunity to prepare itself. For example, ``AbstractMainMenu`` and ``AbstractFlatMenu`` needs to call ``set_max_levels()``...
[ "def", "prepare_to_render", "(", "self", ",", "request", ",", "contextual_vals", ",", "option_vals", ")", ":", "self", ".", "_contextual_vals", "=", "contextual_vals", "self", ".", "_option_vals", "=", "option_vals", "self", ".", "set_request", "(", "request", "...
Before calling ``render_to_template()``, this method is called to give the instance opportunity to prepare itself. For example, ``AbstractMainMenu`` and ``AbstractFlatMenu`` needs to call ``set_max_levels()`` and ``set_use_specific()`` to update the ``max_levels`` and ``use_specific`` fi...
[ "Before", "calling", "render_to_template", "()", "this", "method", "is", "called", "to", "give", "the", "instance", "opportunity", "to", "prepare", "itself", ".", "For", "example", "AbstractMainMenu", "and", "AbstractFlatMenu", "needs", "to", "call", "set_max_levels...
python
train
inspirehep/harvesting-kit
harvestingkit/edpsciences_package.py
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/edpsciences_package.py#L268-L440
def get_record_rich(self, filename, ref_extract_callback=None): """ Gets the Marc xml of the files in xaml_rich directory :param fileName: the name of the file to parse. :type fileName: string :returns: a string with the marc xml version of the file. """ self.do...
[ "def", "get_record_rich", "(", "self", ",", "filename", ",", "ref_extract_callback", "=", "None", ")", ":", "self", ".", "document", "=", "parse", "(", "filename", ")", "rec", "=", "create_record", "(", ")", "articles", "=", "self", ".", "document", ".", ...
Gets the Marc xml of the files in xaml_rich directory :param fileName: the name of the file to parse. :type fileName: string :returns: a string with the marc xml version of the file.
[ "Gets", "the", "Marc", "xml", "of", "the", "files", "in", "xaml_rich", "directory" ]
python
valid
gem/oq-engine
openquake/commonlib/logictree.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L499-L526
def collect_info(smlt): """ Given a path to a source model logic tree, collect all of the path names to the source models it contains and build 1. a dictionary source model branch ID -> paths 2. a dictionary source model branch ID -> source IDs in applyToSources :param smlt: source model logic ...
[ "def", "collect_info", "(", "smlt", ")", ":", "n", "=", "nrml", ".", "read", "(", "smlt", ")", "try", ":", "blevels", "=", "n", ".", "logicTree", "except", "Exception", ":", "raise", "InvalidFile", "(", "'%s is not a valid source_model_logic_tree_file'", "%", ...
Given a path to a source model logic tree, collect all of the path names to the source models it contains and build 1. a dictionary source model branch ID -> paths 2. a dictionary source model branch ID -> source IDs in applyToSources :param smlt: source model logic tree file :returns: an Info name...
[ "Given", "a", "path", "to", "a", "source", "model", "logic", "tree", "collect", "all", "of", "the", "path", "names", "to", "the", "source", "models", "it", "contains", "and", "build", "1", ".", "a", "dictionary", "source", "model", "branch", "ID", "-", ...
python
train
craffel/mir_eval
mir_eval/transcription.py
https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/transcription.py#L336-L463
def match_notes(ref_intervals, ref_pitches, est_intervals, est_pitches, onset_tolerance=0.05, pitch_tolerance=50.0, offset_ratio=0.2, offset_min_tolerance=0.05, strict=False): """Compute a maximum matching between reference and estimated notes, subject to onset, pitch and (option...
[ "def", "match_notes", "(", "ref_intervals", ",", "ref_pitches", ",", "est_intervals", ",", "est_pitches", ",", "onset_tolerance", "=", "0.05", ",", "pitch_tolerance", "=", "50.0", ",", "offset_ratio", "=", "0.2", ",", "offset_min_tolerance", "=", "0.05", ",", "s...
Compute a maximum matching between reference and estimated notes, subject to onset, pitch and (optionally) offset constraints. Given two note sequences represented by ``ref_intervals``, ``ref_pitches``, ``est_intervals`` and ``est_pitches`` (see :func:`mir_eval.io.load_valued_intervals`), we seek the l...
[ "Compute", "a", "maximum", "matching", "between", "reference", "and", "estimated", "notes", "subject", "to", "onset", "pitch", "and", "(", "optionally", ")", "offset", "constraints", "." ]
python
train
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L211-L224
def name(self): """str: name.""" if self._tsk_attribute: # The value of the attribute name will be None for the default # data stream. attribute_name = getattr(self._tsk_attribute.info, 'name', None) if attribute_name: try: # pytsk3 returns an UTF-8 encoded byte string....
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "_tsk_attribute", ":", "# The value of the attribute name will be None for the default", "# data stream.", "attribute_name", "=", "getattr", "(", "self", ".", "_tsk_attribute", ".", "info", ",", "'name'", ",", ...
str: name.
[ "str", ":", "name", "." ]
python
train
fred49/argtoolbox
argtoolbox/argtoolbox.py
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L697-L703
def load(self, file_parser, section_name): """The current element is loaded from the configuration file, all constraints and requirements are checked. Then element hooks are applied. """ self._load(file_parser, section_name) self.post_load()
[ "def", "load", "(", "self", ",", "file_parser", ",", "section_name", ")", ":", "self", ".", "_load", "(", "file_parser", ",", "section_name", ")", "self", ".", "post_load", "(", ")" ]
The current element is loaded from the configuration file, all constraints and requirements are checked. Then element hooks are applied.
[ "The", "current", "element", "is", "loaded", "from", "the", "configuration", "file", "all", "constraints", "and", "requirements", "are", "checked", ".", "Then", "element", "hooks", "are", "applied", "." ]
python
train
doconix/django-mako-plus
django_mako_plus/exceptions.py
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/exceptions.py#L54-L59
def get_response(self, request, *args, **kwargs): '''Returns the redirect response for this exception.''' # normal process response = HttpResponseRedirect(self.redirect_to) response[REDIRECT_HEADER_KEY] = self.redirect_to return response
[ "def", "get_response", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# normal process", "response", "=", "HttpResponseRedirect", "(", "self", ".", "redirect_to", ")", "response", "[", "REDIRECT_HEADER_KEY", "]", "=", "sel...
Returns the redirect response for this exception.
[ "Returns", "the", "redirect", "response", "for", "this", "exception", "." ]
python
train
guyingbo/iofree
iofree/__init__.py
https://github.com/guyingbo/iofree/blob/9a14250c276f88c784d164f60fb22fbc1e7a3243/iofree/__init__.py#L67-L74
def get_result(self): """ raises *NoResult* exception if no result has been set """ self._process() if not self.has_result: raise NoResult return self.res_queue.popleft()
[ "def", "get_result", "(", "self", ")", ":", "self", ".", "_process", "(", ")", "if", "not", "self", ".", "has_result", ":", "raise", "NoResult", "return", "self", ".", "res_queue", ".", "popleft", "(", ")" ]
raises *NoResult* exception if no result has been set
[ "raises", "*", "NoResult", "*", "exception", "if", "no", "result", "has", "been", "set" ]
python
train
sphinx-gallery/sphinx-gallery
sphinx_gallery/gen_gallery.py
https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L81-L97
def parse_config(app): """Process the Sphinx Gallery configuration""" try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) src_dir = app.builder.srcdir abort_on_example_error = app.builder.config.abort_on_exa...
[ "def", "parse_config", "(", "app", ")", ":", "try", ":", "plot_gallery", "=", "eval", "(", "app", ".", "builder", ".", "config", ".", "plot_gallery", ")", "except", "TypeError", ":", "plot_gallery", "=", "bool", "(", "app", ".", "builder", ".", "config",...
Process the Sphinx Gallery configuration
[ "Process", "the", "Sphinx", "Gallery", "configuration" ]
python
train
CEA-COSMIC/ModOpt
modopt/signal/wavelet.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/wavelet.py#L172-L226
def filter_convolve(data, filters, filter_rot=False, method='scipy'): r"""Filter convolve This method convolves the input image with the wavelet filters Parameters ---------- data : np.ndarray Input data, 2D array filters : np.ndarray Wavelet filters, 3D array filter_rot : ...
[ "def", "filter_convolve", "(", "data", ",", "filters", ",", "filter_rot", "=", "False", ",", "method", "=", "'scipy'", ")", ":", "if", "filter_rot", ":", "return", "np", ".", "sum", "(", "[", "convolve", "(", "coef", ",", "f", ",", "method", "=", "me...
r"""Filter convolve This method convolves the input image with the wavelet filters Parameters ---------- data : np.ndarray Input data, 2D array filters : np.ndarray Wavelet filters, 3D array filter_rot : bool, optional Option to rotate wavelet filters (default is 'False...
[ "r", "Filter", "convolve" ]
python
train
spyder-ide/spyder
spyder/utils/encoding.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/encoding.py#L252-L258
def read(filename, encoding='utf-8'): """ Read text from file ('filename') Return text and encoding """ text, encoding = decode( open(filename, 'rb').read() ) return text, encoding
[ "def", "read", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", ":", "text", ",", "encoding", "=", "decode", "(", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", ")", ")", "return", "text", ",", "encoding" ]
Read text from file ('filename') Return text and encoding
[ "Read", "text", "from", "file", "(", "filename", ")", "Return", "text", "and", "encoding" ]
python
train
networks-lab/metaknowledge
metaknowledge/grantCollection.py
https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/grantCollection.py#L145-L229
def networkCoInvestigator(self, targetTags = None, tagSeperator = ';', count = True, weighted = True, _institutionLevel = False): """Creates a co-investigator from the collection Most grants do not have a known investigator tag so it must be provided by the user in _targetTags_ and the separator charac...
[ "def", "networkCoInvestigator", "(", "self", ",", "targetTags", "=", "None", ",", "tagSeperator", "=", "';'", ",", "count", "=", "True", ",", "weighted", "=", "True", ",", "_institutionLevel", "=", "False", ")", ":", "grph", "=", "nx", ".", "Graph", "(",...
Creates a co-investigator from the collection Most grants do not have a known investigator tag so it must be provided by the user in _targetTags_ and the separator character if it is not a semicolon should also be given. # Parameters > _targetTags_ : `optional list[str]` > A list of ...
[ "Creates", "a", "co", "-", "investigator", "from", "the", "collection" ]
python
train
softlayer/softlayer-python
SoftLayer/managers/vs.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L594-L644
def create_instances(self, config_list): """Creates multiple virtual server instances. This takes a list of dictionaries using the same arguments as create_instance(). .. warning:: This will add charges to your account Example:: # Define the instance ...
[ "def", "create_instances", "(", "self", ",", "config_list", ")", ":", "tags", "=", "[", "conf", ".", "pop", "(", "'tags'", ",", "None", ")", "for", "conf", "in", "config_list", "]", "resp", "=", "self", ".", "guest", ".", "createObjects", "(", "[", "...
Creates multiple virtual server instances. This takes a list of dictionaries using the same arguments as create_instance(). .. warning:: This will add charges to your account Example:: # Define the instance we want to create. new_vsi = { ...
[ "Creates", "multiple", "virtual", "server", "instances", "." ]
python
train
maas/python-libmaas
maas/client/viscera/nodes.py
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L145-L152
async def set_power( self, power_type: str, power_parameters: typing.Mapping[str, typing.Any] = {}): """Set the power type and power parameters for this node.""" data = await self._handler.update( system_id=self.system_id, power_type=power_type, power_para...
[ "async", "def", "set_power", "(", "self", ",", "power_type", ":", "str", ",", "power_parameters", ":", "typing", ".", "Mapping", "[", "str", ",", "typing", ".", "Any", "]", "=", "{", "}", ")", ":", "data", "=", "await", "self", ".", "_handler", ".", ...
Set the power type and power parameters for this node.
[ "Set", "the", "power", "type", "and", "power", "parameters", "for", "this", "node", "." ]
python
train
jxtech/wechatpy
wechatpy/client/api/customservice.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/customservice.py#L210-L236
def get_records(self, start_time, end_time, msgid=1, number=10000): """ 获取客服聊天记录 :param start_time: 查询开始时间,UNIX 时间戳 :param end_time: 查询结束时间,UNIX 时间戳,每次查询不能跨日查询 :param msgid: 消息id顺序从小到大,从1开始 :param number: 每次获取条数,最多10000条 :return: 返回的 JSON 数据包...
[ "def", "get_records", "(", "self", ",", "start_time", ",", "end_time", ",", "msgid", "=", "1", ",", "number", "=", "10000", ")", ":", "if", "isinstance", "(", "start_time", ",", "datetime", ".", "datetime", ")", ":", "start_time", "=", "time", ".", "mk...
获取客服聊天记录 :param start_time: 查询开始时间,UNIX 时间戳 :param end_time: 查询结束时间,UNIX 时间戳,每次查询不能跨日查询 :param msgid: 消息id顺序从小到大,从1开始 :param number: 每次获取条数,最多10000条 :return: 返回的 JSON 数据包
[ "获取客服聊天记录" ]
python
train
openstack/networking-cisco
networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1240-L1296
def _configure_port_entries(self, port, vlan_id, device_id, host_id, vni, is_provider_vlan): """Create a nexus switch entry. if needed, create a VLAN in the appropriate switch or port and configure the appropriate interfaces for this VLAN. Called during ...
[ "def", "_configure_port_entries", "(", "self", ",", "port", ",", "vlan_id", ",", "device_id", ",", "host_id", ",", "vni", ",", "is_provider_vlan", ")", ":", "connections", "=", "self", ".", "_get_active_port_connections", "(", "port", ",", "host_id", ")", "# (...
Create a nexus switch entry. if needed, create a VLAN in the appropriate switch or port and configure the appropriate interfaces for this VLAN. Called during update postcommit port event.
[ "Create", "a", "nexus", "switch", "entry", "." ]
python
train
PyCQA/astroid
astroid/scoped_nodes.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1930-L1960
def postinit( self, bases, body, decorators, newstyle=None, metaclass=None, keywords=None ): """Do some setup after initialisation. :param bases: What the class inherits from. :type bases: list(NodeNG) :param body: The contents of the class body. :type body: list(No...
[ "def", "postinit", "(", "self", ",", "bases", ",", "body", ",", "decorators", ",", "newstyle", "=", "None", ",", "metaclass", "=", "None", ",", "keywords", "=", "None", ")", ":", "self", ".", "keywords", "=", "keywords", "self", ".", "bases", "=", "b...
Do some setup after initialisation. :param bases: What the class inherits from. :type bases: list(NodeNG) :param body: The contents of the class body. :type body: list(NodeNG) :param decorators: The decorators that are applied to this class. :type decorators: Decorator...
[ "Do", "some", "setup", "after", "initialisation", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/states/container_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1540-L1561
def add_input_data_to_scoped_data(self, dictionary): """Add a dictionary to the scoped data As the input_data dictionary maps names to values, the functions looks for the proper data_ports keys in the input_data_ports dictionary :param dictionary: The dictionary that is added to the sc...
[ "def", "add_input_data_to_scoped_data", "(", "self", ",", "dictionary", ")", ":", "for", "dict_key", ",", "value", "in", "dictionary", ".", "items", "(", ")", ":", "for", "input_data_port_key", ",", "data_port", "in", "list", "(", "self", ".", "input_data_port...
Add a dictionary to the scoped data As the input_data dictionary maps names to values, the functions looks for the proper data_ports keys in the input_data_ports dictionary :param dictionary: The dictionary that is added to the scoped data :param state: The state to which the input_dat...
[ "Add", "a", "dictionary", "to", "the", "scoped", "data" ]
python
train
Clinical-Genomics/scout
scout/parse/hgnc.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/parse/hgnc.py#L88-L108
def parse_hgnc_genes(lines): """Parse lines with hgnc formated genes This is designed to take a dump with genes from HGNC. This is downloaded from: ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt Args: lines(iterable(str)): An iterable with HGN...
[ "def", "parse_hgnc_genes", "(", "lines", ")", ":", "header", "=", "[", "]", "logger", ".", "info", "(", "\"Parsing hgnc genes...\"", ")", "for", "index", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "index", "==", "0", ":", "header", "...
Parse lines with hgnc formated genes This is designed to take a dump with genes from HGNC. This is downloaded from: ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt Args: lines(iterable(str)): An iterable with HGNC formated genes Yields: ...
[ "Parse", "lines", "with", "hgnc", "formated", "genes" ]
python
test
jnrbsn/daemonocle
daemonocle/core.py
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L367-L382
def _shutdown(self, message=None, code=0): """Shutdown and cleanup everything.""" if self._shutdown_complete: # Make sure we don't accidentally re-run the all cleanup sys.exit(code) if self.shutdown_callback is not None: # Call the shutdown callback with a me...
[ "def", "_shutdown", "(", "self", ",", "message", "=", "None", ",", "code", "=", "0", ")", ":", "if", "self", ".", "_shutdown_complete", ":", "# Make sure we don't accidentally re-run the all cleanup", "sys", ".", "exit", "(", "code", ")", "if", "self", ".", ...
Shutdown and cleanup everything.
[ "Shutdown", "and", "cleanup", "everything", "." ]
python
train
mikedh/trimesh
trimesh/path/path.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L94-L102
def process(self): """ Apply basic cleaning functions to the Path object, in- place. """ log.debug('Processing drawing') with self._cache: for func in self._process_functions(): func() return self
[ "def", "process", "(", "self", ")", ":", "log", ".", "debug", "(", "'Processing drawing'", ")", "with", "self", ".", "_cache", ":", "for", "func", "in", "self", ".", "_process_functions", "(", ")", ":", "func", "(", ")", "return", "self" ]
Apply basic cleaning functions to the Path object, in- place.
[ "Apply", "basic", "cleaning", "functions", "to", "the", "Path", "object", "in", "-", "place", "." ]
python
train
zsimic/runez
src/runez/serialize.py
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/serialize.py#L99-L112
def to_dict(self): """ :return dict: This object serialized to a dict """ result = {} for name in self.__dict__: if name.startswith("_"): continue key = name.replace("_", "-") attr = getattr(self, name) result[key] ...
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "name", "in", "self", ".", "__dict__", ":", "if", "name", ".", "startswith", "(", "\"_\"", ")", ":", "continue", "key", "=", "name", ".", "replace", "(", "\"_\"", ",", "\"-\""...
:return dict: This object serialized to a dict
[ ":", "return", "dict", ":", "This", "object", "serialized", "to", "a", "dict" ]
python
train
saimn/sigal
sigal/gallery.py
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L422-L483
def thumbnail(self): """Path to the thumbnail of the album.""" if self._thumbnail: # stop if it is already set return self._thumbnail # Test the thumbnail from the Markdown file. thumbnail = self.meta.get('thumbnail', [''])[0] if thumbnail and isfile(jo...
[ "def", "thumbnail", "(", "self", ")", ":", "if", "self", ".", "_thumbnail", ":", "# stop if it is already set", "return", "self", ".", "_thumbnail", "# Test the thumbnail from the Markdown file.", "thumbnail", "=", "self", ".", "meta", ".", "get", "(", "'thumbnail'"...
Path to the thumbnail of the album.
[ "Path", "to", "the", "thumbnail", "of", "the", "album", "." ]
python
valid
picklepete/pyicloud
pyicloud/base.py
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/base.py#L255-L263
def send_verification_code(self, device): """ Requests that a verification code is sent to the given device""" data = json.dumps(device) request = self.session.post( '%s/sendVerificationCode' % self._setup_endpoint, params=self.params, data=data ) ...
[ "def", "send_verification_code", "(", "self", ",", "device", ")", ":", "data", "=", "json", ".", "dumps", "(", "device", ")", "request", "=", "self", ".", "session", ".", "post", "(", "'%s/sendVerificationCode'", "%", "self", ".", "_setup_endpoint", ",", "...
Requests that a verification code is sent to the given device
[ "Requests", "that", "a", "verification", "code", "is", "sent", "to", "the", "given", "device" ]
python
train
meraki-analytics/cassiopeia-datastores
cassiopeia-sqlstore/cassiopeia_sqlstore/SQLStore.py
https://github.com/meraki-analytics/cassiopeia-datastores/blob/1919b79b8b036d48818eb648e712df41f8a1299c/cassiopeia-sqlstore/cassiopeia_sqlstore/SQLStore.py#L144-L150
def _put(self, item: SQLBaseObject): """Puts a item into the database. Updates lastUpdate column""" if item._dto_type in self._expirations and self._expirations[item._dto_type] == 0: # The expiration time has been set to 0 -> shoud not be cached return item.updated() ...
[ "def", "_put", "(", "self", ",", "item", ":", "SQLBaseObject", ")", ":", "if", "item", ".", "_dto_type", "in", "self", ".", "_expirations", "and", "self", ".", "_expirations", "[", "item", ".", "_dto_type", "]", "==", "0", ":", "# The expiration time has b...
Puts a item into the database. Updates lastUpdate column
[ "Puts", "a", "item", "into", "the", "database", ".", "Updates", "lastUpdate", "column" ]
python
train
aganezov/bg
bg/vertices.py
https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/vertices.py#L206-L208
def name(self): """ access to classic name attribute is hidden by this property """ return self.NAME_SEPARATOR.join([super(InfinityVertex, self).name, self.NAME_SUFFIX])
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "NAME_SEPARATOR", ".", "join", "(", "[", "super", "(", "InfinityVertex", ",", "self", ")", ".", "name", ",", "self", ".", "NAME_SUFFIX", "]", ")" ]
access to classic name attribute is hidden by this property
[ "access", "to", "classic", "name", "attribute", "is", "hidden", "by", "this", "property" ]
python
train
delfick/harpoon
harpoon/collector.py
https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/collector.py#L110-L116
def find_harpoon_options(self, configuration, args_dict): """Return us all the harpoon options""" d = lambda r: {} if r in (None, "", NotSpecified) else r return MergedOptions.using( dict(d(configuration.get('harpoon')).items()) , dict(d(args_dict.get("harpoon")).items(...
[ "def", "find_harpoon_options", "(", "self", ",", "configuration", ",", "args_dict", ")", ":", "d", "=", "lambda", "r", ":", "{", "}", "if", "r", "in", "(", "None", ",", "\"\"", ",", "NotSpecified", ")", "else", "r", "return", "MergedOptions", ".", "usi...
Return us all the harpoon options
[ "Return", "us", "all", "the", "harpoon", "options" ]
python
train
google/grumpy
compiler/imputil.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/compiler/imputil.py#L296-L311
def parse_future_features(mod): """Accumulates a set of flags for the compiler __future__ imports.""" assert isinstance(mod, ast.Module) found_docstring = False for node in mod.body: if isinstance(node, ast.ImportFrom): if node.module == '__future__': return node, _make_future_features(node) ...
[ "def", "parse_future_features", "(", "mod", ")", ":", "assert", "isinstance", "(", "mod", ",", "ast", ".", "Module", ")", "found_docstring", "=", "False", "for", "node", "in", "mod", ".", "body", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "...
Accumulates a set of flags for the compiler __future__ imports.
[ "Accumulates", "a", "set", "of", "flags", "for", "the", "compiler", "__future__", "imports", "." ]
python
valid
wiheto/teneto
teneto/plot/graphlet_stack_plot.py
https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/plot/graphlet_stack_plot.py#L9-L271
def graphlet_stack_plot(netin, ax, q=10, cmap='Reds', gridcolor='k', borderwidth=2, bordercolor=None, Fs=1, timeunit='', t0=1, sharpen='yes', vminmax='minmax'): r''' Returns matplotlib axis handle for graphlet_stack_plot. This is a row of transformed connectivity matrices to look like a 3D stack. Parameter...
[ "def", "graphlet_stack_plot", "(", "netin", ",", "ax", ",", "q", "=", "10", ",", "cmap", "=", "'Reds'", ",", "gridcolor", "=", "'k'", ",", "borderwidth", "=", "2", ",", "bordercolor", "=", "None", ",", "Fs", "=", "1", ",", "timeunit", "=", "''", ",...
r''' Returns matplotlib axis handle for graphlet_stack_plot. This is a row of transformed connectivity matrices to look like a 3D stack. Parameters ---------- netin : array, dict network input (graphlet or contact) ax : matplotlib ax handles. q : int Quality. Increaseing this w...
[ "r", "Returns", "matplotlib", "axis", "handle", "for", "graphlet_stack_plot", ".", "This", "is", "a", "row", "of", "transformed", "connectivity", "matrices", "to", "look", "like", "a", "3D", "stack", "." ]
python
train
tundish/turberfield-dialogue
turberfield/dialogue/model.py
https://github.com/tundish/turberfield-dialogue/blob/e7ccf7c19ae162e2f315ddf2642394e858529b4a/turberfield/dialogue/model.py#L331-L393
def select(self, personae, relative=False, roles=1): """Select a persona for each entity declared in the scene. :param personae: A sequence of Personae. :param bool relative: Affects imports from namespace packages. Used for testing only. :param int roles: The maximum number...
[ "def", "select", "(", "self", ",", "personae", ",", "relative", "=", "False", ",", "roles", "=", "1", ")", ":", "def", "constrained", "(", "entity", ")", ":", "return", "(", "len", "(", "entity", "[", "\"options\"", "]", ".", "get", "(", "\"types\"",...
Select a persona for each entity declared in the scene. :param personae: A sequence of Personae. :param bool relative: Affects imports from namespace packages. Used for testing only. :param int roles: The maximum number of roles allocated to each persona. :return: An Ordered...
[ "Select", "a", "persona", "for", "each", "entity", "declared", "in", "the", "scene", "." ]
python
train
apache/spark
python/pyspark/java_gateway.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/java_gateway.py#L150-L160
def _do_server_auth(conn, auth_secret): """ Performs the authentication protocol defined by the SocketAuthHelper class on the given file-like object 'conn'. """ write_with_length(auth_secret.encode("utf-8"), conn) conn.flush() reply = UTF8Deserializer().loads(conn) if reply != "ok": ...
[ "def", "_do_server_auth", "(", "conn", ",", "auth_secret", ")", ":", "write_with_length", "(", "auth_secret", ".", "encode", "(", "\"utf-8\"", ")", ",", "conn", ")", "conn", ".", "flush", "(", ")", "reply", "=", "UTF8Deserializer", "(", ")", ".", "loads", ...
Performs the authentication protocol defined by the SocketAuthHelper class on the given file-like object 'conn'.
[ "Performs", "the", "authentication", "protocol", "defined", "by", "the", "SocketAuthHelper", "class", "on", "the", "given", "file", "-", "like", "object", "conn", "." ]
python
train
tensorflow/tensorboard
tensorboard/plugins/hparams/list_session_groups.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/list_session_groups.py#L199-L226
def _sort(self, session_groups): """Sorts 'session_groups' in place according to _request.col_params.""" # Sort by session_group name so we have a deterministic order. session_groups.sort(key=operator.attrgetter('name')) # Sort by lexicographical order of the _request.col_params whose order # is no...
[ "def", "_sort", "(", "self", ",", "session_groups", ")", ":", "# Sort by session_group name so we have a deterministic order.", "session_groups", ".", "sort", "(", "key", "=", "operator", ".", "attrgetter", "(", "'name'", ")", ")", "# Sort by lexicographical order of the ...
Sorts 'session_groups' in place according to _request.col_params.
[ "Sorts", "session_groups", "in", "place", "according", "to", "_request", ".", "col_params", "." ]
python
train
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L855-L891
def _EvaluateExpression(frame, expression): """Compiles and evaluates watched expression. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: (False, status) on error or (True, value) on success. """ try: code = compile(expression, '<watched_expr...
[ "def", "_EvaluateExpression", "(", "frame", ",", "expression", ")", ":", "try", ":", "code", "=", "compile", "(", "expression", ",", "'<watched_expression>'", ",", "'eval'", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "e", ":", "# expressi...
Compiles and evaluates watched expression. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: (False, status) on error or (True, value) on success.
[ "Compiles", "and", "evaluates", "watched", "expression", "." ]
python
train
blockstack/blockstack-core
blockstack/lib/subdomains.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1748-L1764
def verify_singlesig(address, hash_hex, scriptSig): """ Verify that a p2pkh address is signed by the given pay-to-pubkey-hash scriptsig """ try: sighex, pubkey_hex = virtualchain.btc_script_deserialize(scriptSig) except: log.warn("Wrong signature structure for {}".format(address)) ...
[ "def", "verify_singlesig", "(", "address", ",", "hash_hex", ",", "scriptSig", ")", ":", "try", ":", "sighex", ",", "pubkey_hex", "=", "virtualchain", ".", "btc_script_deserialize", "(", "scriptSig", ")", "except", ":", "log", ".", "warn", "(", "\"Wrong signatu...
Verify that a p2pkh address is signed by the given pay-to-pubkey-hash scriptsig
[ "Verify", "that", "a", "p2pkh", "address", "is", "signed", "by", "the", "given", "pay", "-", "to", "-", "pubkey", "-", "hash", "scriptsig" ]
python
train
insightindustry/validator-collection
validator_collection/checkers.py
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L379-L436
def is_string(value, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``Tr...
[ "def", "is_string", "(", "value", ",", "coerce_value", "=", "False", ",", "minimum_length", "=", "None", ",", "maximum_length", "=", "None", ",", "whitespace_padding", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "None", ":", "re...
Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``True``, will check whether ``value`` can be coerced to a string if it is not already. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied,...
[ "Indicate", "whether", "value", "is", "a", "string", "." ]
python
train
Terrance/SkPy
skpy/conn.py
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L646-L661
def auth(self, token): """ Take an existing Skype token and refresh it, to extend the expiry time without other credentials. Args: token (str): existing Skype token Returns: (str, datetime.datetime) tuple: Skype token, and associated expiry if known Rai...
[ "def", "auth", "(", "self", ",", "token", ")", ":", "t", "=", "self", ".", "sendToken", "(", "token", ")", "return", "self", ".", "getToken", "(", "t", ")" ]
Take an existing Skype token and refresh it, to extend the expiry time without other credentials. Args: token (str): existing Skype token Returns: (str, datetime.datetime) tuple: Skype token, and associated expiry if known Raises: .SkypeAuthException: if th...
[ "Take", "an", "existing", "Skype", "token", "and", "refresh", "it", "to", "extend", "the", "expiry", "time", "without", "other", "credentials", "." ]
python
test
google/grr
grr/server/grr_response_server/aff4_objects/users.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/users.py#L215-L226
def Describe(self): """Return a description of this user.""" result = ["\nUsername: %s" % self.urn.Basename()] labels = [l.name for l in self.GetLabels()] result.append("Labels: %s" % ",".join(labels)) if self.Get(self.Schema.PASSWORD) is None: result.append("Password: not set") else: ...
[ "def", "Describe", "(", "self", ")", ":", "result", "=", "[", "\"\\nUsername: %s\"", "%", "self", ".", "urn", ".", "Basename", "(", ")", "]", "labels", "=", "[", "l", ".", "name", "for", "l", "in", "self", ".", "GetLabels", "(", ")", "]", "result",...
Return a description of this user.
[ "Return", "a", "description", "of", "this", "user", "." ]
python
train
google/transitfeed
transitfeed/trip.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L374-L377
def GetPattern(self): """Return a tuple of Stop objects, in the order visited""" stoptimes = self.GetStopTimes() return tuple(st.stop for st in stoptimes)
[ "def", "GetPattern", "(", "self", ")", ":", "stoptimes", "=", "self", ".", "GetStopTimes", "(", ")", "return", "tuple", "(", "st", ".", "stop", "for", "st", "in", "stoptimes", ")" ]
Return a tuple of Stop objects, in the order visited
[ "Return", "a", "tuple", "of", "Stop", "objects", "in", "the", "order", "visited" ]
python
train
b3j0f/conf
b3j0f/conf/parser/resolver/registry.py
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/registry.py#L317-L339
def getname(exprresolver): """Get expression resolver name. Expression resolver name is given by the attribute __resolver__. If not exist, then the it is given by the attribute __name__. Otherwise, given by the __class__.__name__ attribute. :raises: TypeError if exprresolver is not callable.""" ...
[ "def", "getname", "(", "exprresolver", ")", ":", "result", "=", "None", "if", "not", "callable", "(", "exprresolver", ")", ":", "raise", "TypeError", "(", "'Expression resolver must be a callable object.'", ")", "result", "=", "getattr", "(", "exprresolver", ",", ...
Get expression resolver name. Expression resolver name is given by the attribute __resolver__. If not exist, then the it is given by the attribute __name__. Otherwise, given by the __class__.__name__ attribute. :raises: TypeError if exprresolver is not callable.
[ "Get", "expression", "resolver", "name", "." ]
python
train
Microsoft/malmo
Malmo/samples/Python_examples/tutorial_6.py
https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/tutorial_6.py#L89-L134
def act(self, world_state, agent_host, current_r ): """take 1 action in response to the current world state""" obs_text = world_state.observations[-1].text obs = json.loads(obs_text) # most recent observation self.logger.debug(obs) if not u'XPos' in obs or not u'ZPos' in...
[ "def", "act", "(", "self", ",", "world_state", ",", "agent_host", ",", "current_r", ")", ":", "obs_text", "=", "world_state", ".", "observations", "[", "-", "1", "]", ".", "text", "obs", "=", "json", ".", "loads", "(", "obs_text", ")", "# most recent obs...
take 1 action in response to the current world state
[ "take", "1", "action", "in", "response", "to", "the", "current", "world", "state" ]
python
train
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L236-L328
def get_document( self, name, mask=None, transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets a single document. Example: ...
[ "def", "get_document", "(", "self", ",", "name", ",", "mask", "=", "None", ",", "transaction", "=", "None", ",", "read_time", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "="...
Gets a single document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> ...
[ "Gets", "a", "single", "document", "." ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L4735-L4745
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configuration_id') and self.configuration_id is not None: _dict['configuration_id'] = self.configuration_id if hasattr(self, 'status') and self.status i...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'configuration_id'", ")", "and", "self", ".", "configuration_id", "is", "not", "None", ":", "_dict", "[", "'configuration_id'", "]", "=", "self", ".", ...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
Jahaja/psdash
psdash/log.py
https://github.com/Jahaja/psdash/blob/4f1784742666045a3c33bd471dbe489b4f5c7699/psdash/log.py#L114-L140
def search(self, text): """ Find text in log file from current position returns a tuple containing: absolute position, position in result buffer, result buffer (the actual file contents) """ key = hash(text) searcher = self._searchers....
[ "def", "search", "(", "self", ",", "text", ")", ":", "key", "=", "hash", "(", "text", ")", "searcher", "=", "self", ".", "_searchers", ".", "get", "(", "key", ")", "if", "not", "searcher", ":", "searcher", "=", "ReverseFileSearcher", "(", "self", "."...
Find text in log file from current position returns a tuple containing: absolute position, position in result buffer, result buffer (the actual file contents)
[ "Find", "text", "in", "log", "file", "from", "current", "position" ]
python
train
viewflow/django-fsm
django_fsm/__init__.py
https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L493-L522
def transition(field, source='*', target=None, on_error=None, conditions=[], permission=None, custom={}): """ Method decorator to mark allowed transitions. Set target to None if current state needs to be validated and has not changed after the function call. """ def inner_transition(func): ...
[ "def", "transition", "(", "field", ",", "source", "=", "'*'", ",", "target", "=", "None", ",", "on_error", "=", "None", ",", "conditions", "=", "[", "]", ",", "permission", "=", "None", ",", "custom", "=", "{", "}", ")", ":", "def", "inner_transition...
Method decorator to mark allowed transitions. Set target to None if current state needs to be validated and has not changed after the function call.
[ "Method", "decorator", "to", "mark", "allowed", "transitions", "." ]
python
train
python-rope/rope
rope/refactor/patchedast.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/patchedast.py#L784-L796
def _good_token(self, token, offset, start=None): """Checks whether consumed token is in comments""" if start is None: start = self.offset try: comment_index = self.source.rindex('#', start, offset) except ValueError: return True try: ...
[ "def", "_good_token", "(", "self", ",", "token", ",", "offset", ",", "start", "=", "None", ")", ":", "if", "start", "is", "None", ":", "start", "=", "self", ".", "offset", "try", ":", "comment_index", "=", "self", ".", "source", ".", "rindex", "(", ...
Checks whether consumed token is in comments
[ "Checks", "whether", "consumed", "token", "is", "in", "comments" ]
python
train
Zsailer/kubeconf
kubeconf/kubeconf.py
https://github.com/Zsailer/kubeconf/blob/b4e81001b5d2fb8d461056f25eb8b03307d57a6b/kubeconf/kubeconf.py#L295-L301
def context_exists(self, name): """Check if a given context exists.""" contexts = self.data['contexts'] for context in contexts: if context['name'] == name: return True return False
[ "def", "context_exists", "(", "self", ",", "name", ")", ":", "contexts", "=", "self", ".", "data", "[", "'contexts'", "]", "for", "context", "in", "contexts", ":", "if", "context", "[", "'name'", "]", "==", "name", ":", "return", "True", "return", "Fal...
Check if a given context exists.
[ "Check", "if", "a", "given", "context", "exists", "." ]
python
train
Hackerfleet/hfos
hfos/ui/schemamanager.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/schemamanager.py#L96-L103
def cli_form(self, *args): """Display a schemata's form definition""" if args[0] == '*': for schema in schemastore: self.log(schema, ':', schemastore[schema]['form'], pretty=True) else: self.log(schemastore[args[0]]['form'], pretty=True)
[ "def", "cli_form", "(", "self", ",", "*", "args", ")", ":", "if", "args", "[", "0", "]", "==", "'*'", ":", "for", "schema", "in", "schemastore", ":", "self", ".", "log", "(", "schema", ",", "':'", ",", "schemastore", "[", "schema", "]", "[", "'fo...
Display a schemata's form definition
[ "Display", "a", "schemata", "s", "form", "definition" ]
python
train
draperjames/qtpandas
qtpandas/views/CustomDelegates.py
https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CustomDelegates.py#L91-L100
def setEditorData(self, spinBox, index): """Sets the data to be displayed and edited by the editor from the data model item specified by the model index. Args: spinBox (BigIntSpinbox): editor widget. index (QModelIndex): model data index. """ if index.isValid(): ...
[ "def", "setEditorData", "(", "self", ",", "spinBox", ",", "index", ")", ":", "if", "index", ".", "isValid", "(", ")", ":", "value", "=", "index", ".", "model", "(", ")", ".", "data", "(", "index", ",", "QtCore", ".", "Qt", ".", "EditRole", ")", "...
Sets the data to be displayed and edited by the editor from the data model item specified by the model index. Args: spinBox (BigIntSpinbox): editor widget. index (QModelIndex): model data index.
[ "Sets", "the", "data", "to", "be", "displayed", "and", "edited", "by", "the", "editor", "from", "the", "data", "model", "item", "specified", "by", "the", "model", "index", "." ]
python
train
loli/medpy
medpy/features/intensity.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/intensity.py#L373-L452
def local_histogram(image, bins=19, rang="image", cutoffp=(0.0, 100.0), size=None, footprint=None, output=None, mode="ignore", origin=0, mask=slice(None)): r""" Computes multi-dimensional histograms over a region around each voxel. Supply an image and (optionally) a mask and get the local histogram of ...
[ "def", "local_histogram", "(", "image", ",", "bins", "=", "19", ",", "rang", "=", "\"image\"", ",", "cutoffp", "=", "(", "0.0", ",", "100.0", ")", ",", "size", "=", "None", ",", "footprint", "=", "None", ",", "output", "=", "None", ",", "mode", "="...
r""" Computes multi-dimensional histograms over a region around each voxel. Supply an image and (optionally) a mask and get the local histogram of local neighbourhoods around each voxel. These neighbourhoods are cubic with a sidelength of size in voxels or, when a shape instead of an integer is pas...
[ "r", "Computes", "multi", "-", "dimensional", "histograms", "over", "a", "region", "around", "each", "voxel", ".", "Supply", "an", "image", "and", "(", "optionally", ")", "a", "mask", "and", "get", "the", "local", "histogram", "of", "local", "neighbourhoods"...
python
train
dshean/pygeotools
pygeotools/lib/filtlib.py
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/filtlib.py#L271-L284
def median_fltr(dem, fsize=7, origmask=False): """Scipy.ndimage median filter Does not properly handle NaN """ print("Applying median filter with size %s" % fsize) from scipy.ndimage.filters import median_filter dem_filt_med = median_filter(dem.filled(np.nan), fsize) #Now mask all nans ...
[ "def", "median_fltr", "(", "dem", ",", "fsize", "=", "7", ",", "origmask", "=", "False", ")", ":", "print", "(", "\"Applying median filter with size %s\"", "%", "fsize", ")", "from", "scipy", ".", "ndimage", ".", "filters", "import", "median_filter", "dem_filt...
Scipy.ndimage median filter Does not properly handle NaN
[ "Scipy", ".", "ndimage", "median", "filter" ]
python
train
fossasia/knittingpattern
knittingpattern/convert/InstructionToSVG.py
https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/InstructionToSVG.py#L155-L170
def default_instruction_to_svg_dict(self, instruction): """Returns an xml-dictionary with the same content as :meth:`default_instruction_to_svg` If no file ``default.svg`` was loaded, an empty svg-dict is returned. """ instruction_type = instruction.type default_type = "...
[ "def", "default_instruction_to_svg_dict", "(", "self", ",", "instruction", ")", ":", "instruction_type", "=", "instruction", ".", "type", "default_type", "=", "\"default\"", "rep_str", "=", "\"{instruction.type}\"", "if", "default_type", "not", "in", "self", ".", "_...
Returns an xml-dictionary with the same content as :meth:`default_instruction_to_svg` If no file ``default.svg`` was loaded, an empty svg-dict is returned.
[ "Returns", "an", "xml", "-", "dictionary", "with", "the", "same", "content", "as", ":", "meth", ":", "default_instruction_to_svg" ]
python
valid
LionelAuroux/pyrser
pyrser/type_system/scope.py
https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/scope.py#L370-L378
def getsig_by_symbol_name(self, name: str) -> Signature: """ Retrieve the unique Signature of a symbol. Fail if the Signature is not unique """ subscope = self.get_by_symbol_name(name) if len(subscope) != 1: raise KeyError("%s have multiple candidates in scope" % name...
[ "def", "getsig_by_symbol_name", "(", "self", ",", "name", ":", "str", ")", "->", "Signature", ":", "subscope", "=", "self", ".", "get_by_symbol_name", "(", "name", ")", "if", "len", "(", "subscope", ")", "!=", "1", ":", "raise", "KeyError", "(", "\"%s ha...
Retrieve the unique Signature of a symbol. Fail if the Signature is not unique
[ "Retrieve", "the", "unique", "Signature", "of", "a", "symbol", ".", "Fail", "if", "the", "Signature", "is", "not", "unique" ]
python
test
Data-Mechanics/geoql
geoql/geoql.py
https://github.com/Data-Mechanics/geoql/blob/c6184e1734c76a259855d6282e919614839a767e/geoql/geoql.py#L97-L107
def features_keep_within_radius(obj, center, radius, units): """ Filter all features in a collection by retaining only those that fall within the specified radius. """ features_keep = [] for feature in tqdm(obj['features']): if all([getattr(geopy.distance.vincenty((lat,lon), center), uni...
[ "def", "features_keep_within_radius", "(", "obj", ",", "center", ",", "radius", ",", "units", ")", ":", "features_keep", "=", "[", "]", "for", "feature", "in", "tqdm", "(", "obj", "[", "'features'", "]", ")", ":", "if", "all", "(", "[", "getattr", "(",...
Filter all features in a collection by retaining only those that fall within the specified radius.
[ "Filter", "all", "features", "in", "a", "collection", "by", "retaining", "only", "those", "that", "fall", "within", "the", "specified", "radius", "." ]
python
train
statueofmike/rtsp
scripts/others/rtsp.py
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L293-L320
def exec_cmd(rtsp,cmd): '''根据命令执行操作''' global CUR_RANGE,CUR_SCALE if cmd in ('exit','teardown'): rtsp.do_teardown() elif cmd == 'pause': CUR_SCALE = 1; CUR_RANGE = 'npt=now-' rtsp.do_pause() elif cmd == 'help': PRINT(play_ctrl_help()) elif cmd == 'forward': ...
[ "def", "exec_cmd", "(", "rtsp", ",", "cmd", ")", ":", "global", "CUR_RANGE", ",", "CUR_SCALE", "if", "cmd", "in", "(", "'exit'", ",", "'teardown'", ")", ":", "rtsp", ".", "do_teardown", "(", ")", "elif", "cmd", "==", "'pause'", ":", "CUR_SCALE", "=", ...
根据命令执行操作
[ "根据命令执行操作" ]
python
train
7sDream/zhihu-py3
zhihu/answer.py
https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/answer.py#L169-L181
def collect_num(self): """获取答案收藏数 :return: 答案收藏数量 :rtype: int """ element = self.soup.find("a", { "data-za-a": "click_answer_collected_count" }) if element is None: return 0 else: return int(element.get_text())
[ "def", "collect_num", "(", "self", ")", ":", "element", "=", "self", ".", "soup", ".", "find", "(", "\"a\"", ",", "{", "\"data-za-a\"", ":", "\"click_answer_collected_count\"", "}", ")", "if", "element", "is", "None", ":", "return", "0", "else", ":", "re...
获取答案收藏数 :return: 答案收藏数量 :rtype: int
[ "获取答案收藏数" ]
python
train
weld-project/weld
python/grizzly/grizzly/grizzly_impl.py
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L14-L31
def get_field(expr, field): """ Fetch a field from a struct expr """ weld_obj = WeldObject(encoder_, decoder_) struct_var = weld_obj.update(expr) if isinstance(expr, WeldObject): struct_var = expr.obj_id weld_obj.dependencies[struct_var] = expr weld_template = """ %(stru...
[ "def", "get_field", "(", "expr", ",", "field", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "struct_var", "=", "weld_obj", ".", "update", "(", "expr", ")", "if", "isinstance", "(", "expr", ",", "WeldObject", ")", ":", ...
Fetch a field from a struct expr
[ "Fetch", "a", "field", "from", "a", "struct", "expr" ]
python
train