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
tgbugs/pyontutils
ilxutils/ilxutils/nltklib.py
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/nltklib.py#L36-L70
def sentence_similarity(sentence1, sentence2): """ compute the sentence similarity using Wordnet """ # Tokenize and tag sentence1 = pos_tag(word_tokenize(sentence1)) sentence2 = pos_tag(word_tokenize(sentence2)) # Get the synsets for the tagged words synsets1 = [tagged_to_synset(*tagged_word) f...
[ "def", "sentence_similarity", "(", "sentence1", ",", "sentence2", ")", ":", "# Tokenize and tag", "sentence1", "=", "pos_tag", "(", "word_tokenize", "(", "sentence1", ")", ")", "sentence2", "=", "pos_tag", "(", "word_tokenize", "(", "sentence2", ")", ")", "# Get...
compute the sentence similarity using Wordnet
[ "compute", "the", "sentence", "similarity", "using", "Wordnet" ]
python
train
MIT-LCP/wfdb-python
wfdb/io/record.py
https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L235-L255
def _adjust_datetime(self, sampfrom): """ Adjust date and time fields to reflect user input if possible. Helper function for the `_arrange_fields` of both Record and MultiRecord objects. """ if sampfrom: dt_seconds = sampfrom / self.fs if self.bas...
[ "def", "_adjust_datetime", "(", "self", ",", "sampfrom", ")", ":", "if", "sampfrom", ":", "dt_seconds", "=", "sampfrom", "/", "self", ".", "fs", "if", "self", ".", "base_date", "and", "self", ".", "base_time", ":", "self", ".", "base_datetime", "=", "dat...
Adjust date and time fields to reflect user input if possible. Helper function for the `_arrange_fields` of both Record and MultiRecord objects.
[ "Adjust", "date", "and", "time", "fields", "to", "reflect", "user", "input", "if", "possible", "." ]
python
train
bitesofcode/projexui
projexui/wizards/xscaffoldwizard/xscaffoldwizard.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L136-L156
def propertyWidgetMap(self): """ Returns the mapping for this page between its widgets and its scaffold property. :return {<projex.scaffold.Property>: <QtGui.QWidget>, ..} """ out = {} scaffold = self.scaffold() # initialize...
[ "def", "propertyWidgetMap", "(", "self", ")", ":", "out", "=", "{", "}", "scaffold", "=", "self", ".", "scaffold", "(", ")", "# initialize the scaffold properties\r", "for", "widget", "in", "self", ".", "findChildren", "(", "QtGui", ".", "QWidget", ")", ":",...
Returns the mapping for this page between its widgets and its scaffold property. :return {<projex.scaffold.Property>: <QtGui.QWidget>, ..}
[ "Returns", "the", "mapping", "for", "this", "page", "between", "its", "widgets", "and", "its", "scaffold", "property", ".", ":", "return", "{", "<projex", ".", "scaffold", ".", "Property", ">", ":", "<QtGui", ".", "QWidget", ">", "..", "}" ]
python
train
Xython/Linq.py
linq/standard/dict.py
https://github.com/Xython/Linq.py/blob/ffb65f92f1df0d8161d5f835f5947554f6f33d72/linq/standard/dict.py#L163-L180
def Drop(self: dict, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ] """ n = len(self) - n if n <= 0: yield from self.items() else: for i, e in enumerate(self.items()): ...
[ "def", "Drop", "(", "self", ":", "dict", ",", "n", ")", ":", "n", "=", "len", "(", "self", ")", "-", "n", "if", "n", "<=", "0", ":", "yield", "from", "self", ".", "items", "(", ")", "else", ":", "for", "i", ",", "e", "in", "enumerate", "(",...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ]
[ "[", "{", "self", ":", "[", "1", "2", "3", "4", "5", "]", "n", ":", "3", "assert", ":", "lambda", "ret", ":", "list", "(", "ret", ")", "==", "[", "1", "2", "]", "}", "]" ]
python
train
ansible/tower-cli
tower_cli/resources/job.py
https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/resources/job.py#L79-L252
def launch(self, job_template=None, monitor=False, wait=False, timeout=None, no_input=True, extra_vars=None, **kwargs): """Launch a new job based on a job template. Creates a new job in Ansible Tower, immediately starts it, and returns back an ID in order for its status to be mon...
[ "def", "launch", "(", "self", ",", "job_template", "=", "None", ",", "monitor", "=", "False", ",", "wait", "=", "False", ",", "timeout", "=", "None", ",", "no_input", "=", "True", ",", "extra_vars", "=", "None", ",", "*", "*", "kwargs", ")", ":", "...
Launch a new job based on a job template. Creates a new job in Ansible Tower, immediately starts it, and returns back an ID in order for its status to be monitored. =====API DOCS===== Launch a new job based on a job template. :param job_template: Primary key or name of the job...
[ "Launch", "a", "new", "job", "based", "on", "a", "job", "template", "." ]
python
valid
riptano/ccm
ccmlib/node.py
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L451-L519
def watch_log_for(self, exprs, from_mark=None, timeout=600, process=None, verbose=False, filename='system.log'): """ Watch the log until one or more (regular) expression are found. This methods when all the expressions have been found or the method timeouts (a TimeoutError is then raised...
[ "def", "watch_log_for", "(", "self", ",", "exprs", ",", "from_mark", "=", "None", ",", "timeout", "=", "600", ",", "process", "=", "None", ",", "verbose", "=", "False", ",", "filename", "=", "'system.log'", ")", ":", "start", "=", "time", ".", "time", ...
Watch the log until one or more (regular) expression are found. This methods when all the expressions have been found or the method timeouts (a TimeoutError is then raised). On successful completion, a list of pair (line matched, match object) is returned.
[ "Watch", "the", "log", "until", "one", "or", "more", "(", "regular", ")", "expression", "are", "found", ".", "This", "methods", "when", "all", "the", "expressions", "have", "been", "found", "or", "the", "method", "timeouts", "(", "a", "TimeoutError", "is",...
python
train
a1ezzz/wasp-general
wasp_general/network/clients/webdav.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/webdav.py#L136-L146
def change_directory(self, path, *args, **kwargs): """ :meth:`.WNetworkClientProto.change_directory` method implementation """ client = self.dav_client() previous_path = self.session_path() try: if client.is_dir(self.session_path(path)) is False: raise ValueError('Unable to change current working direc...
[ "def", "change_directory", "(", "self", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "client", "=", "self", ".", "dav_client", "(", ")", "previous_path", "=", "self", ".", "session_path", "(", ")", "try", ":", "if", "client", "."...
:meth:`.WNetworkClientProto.change_directory` method implementation
[ ":", "meth", ":", ".", "WNetworkClientProto", ".", "change_directory", "method", "implementation" ]
python
train
holmes-app/holmes-alf
holmesalf/wrapper.py
https://github.com/holmes-app/holmes-alf/blob/4bf891831390ecfae818cf37d8ffc3a76fe9f1ec/holmesalf/wrapper.py#L37-L45
def async_client(self): """Asynchronous OAuth 2.0 Bearer client""" if not self._async_client: self._async_client = AlfAsyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), client_id=self.config.get('OAUTH_CLIENT_ID'), client_secr...
[ "def", "async_client", "(", "self", ")", ":", "if", "not", "self", ".", "_async_client", ":", "self", ".", "_async_client", "=", "AlfAsyncClient", "(", "token_endpoint", "=", "self", ".", "config", ".", "get", "(", "'OAUTH_TOKEN_ENDPOINT'", ")", ",", "client...
Asynchronous OAuth 2.0 Bearer client
[ "Asynchronous", "OAuth", "2", ".", "0", "Bearer", "client" ]
python
train
kellerza/pyqwikswitch
pyqwikswitch/threaded.py
https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/threaded.py#L122-L135
def update_from_devices(self): """Retrieve a list of &devices and values.""" # _LOGGER.warning("update from devices") try: rest = requests.get(URL_DEVICES.format(self._url)) if rest.status_code != 200: _LOGGER.error("Devices returned %s", rest.status_code)...
[ "def", "update_from_devices", "(", "self", ")", ":", "# _LOGGER.warning(\"update from devices\")", "try", ":", "rest", "=", "requests", ".", "get", "(", "URL_DEVICES", ".", "format", "(", "self", ".", "_url", ")", ")", "if", "rest", ".", "status_code", "!=", ...
Retrieve a list of &devices and values.
[ "Retrieve", "a", "list", "of", "&devices", "and", "values", "." ]
python
train
mitsei/dlkit
dlkit/json_/grading/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L223-L235
def clear_input_score_start_range(self): """Clears the input score start. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.g...
[ "def", "clear_input_score_start_range", "(", "self", ")", ":", "# Implemented from template for osid.grading.GradeSystemForm.clear_lowest_numeric_score", "if", "(", "self", ".", "get_input_score_start_range_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", "."...
Clears the input score start. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
[ "Clears", "the", "input", "score", "start", "." ]
python
train
apple/turicreate
src/unity/python/turicreate/toolkits/recommender/util.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/recommender/util.py#L1763-L1772
def _get_popularity_baseline(self): """ Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes. """ response = self.__proxy__.get_popularity_baseline() from .popularity_recommender import PopularityRecommen...
[ "def", "_get_popularity_baseline", "(", "self", ")", ":", "response", "=", "self", ".", "__proxy__", ".", "get_popularity_baseline", "(", ")", "from", ".", "popularity_recommender", "import", "PopularityRecommender", "return", "PopularityRecommender", "(", "response", ...
Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes.
[ "Returns", "a", "new", "popularity", "model", "matching", "the", "data", "set", "this", "model", "was", "trained", "with", ".", "Can", "be", "used", "for", "comparison", "purposes", "." ]
python
train
StackStorm/pybind
pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py#L544-L567
def _set_protected_port(self, v, load=False): """ Setter method for protected_port, mapped from YANG variable /interface/hundredgigabitethernet/protected_port (container) If this variable is read-only (config: false) in the source YANG file, then _set_protected_port is considered as a private method...
[ "def", "_set_protected_port", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for protected_port, mapped from YANG variable /interface/hundredgigabitethernet/protected_port (container) If this variable is read-only (config: false) in the source YANG file, then _set_protected_port is considered as a private method. Backends looking to populate this variable should do...
[ "Setter", "method", "for", "protected_port", "mapped", "from", "YANG", "variable", "/", "interface", "/", "hundredgigabitethernet", "/", "protected_port", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ...
python
train
carljm/django-adminfiles
adminfiles/listeners.py
https://github.com/carljm/django-adminfiles/blob/b01dc7be266305d575c11d5ff9a37ccac04a78c2/adminfiles/listeners.py#L15-L27
def _get_field(instance, field): """ This is here to support ``MarkupField``. It's a little ugly to have that support baked-in; other option would be to have a generic way (via setting?) to override how attribute values are fetched from content model instances. """ value = getattr(inst...
[ "def", "_get_field", "(", "instance", ",", "field", ")", ":", "value", "=", "getattr", "(", "instance", ",", "field", ")", "if", "hasattr", "(", "value", ",", "'raw'", ")", ":", "value", "=", "value", ".", "raw", "return", "value" ]
This is here to support ``MarkupField``. It's a little ugly to have that support baked-in; other option would be to have a generic way (via setting?) to override how attribute values are fetched from content model instances.
[ "This", "is", "here", "to", "support", "MarkupField", ".", "It", "s", "a", "little", "ugly", "to", "have", "that", "support", "baked", "-", "in", ";", "other", "option", "would", "be", "to", "have", "a", "generic", "way", "(", "via", "setting?", ")", ...
python
train
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/ratelimits.py
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/ratelimits.py#L85-L97
def maybe_rate_limit(client, headers, atexit=False): """Optionally pause the process based on suggested rate interval.""" # pylint: disable=fixme # pylint: disable=global-statement # FIXME: Yes, I know this is not great. We'll fix it later. :-) global LAST_CLIENT, LAST_HEADERS if LAST_CLIENT an...
[ "def", "maybe_rate_limit", "(", "client", ",", "headers", ",", "atexit", "=", "False", ")", ":", "# pylint: disable=fixme", "# pylint: disable=global-statement", "# FIXME: Yes, I know this is not great. We'll fix it later. :-)", "global", "LAST_CLIENT", ",", "LAST_HEADERS", "if...
Optionally pause the process based on suggested rate interval.
[ "Optionally", "pause", "the", "process", "based", "on", "suggested", "rate", "interval", "." ]
python
train
SKA-ScienceDataProcessor/integration-prototype
sip/examples/flask_processing_controller/app/old.db/mock/init.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/examples/flask_processing_controller/app/old.db/mock/init.py#L18-L23
def generate_scheduling_block_id(num_blocks, project='test'): """Generate a scheduling_block id""" _date = strftime("%Y%m%d", gmtime()) _project = project for i in range(num_blocks): yield '{}-{}-sbi{:03d}'.format(_date, _project, i)
[ "def", "generate_scheduling_block_id", "(", "num_blocks", ",", "project", "=", "'test'", ")", ":", "_date", "=", "strftime", "(", "\"%Y%m%d\"", ",", "gmtime", "(", ")", ")", "_project", "=", "project", "for", "i", "in", "range", "(", "num_blocks", ")", ":"...
Generate a scheduling_block id
[ "Generate", "a", "scheduling_block", "id" ]
python
train
baverman/supplement
supplement/remote.py
https://github.com/baverman/supplement/blob/955002fe5a5749c9f0d89002f0006ec4fcd35bc9/supplement/remote.py#L139-L158
def get_docstring(self, project_path, source, position, filename): """Return signature and docstring for current cursor call context Some examples of call context:: func(| func(arg| func(arg,| func(arg, func2(| # call context is func2 Signature ...
[ "def", "get_docstring", "(", "self", ",", "project_path", ",", "source", ",", "position", ",", "filename", ")", ":", "return", "self", ".", "_call", "(", "'get_docstring'", ",", "project_path", ",", "source", ",", "position", ",", "filename", ")" ]
Return signature and docstring for current cursor call context Some examples of call context:: func(| func(arg| func(arg,| func(arg, func2(| # call context is func2 Signature and docstring can be None :param project_path: absolute project path ...
[ "Return", "signature", "and", "docstring", "for", "current", "cursor", "call", "context" ]
python
train
MisterY/pydatum
pydatum/datum.py
https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L151-L155
def set_value(self, value: datetime): """ Sets the current value """ assert isinstance(value, datetime) self.value = value
[ "def", "set_value", "(", "self", ",", "value", ":", "datetime", ")", ":", "assert", "isinstance", "(", "value", ",", "datetime", ")", "self", ".", "value", "=", "value" ]
Sets the current value
[ "Sets", "the", "current", "value" ]
python
train
pypa/pipenv
pipenv/vendor/pyparsing.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L4846-L4889
def traceParseAction(f): """Decorator for debugging parse actions. When the parse action is called, this decorator will print ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``. When the parse action completes, the decorator will print ``"<<"`` followed by...
[ "def", "traceParseAction", "(", "f", ")", ":", "f", "=", "_trim_arity", "(", "f", ")", "def", "z", "(", "*", "paArgs", ")", ":", "thisFunc", "=", "f", ".", "__name__", "s", ",", "l", ",", "t", "=", "paArgs", "[", "-", "3", ":", "]", "if", "le...
Decorator for debugging parse actions. When the parse action is called, this decorator will print ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``. When the parse action completes, the decorator will print ``"<<"`` followed by the returned value, or any exce...
[ "Decorator", "for", "debugging", "parse", "actions", "." ]
python
train
ValvePython/steam
steam/game_servers.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/game_servers.py#L452-L513
def a2s_players(server_addr, timeout=2, challenge=0): """Get list of players and their info :param server_addr: (ip, port) for the server :type server_addr: tuple :param timeout: (optional) timeout in seconds :type timeout: float :param challenge: (optional) challenge number :type challe...
[ "def", "a2s_players", "(", "server_addr", ",", "timeout", "=", "2", ",", "challenge", "=", "0", ")", ":", "ss", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "ss", ".", "connect", "(", "server_addr"...
Get list of players and their info :param server_addr: (ip, port) for the server :type server_addr: tuple :param timeout: (optional) timeout in seconds :type timeout: float :param challenge: (optional) challenge number :type challenge: int :raises: :class:`RuntimeError`, :class:`socket.t...
[ "Get", "list", "of", "players", "and", "their", "info" ]
python
train
peterdemin/pip-compile-multi
pipcompilemulti/verify.py
https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/verify.py#L15-L40
def verify_environments(): """ For each environment verify hash comments and report failures. If any failure occured, exit with code 1. """ env_confs = discover( os.path.join( OPTIONS['base_dir'], '*.' + OPTIONS['in_ext'], ) ) success = True for co...
[ "def", "verify_environments", "(", ")", ":", "env_confs", "=", "discover", "(", "os", ".", "path", ".", "join", "(", "OPTIONS", "[", "'base_dir'", "]", ",", "'*.'", "+", "OPTIONS", "[", "'in_ext'", "]", ",", ")", ")", "success", "=", "True", "for", "...
For each environment verify hash comments and report failures. If any failure occured, exit with code 1.
[ "For", "each", "environment", "verify", "hash", "comments", "and", "report", "failures", ".", "If", "any", "failure", "occured", "exit", "with", "code", "1", "." ]
python
train
driftx/Telephus
telephus/cassandra/Cassandra.py
https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1583-L1591
def trace_next_query(self, ): """ Enables tracing for the next query in this connection and returns the UUID for that trace session The next query will be traced idependently of trace probability and the returned UUID can be used to query the trace keyspace """ self._seqid += 1 d = self._reqs[se...
[ "def", "trace_next_query", "(", "self", ",", ")", ":", "self", ".", "_seqid", "+=", "1", "d", "=", "self", ".", "_reqs", "[", "self", ".", "_seqid", "]", "=", "defer", ".", "Deferred", "(", ")", "self", ".", "send_trace_next_query", "(", ")", "return...
Enables tracing for the next query in this connection and returns the UUID for that trace session The next query will be traced idependently of trace probability and the returned UUID can be used to query the trace keyspace
[ "Enables", "tracing", "for", "the", "next", "query", "in", "this", "connection", "and", "returns", "the", "UUID", "for", "that", "trace", "session", "The", "next", "query", "will", "be", "traced", "idependently", "of", "trace", "probability", "and", "the", "...
python
train
Nic30/hwt
hwt/hdl/switchContainer.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/switchContainer.py#L163-L177
def _merge_with_other_stm(self, other: "IfContainer") -> None: """ Merge other statement to this statement """ merge = self._merge_statement_lists newCases = [] for (c, caseA), (_, caseB) in zip(self.cases, other.cases): newCases.append((c, merge(caseA, caseB)...
[ "def", "_merge_with_other_stm", "(", "self", ",", "other", ":", "\"IfContainer\"", ")", "->", "None", ":", "merge", "=", "self", ".", "_merge_statement_lists", "newCases", "=", "[", "]", "for", "(", "c", ",", "caseA", ")", ",", "(", "_", ",", "caseB", ...
Merge other statement to this statement
[ "Merge", "other", "statement", "to", "this", "statement" ]
python
test
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L225-L234
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg....
[ "def", "get_income_in_period", "(", "self", ",", "start", ":", "datetime", ",", "end", ":", "datetime", ")", "->", "Decimal", ":", "accounts", "=", "self", ".", "get_income_accounts", "(", ")", "income", "=", "Decimal", "(", "0", ")", "for", "acct", "in"...
Returns all income in the given period
[ "Returns", "all", "income", "in", "the", "given", "period" ]
python
train
kmedian/illmat
illmat/illmat.py
https://github.com/kmedian/illmat/blob/2755e7c7da67378a0fa38ed24ba040dbf0f645bd/illmat/illmat.py#L5-L29
def illmat(D, random_state=None): """Generate a <D x D> ill-conditioned correlation matrix with random coefficients Parameters: ----------- D : int Dimension of the matrix Return: ------- cmat : ndarray DxD matrix with +1 as diagonal elements, mirrored random nu...
[ "def", "illmat", "(", "D", ",", "random_state", "=", "None", ")", ":", "if", "random_state", ":", "np", ".", "random", ".", "seed", "(", "random_state", ")", "uni", "=", "np", ".", "random", ".", "uniform", "(", "size", "=", "(", "D", ",", "D", "...
Generate a <D x D> ill-conditioned correlation matrix with random coefficients Parameters: ----------- D : int Dimension of the matrix Return: ------- cmat : ndarray DxD matrix with +1 as diagonal elements, mirrored random numbers [-1,+1].
[ "Generate", "a", "<D", "x", "D", ">", "ill", "-", "conditioned", "correlation", "matrix", "with", "random", "coefficients" ]
python
train
Gandi/gandi.cli
gandi/cli/core/params.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/params.py#L562-L583
def handle_parse_result(self, ctx, opts, args): """ Save value for this option in configuration if key/value pair doesn't already exist. Or old value in config was deprecated it needs to be updated to the new value format but the value keeps the same "meaning" """ ...
[ "def", "handle_parse_result", "(", "self", ",", "ctx", ",", "opts", ",", "args", ")", ":", "gandi", "=", "ctx", ".", "obj", "needs_update", "=", "False", "value", ",", "args", "=", "click", ".", "Option", ".", "handle_parse_result", "(", "self", ",", "...
Save value for this option in configuration if key/value pair doesn't already exist. Or old value in config was deprecated it needs to be updated to the new value format but the value keeps the same "meaning"
[ "Save", "value", "for", "this", "option", "in", "configuration", "if", "key", "/", "value", "pair", "doesn", "t", "already", "exist", ".", "Or", "old", "value", "in", "config", "was", "deprecated", "it", "needs", "to", "be", "updated", "to", "the", "new"...
python
train
Kronuz/pyScss
scss/extension/compass/images.py
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/images.py#L210-L217
def image_url(path, only_path=False, cache_buster=True, dst_color=None, src_color=None, spacing=None, collapse_x=None, collapse_y=None): """ Generates a path to an asset found relative to the project's images directory. Passing a true value as the second argument will cause the only the path to be r...
[ "def", "image_url", "(", "path", ",", "only_path", "=", "False", ",", "cache_buster", "=", "True", ",", "dst_color", "=", "None", ",", "src_color", "=", "None", ",", "spacing", "=", "None", ",", "collapse_x", "=", "None", ",", "collapse_y", "=", "None", ...
Generates a path to an asset found relative to the project's images directory. Passing a true value as the second argument will cause the only the path to be returned instead of a `url()` function
[ "Generates", "a", "path", "to", "an", "asset", "found", "relative", "to", "the", "project", "s", "images", "directory", ".", "Passing", "a", "true", "value", "as", "the", "second", "argument", "will", "cause", "the", "only", "the", "path", "to", "be", "r...
python
train
f3at/feat
src/feat/common/run.py
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/common/run.py#L247-L258
def _ensure_dir(directory, description): """ Ensure the given directory exists, creating it if not. @raise errors.FatalError: if the directory could not be created. """ if not os.path.exists(directory): try: os.makedirs(directory) except OSError, e: sys.stder...
[ "def", "_ensure_dir", "(", "directory", ",", "description", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "try", ":", "os", ".", "makedirs", "(", "directory", ")", "except", "OSError", ",", "e", ":", "sys", ".",...
Ensure the given directory exists, creating it if not. @raise errors.FatalError: if the directory could not be created.
[ "Ensure", "the", "given", "directory", "exists", "creating", "it", "if", "not", "." ]
python
train
rcarmo/pngcanvas
pngcanvas.py
https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L141-L144
def rectangle(self, x0, y0, x1, y1): """Draw a rectangle""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) self.polyline([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]])
[ "def", "rectangle", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "self", ".", "rect_helper", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", "self", ".", "polyline", "(", "[...
Draw a rectangle
[ "Draw", "a", "rectangle" ]
python
train
polyaxon/polyaxon-cli
polyaxon_cli/cli/superuser.py
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/superuser.py#L48-L66
def revoke(username): """Revoke superuser role to a user. Example: \b ```bash $ polyaxon superuser revoke david ``` """ try: PolyaxonClient().user.revoke_superuser(username) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.p...
[ "def", "revoke", "(", "username", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "user", ".", "revoke_superuser", "(", "username", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ...
Revoke superuser role to a user. Example: \b ```bash $ polyaxon superuser revoke david ```
[ "Revoke", "superuser", "role", "to", "a", "user", "." ]
python
valid
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L155-L171
def encode_id_token(self, id_token): """ Return encoded ID token. """ # Encode the ID token using the `client_secret`. # # TODO: Using the `client_secret` is not ideal, since it is transmitted # over the wire in some authentication flows. A better alternative i...
[ "def", "encode_id_token", "(", "self", ",", "id_token", ")", ":", "# Encode the ID token using the `client_secret`.", "#", "# TODO: Using the `client_secret` is not ideal, since it is transmitted", "# over the wire in some authentication flows. A better alternative is", "# to use the public...
Return encoded ID token.
[ "Return", "encoded", "ID", "token", "." ]
python
train
TheHive-Project/Cortex-Analyzers
analyzers/SoltraEdge/soltra.py
https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L55-L68
def api_related(self, query): ''' Find related objects through SoltraEdge API ''' url = "{0}/{1}/related/?format=json".format(self.base_url, query) response = requests.get(url, headers=self.headers, verify=self.verify_ssl) if response.status_code == 200: ret...
[ "def", "api_related", "(", "self", ",", "query", ")", ":", "url", "=", "\"{0}/{1}/related/?format=json\"", ".", "format", "(", "self", ".", "base_url", ",", "query", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", "...
Find related objects through SoltraEdge API
[ "Find", "related", "objects", "through", "SoltraEdge", "API" ]
python
train
ahopkins/sanic-jwt
sanic_jwt/authentication.py
https://github.com/ahopkins/sanic-jwt/blob/fca7750499c8cedde823d778512f613777fb5282/sanic_jwt/authentication.py#L117-L142
def _check_authentication(self, request, request_args, request_kwargs): """ Checks a request object to determine if that request contains a valid, and authenticated JWT. It returns a tuple: 1. Boolean whether the request is authenticated with a valid JWT 2. HTTP status c...
[ "def", "_check_authentication", "(", "self", ",", "request", ",", "request_args", ",", "request_kwargs", ")", ":", "try", ":", "is_valid", ",", "status", ",", "reasons", "=", "self", ".", "_verify", "(", "request", ",", "request_args", "=", "request_args", "...
Checks a request object to determine if that request contains a valid, and authenticated JWT. It returns a tuple: 1. Boolean whether the request is authenticated with a valid JWT 2. HTTP status code 3. Reasons (if any) for a potential authentication failure
[ "Checks", "a", "request", "object", "to", "determine", "if", "that", "request", "contains", "a", "valid", "and", "authenticated", "JWT", "." ]
python
train
ungarj/mapchete
mapchete/config.py
https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L557-L560
def process_file(self): """Deprecated.""" warnings.warn(DeprecationWarning("'self.process_file' is deprecated")) return os.path.join(self._raw["config_dir"], self._raw["process"])
[ "def", "process_file", "(", "self", ")", ":", "warnings", ".", "warn", "(", "DeprecationWarning", "(", "\"'self.process_file' is deprecated\"", ")", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_raw", "[", "\"config_dir\"", "]", ",", "se...
Deprecated.
[ "Deprecated", "." ]
python
valid
atlassian-api/atlassian-python-api
atlassian/confluence.py
https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/confluence.py#L397-L405
def remove_content_history(self, page_id, version_number): """ Remove content history. It works as experimental method :param page_id: :param version_number: version number :return: """ url = 'rest/experimental/content/{id}/version/{versionNumber}'.format(id=page_...
[ "def", "remove_content_history", "(", "self", ",", "page_id", ",", "version_number", ")", ":", "url", "=", "'rest/experimental/content/{id}/version/{versionNumber}'", ".", "format", "(", "id", "=", "page_id", ",", "versionNumber", "=", "version_number", ")", "self", ...
Remove content history. It works as experimental method :param page_id: :param version_number: version number :return:
[ "Remove", "content", "history", ".", "It", "works", "as", "experimental", "method", ":", "param", "page_id", ":", ":", "param", "version_number", ":", "version", "number", ":", "return", ":" ]
python
train
Azure/blobxfer
blobxfer/operations/upload.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/upload.py#L131-L143
def termination_check_md5(self): # type: (Uploader) -> bool """Check if terminated from MD5 context :param Uploader self: this :rtype: bool :return: if terminated from MD5 context """ with self._md5_meta_lock: with self._upload_lock: re...
[ "def", "termination_check_md5", "(", "self", ")", ":", "# type: (Uploader) -> bool", "with", "self", ".", "_md5_meta_lock", ":", "with", "self", ".", "_upload_lock", ":", "return", "(", "self", ".", "_upload_terminate", "or", "(", "self", ".", "_all_files_processe...
Check if terminated from MD5 context :param Uploader self: this :rtype: bool :return: if terminated from MD5 context
[ "Check", "if", "terminated", "from", "MD5", "context", ":", "param", "Uploader", "self", ":", "this", ":", "rtype", ":", "bool", ":", "return", ":", "if", "terminated", "from", "MD5", "context" ]
python
train
ashleysommer/sanicpluginsframework
spf/plugin.py
https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L107-L130
def route(self, uri, *args, **kwargs): """Create a plugin route from a decorated function. :param uri: endpoint at which the route will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: capt...
[ "def", "route", "(", "self", ",", "uri", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "0", "and", "callable", "(", "uri", ")", ":", "# pragma: no cover", "raise", "RuntimeError", "(", "\"Cannot use the @rout...
Create a plugin route from a decorated function. :param uri: endpoint at which the route will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: captures the keyword arguments passed in :type...
[ "Create", "a", "plugin", "route", "from", "a", "decorated", "function", ".", ":", "param", "uri", ":", "endpoint", "at", "which", "the", "route", "will", "be", "accessible", ".", ":", "type", "uri", ":", "str", ":", "param", "args", ":", "captures", "a...
python
train
twisted/mantissa
xmantissa/liveform.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1251-L1259
def options(self, request, tag): """ Render each of the options of the wrapped L{ChoiceParameter} instance. """ option = tag.patternGenerator('option') return tag[[ OptionView(index, o, option()) for (index, o) in enumerate(self.par...
[ "def", "options", "(", "self", ",", "request", ",", "tag", ")", ":", "option", "=", "tag", ".", "patternGenerator", "(", "'option'", ")", "return", "tag", "[", "[", "OptionView", "(", "index", ",", "o", ",", "option", "(", ")", ")", "for", "(", "in...
Render each of the options of the wrapped L{ChoiceParameter} instance.
[ "Render", "each", "of", "the", "options", "of", "the", "wrapped", "L", "{", "ChoiceParameter", "}", "instance", "." ]
python
train
mapbox/mapbox-cli-py
mapboxcli/scripts/geocoding.py
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/geocoding.py#L24-L31
def coords_from_query(query): """Transform a query line into a (lng, lat) pair of coordinates.""" try: coords = json.loads(query) except ValueError: vals = re.split(r'[,\s]+', query.strip()) coords = [float(v) for v in vals] return tuple(coords[:2])
[ "def", "coords_from_query", "(", "query", ")", ":", "try", ":", "coords", "=", "json", ".", "loads", "(", "query", ")", "except", "ValueError", ":", "vals", "=", "re", ".", "split", "(", "r'[,\\s]+'", ",", "query", ".", "strip", "(", ")", ")", "coord...
Transform a query line into a (lng, lat) pair of coordinates.
[ "Transform", "a", "query", "line", "into", "a", "(", "lng", "lat", ")", "pair", "of", "coordinates", "." ]
python
train
scanny/python-pptx
pptx/shapes/shapetree.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/shapetree.py#L843-L855
def new_movie_pic(cls, shapes, shape_id, movie_file, x, y, cx, cy, poster_frame_image, mime_type): """Return a new `p:pic` element containing video in *movie_file*. If *mime_type* is None, 'video/unknown' is used. If *poster_frame_file* is None, the default "media loudspea...
[ "def", "new_movie_pic", "(", "cls", ",", "shapes", ",", "shape_id", ",", "movie_file", ",", "x", ",", "y", ",", "cx", ",", "cy", ",", "poster_frame_image", ",", "mime_type", ")", ":", "return", "cls", "(", "shapes", ",", "shape_id", ",", "movie_file", ...
Return a new `p:pic` element containing video in *movie_file*. If *mime_type* is None, 'video/unknown' is used. If *poster_frame_file* is None, the default "media loudspeaker" image is used.
[ "Return", "a", "new", "p", ":", "pic", "element", "containing", "video", "in", "*", "movie_file", "*", "." ]
python
train
SpriteLink/NIPAP
nipap/nipap/backend.py
https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/backend.py#L1625-L1695
def smart_search_vrf(self, auth, query_str, search_options=None, extra_query=None): """ Perform a smart search on VRF list. * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] ...
[ "def", "smart_search_vrf", "(", "self", ",", "auth", ",", "query_str", ",", "search_options", "=", "None", ",", "extra_query", "=", "None", ")", ":", "if", "search_options", "is", "None", ":", "search_options", "=", "{", "}", "self", ".", "_logger", ".", ...
Perform a smart search on VRF list. * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] Search options. See :func:`search_vrf`. * `extra_query` [dict_to_sql] ...
[ "Perform", "a", "smart", "search", "on", "VRF", "list", "." ]
python
train
bokeh/bokeh
bokeh/colors/color.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/color.py#L81-L94
def darken(self, amount): ''' Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color ''' hsl = self.to_hsl() hsl.l = self.clamp(hsl.l - amount) ...
[ "def", "darken", "(", "self", ",", "amount", ")", ":", "hsl", "=", "self", ".", "to_hsl", "(", ")", "hsl", ".", "l", "=", "self", ".", "clamp", "(", "hsl", ".", "l", "-", "amount", ")", "return", "self", ".", "from_hsl", "(", "hsl", ")" ]
Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color
[ "Darken", "(", "reduce", "the", "luminance", ")", "of", "this", "color", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xchart/xchartrenderer.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchartrenderer.py#L320-L369
def drawAxis(self, painter, rect, axis): """ Draws the axis for the given painter. :param painter | <QPainter> rect | <QRect> """ if not axis: return # draw the axis lines painter.save() ...
[ "def", "drawAxis", "(", "self", ",", "painter", ",", "rect", ",", "axis", ")", ":", "if", "not", "axis", ":", "return", "# draw the axis lines\r", "painter", ".", "save", "(", ")", "pen", "=", "QPen", "(", "self", ".", "axisColor", "(", ")", ")", "pe...
Draws the axis for the given painter. :param painter | <QPainter> rect | <QRect>
[ "Draws", "the", "axis", "for", "the", "given", "painter", ".", ":", "param", "painter", "|", "<QPainter", ">", "rect", "|", "<QRect", ">" ]
python
train
secure-systems-lab/securesystemslib
securesystemslib/pyca_crypto_keys.py
https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/pyca_crypto_keys.py#L360-L452
def verify_rsa_signature(signature, signature_scheme, public_key, data): """ <Purpose> Determine whether the corresponding private key of 'public_key' produced 'signature'. verify_signature() will use the public key, signature scheme, and 'data' to complete the verification. >>> public, private = ...
[ "def", "verify_rsa_signature", "(", "signature", ",", "signature_scheme", ",", "public_key", ",", "data", ")", ":", "# Does 'public_key' have the correct format?", "# This check will ensure 'public_key' conforms to", "# 'securesystemslib.formats.PEMRSA_SCHEMA'. Raise", "# 'securesyste...
<Purpose> Determine whether the corresponding private key of 'public_key' produced 'signature'. verify_signature() will use the public key, signature scheme, and 'data' to complete the verification. >>> public, private = generate_rsa_public_and_private(2048) >>> data = b'The quick brown fox jumps ...
[ "<Purpose", ">", "Determine", "whether", "the", "corresponding", "private", "key", "of", "public_key", "produced", "signature", ".", "verify_signature", "()", "will", "use", "the", "public", "key", "signature", "scheme", "and", "data", "to", "complete", "the", "...
python
train
stormpath/stormpath-django
django_stormpath/backends.py
https://github.com/stormpath/stormpath-django/blob/af60eb5da2115d94ac313613c5d4e6b9f3d16157/django_stormpath/backends.py#L86-L106
def authenticate(self, username=None, password=None, **kwargs): """The authenticate method takes credentials as keyword arguments, usually username/email and password. Returns a user model if the Stormpath authentication was successful or None otherwise. It expects three variable to be ...
[ "def", "authenticate", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "username", "is", "None", ":", "UserModel", "=", "get_user_model", "(", ")", "username", "=", "kwargs", ".", "get",...
The authenticate method takes credentials as keyword arguments, usually username/email and password. Returns a user model if the Stormpath authentication was successful or None otherwise. It expects three variable to be defined in Django settings: \n STORMPATH_ID = "apiKeyId...
[ "The", "authenticate", "method", "takes", "credentials", "as", "keyword", "arguments", "usually", "username", "/", "email", "and", "password", "." ]
python
train
ahmontero/dop
dop/client.py
https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L532-L558
def transfer_image(self, image_id_or_slug, region_id): """ This method allows you to transfer an image to a specified region. Required parameters image_id: Numeric, this is the id of the image you would like to transfer. region_id Numeri...
[ "def", "transfer_image", "(", "self", ",", "image_id_or_slug", ",", "region_id", ")", ":", "if", "not", "image_id_or_slug", ":", "msg", "=", "'image_id_or_slug is required to transfer an image!'", "raise", "DOPException", "(", "msg", ")", "if", "not", "region_id", "...
This method allows you to transfer an image to a specified region. Required parameters image_id: Numeric, this is the id of the image you would like to transfer. region_id Numeric, this is the id of the region to which you would like to transfer.
[ "This", "method", "allows", "you", "to", "transfer", "an", "image", "to", "a", "specified", "region", "." ]
python
train
saltstack/salt
salt/states/redismod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/redismod.py#L84-L117
def absent(name, keys=None, **connection_args): ''' Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used ''' ret = {'name': name, 'changes': {}, 'result': True, ...
[ "def", "absent", "(", "name", ",", "keys", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'Key(s) specified already...
Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used
[ "Ensure", "key", "absent", "from", "redis" ]
python
train
ska-sa/montblanc
montblanc/util/__init__.py
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/util/__init__.py#L324-L352
def shape_from_str_tuple(sshape, variables, ignore=None): """ Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral prop...
[ "def", "shape_from_str_tuple", "(", "sshape", ",", "variables", ",", "ignore", "=", "None", ")", ":", "if", "ignore", "is", "None", ":", "ignore", "=", "[", "]", "if", "not", "isinstance", "(", "sshape", ",", "tuple", ")", "and", "not", "isinstance", "...
Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral properties registered with this Solver object variables : dict...
[ "Substitutes", "string", "values", "in", "the", "supplied", "shape", "parameter", "with", "integer", "variables", "stored", "in", "a", "dictionary" ]
python
train
MediaFire/mediafire-python-open-sdk
examples/mediafire-cli.py
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/examples/mediafire-cli.py#L145-L273
def main(): # pylint: disable=too-many-statements """Main entry point""" parser = argparse.ArgumentParser(prog='mediafire-cli', description=__doc__) parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Enable de...
[ "def", "main", "(", ")", ":", "# pylint: disable=too-many-statements", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'mediafire-cli'", ",", "description", "=", "__doc__", ")", "parser", ".", "add_argument", "(", "'--debug'", ",", "dest", "...
Main entry point
[ "Main", "entry", "point" ]
python
train
log2timeline/plaso
plaso/parsers/plist_plugins/install_history.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/plist_plugins/install_history.py#L25-L55
def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs): """Extracts relevant install history entries. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. top_level (dict[str, object]): plist top-lev...
[ "def", "GetEntries", "(", "self", ",", "parser_mediator", ",", "top_level", "=", "None", ",", "*", "*", "unused_kwargs", ")", ":", "for", "entry", "in", "top_level", ":", "datetime_value", "=", "entry", ".", "get", "(", "'date'", ",", "None", ")", "packa...
Extracts relevant install history entries. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. top_level (dict[str, object]): plist top-level key.
[ "Extracts", "relevant", "install", "history", "entries", "." ]
python
train
spdx/tools-python
spdx/parsers/tagvalue.py
https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvalue.py#L451-L456
def p_file_cr_value_1(self, p): """file_cr_value : TEXT""" if six.PY2: p[0] = p[1].decode(encoding='utf-8') else: p[0] = p[1]
[ "def", "p_file_cr_value_1", "(", "self", ",", "p", ")", ":", "if", "six", ".", "PY2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", ".", "decode", "(", "encoding", "=", "'utf-8'", ")", "else", ":", "p", "[", "0", "]", "=", "p", "[", "1"...
file_cr_value : TEXT
[ "file_cr_value", ":", "TEXT" ]
python
valid
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L206-L220
def tileBounds(self, zoom, tileCol, tileRow): "Returns the bounds of a tile in LV03 (EPSG:21781)" assert zoom in range(0, len(self.RESOLUTIONS)) # 0,0 at top left: y axis down and x axis right tileSize = self.tileSize(zoom) minX = self.MINX + tileCol * tileSize maxX = se...
[ "def", "tileBounds", "(", "self", ",", "zoom", ",", "tileCol", ",", "tileRow", ")", ":", "assert", "zoom", "in", "range", "(", "0", ",", "len", "(", "self", ".", "RESOLUTIONS", ")", ")", "# 0,0 at top left: y axis down and x axis right", "tileSize", "=", "se...
Returns the bounds of a tile in LV03 (EPSG:21781)
[ "Returns", "the", "bounds", "of", "a", "tile", "in", "LV03", "(", "EPSG", ":", "21781", ")" ]
python
train
fedora-python/pyp2rpm
pyp2rpm/module_runners.py
https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/module_runners.py#L35-L42
def run(self): """Executes the code of the specified module.""" with utils.ChangeDir(self.dirname): sys.path.insert(0, self.dirname) sys.argv[1:] = self.args runpy.run_module(self.not_suffixed(self.filename), run_name='__main__', ...
[ "def", "run", "(", "self", ")", ":", "with", "utils", ".", "ChangeDir", "(", "self", ".", "dirname", ")", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "self", ".", "dirname", ")", "sys", ".", "argv", "[", "1", ":", "]", "=", "self", ...
Executes the code of the specified module.
[ "Executes", "the", "code", "of", "the", "specified", "module", "." ]
python
train
andycasey/sick
sick/clis/run.py
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/clis/run.py#L202-L224
def _announce_theta(theta): """ Announce theta values to the log. """ c = 299792.458 # km/s is_a_redshift = lambda p: p == "z" or p[:2] == "z_" for parameter, value in theta.items(): try: value[0] except (IndexError, TypeError): message = "\t{0}: {1:.3f}...
[ "def", "_announce_theta", "(", "theta", ")", ":", "c", "=", "299792.458", "# km/s", "is_a_redshift", "=", "lambda", "p", ":", "p", "==", "\"z\"", "or", "p", "[", ":", "2", "]", "==", "\"z_\"", "for", "parameter", ",", "value", "in", "theta", ".", "it...
Announce theta values to the log.
[ "Announce", "theta", "values", "to", "the", "log", "." ]
python
train
saltstack/salt
salt/utils/openstack/neutron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/neutron.py#L450-L459
def create_router(self, name, ext_network=None, admin_state_up=True): ''' Creates a new router ''' body = {'name': name, 'admin_state_up': admin_state_up} if ext_network: net_id = self._find_network_id(ext_network) body['external_gateway_in...
[ "def", "create_router", "(", "self", ",", "name", ",", "ext_network", "=", "None", ",", "admin_state_up", "=", "True", ")", ":", "body", "=", "{", "'name'", ":", "name", ",", "'admin_state_up'", ":", "admin_state_up", "}", "if", "ext_network", ":", "net_id...
Creates a new router
[ "Creates", "a", "new", "router" ]
python
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/job.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L1859-L1875
def destination_uri_file_counts(self): """Return file counts from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.extract.destinationUriFileCounts Returns: a list of integer counts, each representing the number of fi...
[ "def", "destination_uri_file_counts", "(", "self", ")", ":", "counts", "=", "self", ".", "_job_statistics", "(", ")", ".", "get", "(", "\"destinationUriFileCounts\"", ")", "if", "counts", "is", "not", "None", ":", "return", "[", "int", "(", "count", ")", "...
Return file counts from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.extract.destinationUriFileCounts Returns: a list of integer counts, each representing the number of files per destination URI or URI pattern...
[ "Return", "file", "counts", "from", "job", "statistics", "if", "present", "." ]
python
train
f3at/feat
src/feat/extern/log/log.py
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/extern/log/log.py#L557-L574
def addLogHandler(func): """ Add a custom log handler. @param func: a function object with prototype (level, object, category, message) where level is either ERROR, WARN, INFO, DEBUG, or LOG, and the rest of the arguments are strings or None. Use getLevelN...
[ "def", "addLogHandler", "(", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "TypeError", "(", "\"func must be callable\"", ")", "if", "func", "not", "in", "_log_handlers", ":", "_log_handlers", ".", "append", "(", "func", ")" ]
Add a custom log handler. @param func: a function object with prototype (level, object, category, message) where level is either ERROR, WARN, INFO, DEBUG, or LOG, and the rest of the arguments are strings or None. Use getLevelName(level) to get a printable name fo...
[ "Add", "a", "custom", "log", "handler", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/pipeline/run_info.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L402-L413
def _clean_characters(x): """Clean problem characters in sample lane or descriptions. """ if not isinstance(x, six.string_types): x = str(x) else: if not all(ord(char) < 128 for char in x): msg = "Found unicode character in input YAML (%s)" % (x) raise ValueError(...
[ "def", "_clean_characters", "(", "x", ")", ":", "if", "not", "isinstance", "(", "x", ",", "six", ".", "string_types", ")", ":", "x", "=", "str", "(", "x", ")", "else", ":", "if", "not", "all", "(", "ord", "(", "char", ")", "<", "128", "for", "c...
Clean problem characters in sample lane or descriptions.
[ "Clean", "problem", "characters", "in", "sample", "lane", "or", "descriptions", "." ]
python
train
adamchainz/django-perf-rec
django_perf_rec/utils.py
https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/utils.py#L82-L98
def sorted_names(names): """ Sort a list of names but keep the word 'default' first if it's there. """ names = list(names) have_default = False if 'default' in names: names.remove('default') have_default = True sorted_names = sorted(names) if have_default: sort...
[ "def", "sorted_names", "(", "names", ")", ":", "names", "=", "list", "(", "names", ")", "have_default", "=", "False", "if", "'default'", "in", "names", ":", "names", ".", "remove", "(", "'default'", ")", "have_default", "=", "True", "sorted_names", "=", ...
Sort a list of names but keep the word 'default' first if it's there.
[ "Sort", "a", "list", "of", "names", "but", "keep", "the", "word", "default", "first", "if", "it", "s", "there", "." ]
python
train
codelv/enaml-native
src/enamlnative/android/android_spinner.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_spinner.py#L53-L63
def create_widget(self): """ Create the underlying label widget. """ d = self.declaration mode = 1 if d.mode == 'dropdown' else 0 self.widget = Spinner(self.get_context(), mode) # Create the adapter simple_spinner_item = 0x01090008 self.adapter = ArrayAdapter(se...
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "mode", "=", "1", "if", "d", ".", "mode", "==", "'dropdown'", "else", "0", "self", ".", "widget", "=", "Spinner", "(", "self", ".", "get_context", "(", ")", ",", "...
Create the underlying label widget.
[ "Create", "the", "underlying", "label", "widget", "." ]
python
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L427-L451
def Page_deleteCookie(self, cookieName, url): """ Function path: Page.deleteCookie Domain: Page Method name: deleteCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookieName' (type: string) -> Name of the cookie to remove. 'url' (type: string)...
[ "def", "Page_deleteCookie", "(", "self", ",", "cookieName", ",", "url", ")", ":", "assert", "isinstance", "(", "cookieName", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'cookieName' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "cookieNam...
Function path: Page.deleteCookie Domain: Page Method name: deleteCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookieName' (type: string) -> Name of the cookie to remove. 'url' (type: string) -> URL to match cooke domain and path. No return v...
[ "Function", "path", ":", "Page", ".", "deleteCookie", "Domain", ":", "Page", "Method", "name", ":", "deleteCookie", "WARNING", ":", "This", "function", "is", "marked", "Experimental", "!", "Parameters", ":", "Required", "arguments", ":", "cookieName", "(", "ty...
python
train
geertj/gruvi
lib/gruvi/http.py
https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L303-L327
def parse_url(url, default_scheme='http', is_connect=False): """Parse an URL and return its components. The *default_scheme* argument specifies the scheme in case URL is an otherwise valid absolute URL but with a missing scheme. The *is_connect* argument must be set to ``True`` if the URL was requeste...
[ "def", "parse_url", "(", "url", ",", "default_scheme", "=", "'http'", ",", "is_connect", "=", "False", ")", ":", "# If this is not in origin-form, authority-form or asterisk-form and no", "# scheme is present, assume it's in absolute-form with a missing scheme.", "# See RFC7230 secti...
Parse an URL and return its components. The *default_scheme* argument specifies the scheme in case URL is an otherwise valid absolute URL but with a missing scheme. The *is_connect* argument must be set to ``True`` if the URL was requested with the HTTP CONNECT method. These URLs have a different form...
[ "Parse", "an", "URL", "and", "return", "its", "components", "." ]
python
train
marcomusy/vtkplotter
vtkplotter/colors.py
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/colors.py#L386-L413
def makeLUTfromCTF(sclist, N=None): """ Use a Color Transfer Function to generate colors in a vtk lookup table. See `here <http://www.vtk.org/doc/nightly/html/classvtkColorTransferFunction.html>`_. :param list sclist: a list in the form ``[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]``. :return: the...
[ "def", "makeLUTfromCTF", "(", "sclist", ",", "N", "=", "None", ")", ":", "ctf", "=", "vtk", ".", "vtkColorTransferFunction", "(", ")", "ctf", ".", "SetColorSpaceToDiverging", "(", ")", "for", "sc", "in", "sclist", ":", "scalar", ",", "col", "=", "sc", ...
Use a Color Transfer Function to generate colors in a vtk lookup table. See `here <http://www.vtk.org/doc/nightly/html/classvtkColorTransferFunction.html>`_. :param list sclist: a list in the form ``[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]``. :return: the lookup table object ``vtkLookupTable``. This ca...
[ "Use", "a", "Color", "Transfer", "Function", "to", "generate", "colors", "in", "a", "vtk", "lookup", "table", ".", "See", "here", "<http", ":", "//", "www", ".", "vtk", ".", "org", "/", "doc", "/", "nightly", "/", "html", "/", "classvtkColorTransferFunct...
python
train
pyusb/pyusb
usb/legacy.py
https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L220-L223
def releaseInterface(self): r"""Release an interface previously claimed with claimInterface.""" util.release_interface(self.dev, self.__claimed_interface) self.__claimed_interface = -1
[ "def", "releaseInterface", "(", "self", ")", ":", "util", ".", "release_interface", "(", "self", ".", "dev", ",", "self", ".", "__claimed_interface", ")", "self", ".", "__claimed_interface", "=", "-", "1" ]
r"""Release an interface previously claimed with claimInterface.
[ "r", "Release", "an", "interface", "previously", "claimed", "with", "claimInterface", "." ]
python
train
vmware/pyvmomi
pyVmomi/DynamicTypeManagerHelper.py
https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVmomi/DynamicTypeManagerHelper.py#L227-L242
def _ConvertManagedType(self, managedType): """ Convert vmodl.reflect.DynamicTypeManager.ManagedTypeInfo to pyVmomi managed type definition """ if managedType: vmodlName = managedType.name wsdlName = managedType.wsdlName version = managedType.version par...
[ "def", "_ConvertManagedType", "(", "self", ",", "managedType", ")", ":", "if", "managedType", ":", "vmodlName", "=", "managedType", ".", "name", "wsdlName", "=", "managedType", ".", "wsdlName", "version", "=", "managedType", ".", "version", "parent", "=", "man...
Convert vmodl.reflect.DynamicTypeManager.ManagedTypeInfo to pyVmomi managed type definition
[ "Convert", "vmodl", ".", "reflect", ".", "DynamicTypeManager", ".", "ManagedTypeInfo", "to", "pyVmomi", "managed", "type", "definition" ]
python
train
thumbor/thumbor
thumbor/url_composer.py
https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/url_composer.py#L159-L183
def main(arguments=None): '''Converts a given url with the specified arguments.''' parsed_options, arguments = get_options(arguments) image_url = arguments[0] image_url = quote(image_url) try: config = Config.load(None) except Exception: config = None if not parsed_option...
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "parsed_options", ",", "arguments", "=", "get_options", "(", "arguments", ")", "image_url", "=", "arguments", "[", "0", "]", "image_url", "=", "quote", "(", "image_url", ")", "try", ":", "config", "...
Converts a given url with the specified arguments.
[ "Converts", "a", "given", "url", "with", "the", "specified", "arguments", "." ]
python
train
LonamiWebs/Telethon
telethon_generator/generators/docs.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L28-L33
def get_import_code(tlobject): """``TLObject -> from ... import ...``.""" kind = 'functions' if tlobject.is_function else 'types' ns = '.' + tlobject.namespace if tlobject.namespace else '' return 'from telethon.tl.{}{} import {}'\ .format(kind, ns, tlobject.class_name)
[ "def", "get_import_code", "(", "tlobject", ")", ":", "kind", "=", "'functions'", "if", "tlobject", ".", "is_function", "else", "'types'", "ns", "=", "'.'", "+", "tlobject", ".", "namespace", "if", "tlobject", ".", "namespace", "else", "''", "return", "'from ...
``TLObject -> from ... import ...``.
[ "TLObject", "-", ">", "from", "...", "import", "...", "." ]
python
train
cox-labs/perseuspy
perseuspy/io/perseus/matrix.py
https://github.com/cox-labs/perseuspy/blob/3809c1bd46512605f9e7ca7f97e026e4940ed604/perseuspy/io/perseus/matrix.py#L105-L147
def to_perseus(df, path_or_file, main_columns=None, separator=separator, convert_bool_to_category=True, numerical_annotation_rows = set([])): """ Save pd.DataFrame to Perseus text format. :param df: pd.DataFrame. :param path_or_file: File name or file-like object. :param mai...
[ "def", "to_perseus", "(", "df", ",", "path_or_file", ",", "main_columns", "=", "None", ",", "separator", "=", "separator", ",", "convert_bool_to_category", "=", "True", ",", "numerical_annotation_rows", "=", "set", "(", "[", "]", ")", ")", ":", "_df", "=", ...
Save pd.DataFrame to Perseus text format. :param df: pd.DataFrame. :param path_or_file: File name or file-like object. :param main_columns: Main columns. Will be infered if set to None. All numeric columns up-until the first non-numeric column are considered main columns. :param separator: For separati...
[ "Save", "pd", ".", "DataFrame", "to", "Perseus", "text", "format", "." ]
python
train
timofurrer/observable
observable/core.py
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L53-L57
def is_registered(self, event: str, handler: T.Callable) -> bool: """Returns whether the given handler is registered for the given event.""" return handler in self._events.get(event, [])
[ "def", "is_registered", "(", "self", ",", "event", ":", "str", ",", "handler", ":", "T", ".", "Callable", ")", "->", "bool", ":", "return", "handler", "in", "self", ".", "_events", ".", "get", "(", "event", ",", "[", "]", ")" ]
Returns whether the given handler is registered for the given event.
[ "Returns", "whether", "the", "given", "handler", "is", "registered", "for", "the", "given", "event", "." ]
python
train
gesellkammer/sndfileio
sndfileio/resampling.py
https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L191-L213
def _resample_obspy(samples, sr, newsr, window='hanning', lowpass=True): # type: (np.ndarray, int, int, str, bool) -> np.ndarray """ Resample using Fourier method. The same as resample_scipy but with low-pass filtering for upsampling """ from scipy.signal import resample from math import ce...
[ "def", "_resample_obspy", "(", "samples", ",", "sr", ",", "newsr", ",", "window", "=", "'hanning'", ",", "lowpass", "=", "True", ")", ":", "# type: (np.ndarray, int, int, str, bool) -> np.ndarray", "from", "scipy", ".", "signal", "import", "resample", "from", "mat...
Resample using Fourier method. The same as resample_scipy but with low-pass filtering for upsampling
[ "Resample", "using", "Fourier", "method", ".", "The", "same", "as", "resample_scipy", "but", "with", "low", "-", "pass", "filtering", "for", "upsampling" ]
python
train
annoviko/pyclustering
pyclustering/nnet/examples/syncpr_examples.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/examples/syncpr_examples.py#L106-L116
def small_ftk_image_recognition(): """! @brief Trains network using letters 'F', 'T', 'K' and recognize each of them with and without noise. """ images = []; images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_F; images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_T; images += IMAGE...
[ "def", "small_ftk_image_recognition", "(", ")", ":", "images", "=", "[", "]", "images", "+=", "IMAGE_SYMBOL_SAMPLES", ".", "LIST_IMAGES_SYMBOL_F", "images", "+=", "IMAGE_SYMBOL_SAMPLES", ".", "LIST_IMAGES_SYMBOL_T", "images", "+=", "IMAGE_SYMBOL_SAMPLES", ".", "LIST_IMA...
! @brief Trains network using letters 'F', 'T', 'K' and recognize each of them with and without noise.
[ "!" ]
python
valid
lsbardel/python-stdnet
stdnet/odm/struct.py
https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/struct.py#L588-L592
def pop_back(self): '''Remove the last element from the :class:`Sequence`.''' backend = self.backend return backend.execute(backend.structure(self).pop_back(), self.value_pickler.loads)
[ "def", "pop_back", "(", "self", ")", ":", "backend", "=", "self", ".", "backend", "return", "backend", ".", "execute", "(", "backend", ".", "structure", "(", "self", ")", ".", "pop_back", "(", ")", ",", "self", ".", "value_pickler", ".", "loads", ")" ]
Remove the last element from the :class:`Sequence`.
[ "Remove", "the", "last", "element", "from", "the", ":", "class", ":", "Sequence", "." ]
python
train
eykd/paved
paved/pycheck.py
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/pycheck.py#L37-L71
def sloccount(): '''Print "Source Lines of Code" and export to file. Export is hudson_ plugin_ compatible: sloccount.sc requirements: - sloccount_ should be installed. - tee and pipes are used options.paved.pycheck.sloccount.param .. _sloccount: http://www.dwheeler.com/sloccount/ ....
[ "def", "sloccount", "(", ")", ":", "# filter out subpackages", "setup", "=", "options", ".", "get", "(", "'setup'", ")", "packages", "=", "options", ".", "get", "(", "'packages'", ")", "if", "setup", "else", "None", "if", "packages", ":", "dirs", "=", "...
Print "Source Lines of Code" and export to file. Export is hudson_ plugin_ compatible: sloccount.sc requirements: - sloccount_ should be installed. - tee and pipes are used options.paved.pycheck.sloccount.param .. _sloccount: http://www.dwheeler.com/sloccount/ .. _hudson: http://hudson...
[ "Print", "Source", "Lines", "of", "Code", "and", "export", "to", "file", "." ]
python
valid
spacetelescope/stsci.tools
lib/stsci/tools/iterfile.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/iterfile.py#L111-L153
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. Modified from 'pydrizzle.fileutil' to allow this module to be independent of PyDrizzle/MultiDrizzle. """ # Parse out any extension speci...
[ "def", "parseFilename", "(", "filename", ")", ":", "# Parse out any extension specified in filename", "_indx", "=", "filename", ".", "find", "(", "'['", ")", "if", "_indx", ">", "0", ":", "# Read extension name provided", "_fname", "=", "filename", "[", ":", "_ind...
Parse out filename from any specified extensions. Returns rootname and string version of extension name. Modified from 'pydrizzle.fileutil' to allow this module to be independent of PyDrizzle/MultiDrizzle.
[ "Parse", "out", "filename", "from", "any", "specified", "extensions", ".", "Returns", "rootname", "and", "string", "version", "of", "extension", "name", "." ]
python
train
cackharot/suds-py3
suds/wsse.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/wsse.py#L160-L181
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Passw...
[ "def", "xml", "(", "self", ")", ":", "root", "=", "Element", "(", "'UsernameToken'", ",", "ns", "=", "wssens", ")", "u", "=", "Element", "(", "'Username'", ",", "ns", "=", "wssens", ")", "u", ".", "setText", "(", "self", ".", "username", ")", "root...
Get xml representation of the object. @return: The root node. @rtype: L{Element}
[ "Get", "xml", "representation", "of", "the", "object", "." ]
python
train
AguaClara/aguaclara
aguaclara/core/drills.py
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/drills.py#L8-L18
def get_drill_bits_d_imperial(): """Return array of possible drill diameters in imperial.""" step_32nd = np.arange(0.03125, 0.25, 0.03125) step_8th = np.arange(0.25, 1.0, 0.125) step_4th = np.arange(1.0, 2.0, 0.25) maximum = [2.0] return np.concatenate((step_32nd, ste...
[ "def", "get_drill_bits_d_imperial", "(", ")", ":", "step_32nd", "=", "np", ".", "arange", "(", "0.03125", ",", "0.25", ",", "0.03125", ")", "step_8th", "=", "np", ".", "arange", "(", "0.25", ",", "1.0", ",", "0.125", ")", "step_4th", "=", "np", ".", ...
Return array of possible drill diameters in imperial.
[ "Return", "array", "of", "possible", "drill", "diameters", "in", "imperial", "." ]
python
train
sendgrid/sendgrid-python
sendgrid/helpers/mail/attachment.py
https://github.com/sendgrid/sendgrid-python/blob/266c2abde7a35dfcce263e06bedc6a0bbdebeac9/sendgrid/helpers/mail/attachment.py#L196-L218
def get(self): """ Get a JSON-ready representation of this Attachment. :returns: This Attachment, ready for use in a request body. :rtype: dict """ attachment = {} if self.file_content is not None: attachment["content"] = self.file_content.get() ...
[ "def", "get", "(", "self", ")", ":", "attachment", "=", "{", "}", "if", "self", ".", "file_content", "is", "not", "None", ":", "attachment", "[", "\"content\"", "]", "=", "self", ".", "file_content", ".", "get", "(", ")", "if", "self", ".", "file_typ...
Get a JSON-ready representation of this Attachment. :returns: This Attachment, ready for use in a request body. :rtype: dict
[ "Get", "a", "JSON", "-", "ready", "representation", "of", "this", "Attachment", "." ]
python
train
facetoe/zenpy
zenpy/lib/api_objects/__init__.py
https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api_objects/__init__.py#L56-L67
def to_dict(self, serialize=False): """ This method returns the object as a Python dict. If serialize is passed, only those attributes that have been modified will be included in the result. :param serialize: :return: """ if serialize: encode_method = ...
[ "def", "to_dict", "(", "self", ",", "serialize", "=", "False", ")", ":", "if", "serialize", ":", "encode_method", "=", "json_encode_for_zendesk", "else", ":", "encode_method", "=", "json_encode_for_printing", "return", "json", ".", "loads", "(", "json", ".", "...
This method returns the object as a Python dict. If serialize is passed, only those attributes that have been modified will be included in the result. :param serialize: :return:
[ "This", "method", "returns", "the", "object", "as", "a", "Python", "dict", ".", "If", "serialize", "is", "passed", "only", "those", "attributes", "that", "have", "been", "modified", "will", "be", "included", "in", "the", "result", ".", ":", "param", "seria...
python
train
colab/colab
colab/accounts/utils/validators.py
https://github.com/colab/colab/blob/2ad099231e620bec647363b27d38006eca71e13b/colab/accounts/utils/validators.py#L6-L28
def validate_social_account(account, url): """Verifies if a social account is valid. Examples: >>> validate_social_account('seocam', 'http://twitter.com') True >>> validate_social_account('seocam-fake-should-fail', 'http://twitter.com') False """ requ...
[ "def", "validate_social_account", "(", "account", ",", "url", ")", ":", "request", "=", "urllib2", ".", "Request", "(", "urlparse", ".", "urljoin", "(", "url", ",", "account", ")", ")", "request", ".", "get_method", "=", "lambda", ":", "'HEAD'", "try", "...
Verifies if a social account is valid. Examples: >>> validate_social_account('seocam', 'http://twitter.com') True >>> validate_social_account('seocam-fake-should-fail', 'http://twitter.com') False
[ "Verifies", "if", "a", "social", "account", "is", "valid", "." ]
python
train
Groundworkstech/pybfd
setup.py
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/setup.py#L117-L142
def find_binutils_libs(self, libdir, lib_ext): """Find Binutils libraries.""" bfd_expr = re.compile("(lib(?:bfd)|(?:opcodes))(.*?)\%s" % lib_ext ) libs = {} for root, dirs, files in os.walk(libdir): for f in files: m = bfd_expr.search(f) if m: ...
[ "def", "find_binutils_libs", "(", "self", ",", "libdir", ",", "lib_ext", ")", ":", "bfd_expr", "=", "re", ".", "compile", "(", "\"(lib(?:bfd)|(?:opcodes))(.*?)\\%s\"", "%", "lib_ext", ")", "libs", "=", "{", "}", "for", "root", ",", "dirs", ",", "files", "i...
Find Binutils libraries.
[ "Find", "Binutils", "libraries", "." ]
python
train
MrYsLab/pymata-aio
pymata_aio/pymata_core.py
https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_core.py#L1683-L1724
async def _report_firmware(self, sysex_data): """ This is a private message handler method. This method handles the sysex 'report firmware' command sent by Firmata (0x79). It assembles the firmware version by concatenating the major and minor version number components an...
[ "async", "def", "_report_firmware", "(", "self", ",", "sysex_data", ")", ":", "# first byte after command is major number", "major", "=", "sysex_data", "[", "1", "]", "version_string", "=", "str", "(", "major", ")", "# next byte is minor number", "minor", "=", "syse...
This is a private message handler method. This method handles the sysex 'report firmware' command sent by Firmata (0x79). It assembles the firmware version by concatenating the major and minor version number components and the firmware identifier into a string. e.g. "2.3...
[ "This", "is", "a", "private", "message", "handler", "method", ".", "This", "method", "handles", "the", "sysex", "report", "firmware", "command", "sent", "by", "Firmata", "(", "0x79", ")", ".", "It", "assembles", "the", "firmware", "version", "by", "concatena...
python
train
TrafficSenseMSD/SumoTools
traci/_vehicletype.py
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/traci/_vehicletype.py#L380-L386
def copy(self, origTypeID, newTypeID): """copy(string, string) -> None Duplicates the vType with ID origTypeID. The newly created vType is assigned the ID newTypeID """ self._connection._sendStringCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.COPY, origTypeID, newTypeID)
[ "def", "copy", "(", "self", ",", "origTypeID", ",", "newTypeID", ")", ":", "self", ".", "_connection", ".", "_sendStringCmd", "(", "tc", ".", "CMD_SET_VEHICLETYPE_VARIABLE", ",", "tc", ".", "COPY", ",", "origTypeID", ",", "newTypeID", ")" ]
copy(string, string) -> None Duplicates the vType with ID origTypeID. The newly created vType is assigned the ID newTypeID
[ "copy", "(", "string", "string", ")", "-", ">", "None" ]
python
train
fboender/ansible-cmdb
lib/jsonxs.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/jsonxs.py#L88-L127
def tokenize(expr): """ Parse a string expression into a set of tokens that can be used as a path into a Python datastructure. """ tokens = [] escape = False cur_token = '' for c in expr: if escape == True: cur_token += c escape = False else: ...
[ "def", "tokenize", "(", "expr", ")", ":", "tokens", "=", "[", "]", "escape", "=", "False", "cur_token", "=", "''", "for", "c", "in", "expr", ":", "if", "escape", "==", "True", ":", "cur_token", "+=", "c", "escape", "=", "False", "else", ":", "if", ...
Parse a string expression into a set of tokens that can be used as a path into a Python datastructure.
[ "Parse", "a", "string", "expression", "into", "a", "set", "of", "tokens", "that", "can", "be", "used", "as", "a", "path", "into", "a", "Python", "datastructure", "." ]
python
train
DEIB-GECO/PyGMQL
gmql/ml/algorithms/clustering.py
https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/algorithms/clustering.py#L214-L232
def fit(self, data=None): """ Performs clustering.rst :param data: Data to be fit :return: the clustering.rst object """ if self.is_pyclustering_instance(self.model): if isinstance(self.model, xmeans): data = self.input_preprocess(data) ...
[ "def", "fit", "(", "self", ",", "data", "=", "None", ")", ":", "if", "self", ".", "is_pyclustering_instance", "(", "self", ".", "model", ")", ":", "if", "isinstance", "(", "self", ".", "model", ",", "xmeans", ")", ":", "data", "=", "self", ".", "in...
Performs clustering.rst :param data: Data to be fit :return: the clustering.rst object
[ "Performs", "clustering", ".", "rst" ]
python
train
wbond/pybars3
pybars/_compiler.py
https://github.com/wbond/pybars3/blob/71f13d1012d3746e76099d8db141c43fc769cfed/pybars/_compiler.py#L852-L891
def compile(self, source, path=None): """Compile source to a ready to run template. :param source: The template to compile - should be a unicode string :return: A template function ready to execute """ container = self._generate_code(source) de...
[ "def", "compile", "(", "self", ",", "source", ",", "path", "=", "None", ")", ":", "container", "=", "self", ".", "_generate_code", "(", "source", ")", "def", "make_module_name", "(", "name", ",", "suffix", "=", "None", ")", ":", "output", "=", "'pybars...
Compile source to a ready to run template. :param source: The template to compile - should be a unicode string :return: A template function ready to execute
[ "Compile", "source", "to", "a", "ready", "to", "run", "template", "." ]
python
train
wdbm/shijian
shijian.py
https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1231-L1242
def ustr(text): """ Convert a string to Python 2 unicode or Python 3 string as appropriate to the version of Python in use. """ if text is not None: if sys.version_info >= (3, 0): return str(text) else: return unicode(text) else: return text
[ "def", "ustr", "(", "text", ")", ":", "if", "text", "is", "not", "None", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "return", "str", "(", "text", ")", "else", ":", "return", "unicode", "(", "text", ")", "else", "...
Convert a string to Python 2 unicode or Python 3 string as appropriate to the version of Python in use.
[ "Convert", "a", "string", "to", "Python", "2", "unicode", "or", "Python", "3", "string", "as", "appropriate", "to", "the", "version", "of", "Python", "in", "use", "." ]
python
train
odlgroup/odl
odl/tomo/geometry/parallel.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/geometry/parallel.py#L196-L325
def det_to_src(self, angle, dparam): """Direction from a detector location to the source. The direction vector is computed as follows:: dir = rotation_matrix(angle).dot(detector.surface_normal(dparam)) Note that for flat detectors, ``surface_normal`` does not depend on the...
[ "def", "det_to_src", "(", "self", ",", "angle", ",", "dparam", ")", ":", "# Always call the downstream methods with vectorized arguments", "# to be able to reliably manipulate the final axes of the result", "if", "self", ".", "motion_params", ".", "ndim", "==", "1", ":", "s...
Direction from a detector location to the source. The direction vector is computed as follows:: dir = rotation_matrix(angle).dot(detector.surface_normal(dparam)) Note that for flat detectors, ``surface_normal`` does not depend on the parameter ``dparam``, hence this function is co...
[ "Direction", "from", "a", "detector", "location", "to", "the", "source", "." ]
python
train
rvswift/EB
EB/builder/exhaustive/exhaustive.py
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/exhaustive/exhaustive.py#L19-L60
def run(itf): """ Run optimize functions. """ if not itf: return 1 # access user input options = SplitInput(itf) # read input inputpath = os.path.abspath(options.inputpath) print(" Reading input file ...") molecules = csv_interface.read_csv(inputpath, options) if not mol...
[ "def", "run", "(", "itf", ")", ":", "if", "not", "itf", ":", "return", "1", "# access user input", "options", "=", "SplitInput", "(", "itf", ")", "# read input", "inputpath", "=", "os", ".", "path", ".", "abspath", "(", "options", ".", "inputpath", ")", ...
Run optimize functions.
[ "Run", "optimize", "functions", "." ]
python
train
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L206-L305
def get_equation_components(equation_str): """ Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model...
[ "def", "get_equation_components", "(", "equation_str", ")", ":", "component_structure_grammar", "=", "_include_common_grammar", "(", "r\"\"\"\n entry = component / subscript_definition / lookup_definition\n component = name _ subscriptlist? _ \"=\" _ expression\n subscript_definition = ...
Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model element - the full equation. Returns ------- ...
[ "Breaks", "down", "a", "string", "representing", "only", "the", "equation", "part", "of", "a", "model", "element", ".", "Recognizes", "the", "various", "types", "of", "model", "elements", "that", "may", "exist", "and", "identifies", "them", "." ]
python
train
conbus/fbmq
fbmq/fbmq.py
https://github.com/conbus/fbmq/blob/2e016597e49d4d3d8bd52a4da5d778b992697649/fbmq/fbmq.py#L523-L536
def set_webhook_handler(self, scope, callback): """ Allows adding a webhook_handler as an alternative to the decorators """ scope = scope.lower() if scope == 'after_send': self._after_send = callback return if scope not in Page.WEBHOOK_ENDPOINTS:...
[ "def", "set_webhook_handler", "(", "self", ",", "scope", ",", "callback", ")", ":", "scope", "=", "scope", ".", "lower", "(", ")", "if", "scope", "==", "'after_send'", ":", "self", ".", "_after_send", "=", "callback", "return", "if", "scope", "not", "in"...
Allows adding a webhook_handler as an alternative to the decorators
[ "Allows", "adding", "a", "webhook_handler", "as", "an", "alternative", "to", "the", "decorators" ]
python
train
agile4you/SchemaFactory
schema_factory/schema.py
https://github.com/agile4you/SchemaFactory/blob/515e3fb84cddf70fc17e5d300c74c3a63539f223/schema_factory/schema.py#L108-L200
def schema_factory(schema_name, **schema_nodes): """Schema Validation class factory. Args: schema_name(str): The namespace of the schema. schema_nodes(dict): The attr_names / SchemaNodes mapping of schema. Returns: A Schema class. Raises: SchemaError, for bad attribute...
[ "def", "schema_factory", "(", "schema_name", ",", "*", "*", "schema_nodes", ")", ":", "schema_dict", "=", "dict", "(", ")", "schema_dict", ".", "update", "(", "schema_nodes", ")", "def", "cls_repr", "(", "self", ")", ":", "# pragma: no cover", "return", "\"<...
Schema Validation class factory. Args: schema_name(str): The namespace of the schema. schema_nodes(dict): The attr_names / SchemaNodes mapping of schema. Returns: A Schema class. Raises: SchemaError, for bad attribute setting initialization. Examples: >>> fro...
[ "Schema", "Validation", "class", "factory", "." ]
python
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py#L86-L90
def main(_): """Run the sample attack""" batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3] for filenames, images in load_images(FLAGS.input_dir, batch_shape): save_images(images, filenames, FLAGS.output_dir)
[ "def", "main", "(", "_", ")", ":", "batch_shape", "=", "[", "FLAGS", ".", "batch_size", ",", "FLAGS", ".", "image_height", ",", "FLAGS", ".", "image_width", ",", "3", "]", "for", "filenames", ",", "images", "in", "load_images", "(", "FLAGS", ".", "inpu...
Run the sample attack
[ "Run", "the", "sample", "attack" ]
python
train
Genida/archan
src/archan/dsm.py
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/dsm.py#L90-L96
def validate(self): """Validate data (rows length, categories=entities, square).""" validate_rows_length(self.data, self.columns, exception=self.error) validate_categories_equal_entities(self.categories, self.entities, exception=self.error) if s...
[ "def", "validate", "(", "self", ")", ":", "validate_rows_length", "(", "self", ".", "data", ",", "self", ".", "columns", ",", "exception", "=", "self", ".", "error", ")", "validate_categories_equal_entities", "(", "self", ".", "categories", ",", "self", ".",...
Validate data (rows length, categories=entities, square).
[ "Validate", "data", "(", "rows", "length", "categories", "=", "entities", "square", ")", "." ]
python
train
GNS3/gns3-server
gns3server/controller/export_project.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/export_project.py#L231-L268
def _export_remote_images(project, compute_id, image_type, image, project_zipfile, temporary_dir): """ Export specific image from remote compute :param project: :param compute_id: :param image_type: :param image: :param project_zipfile: :return: """ log.info("Obtaining image `{}...
[ "def", "_export_remote_images", "(", "project", ",", "compute_id", ",", "image_type", ",", "image", ",", "project_zipfile", ",", "temporary_dir", ")", ":", "log", ".", "info", "(", "\"Obtaining image `{}` from `{}`\"", ".", "format", "(", "image", ",", "compute_id...
Export specific image from remote compute :param project: :param compute_id: :param image_type: :param image: :param project_zipfile: :return:
[ "Export", "specific", "image", "from", "remote", "compute", ":", "param", "project", ":", ":", "param", "compute_id", ":", ":", "param", "image_type", ":", ":", "param", "image", ":", ":", "param", "project_zipfile", ":", ":", "return", ":" ]
python
train
trac-hacks/trac-github
tracext/github/__init__.py
https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L648-L686
def github_api(self, url, *args): """ Connect to the given GitHub API URL template by replacing all placeholders with the given parameters and return the decoded JSON result on success. On error, return `None`. :param url: The path to request from the GitHub API. Contains format...
[ "def", "github_api", "(", "self", ",", "url", ",", "*", "args", ")", ":", "import", "requests", "import", "urllib", "github_api_url", "=", "os", ".", "environ", ".", "get", "(", "\"TRAC_GITHUB_API_URL\"", ",", "\"https://api.github.com/\"", ")", "formatted_url",...
Connect to the given GitHub API URL template by replacing all placeholders with the given parameters and return the decoded JSON result on success. On error, return `None`. :param url: The path to request from the GitHub API. Contains format string placeholders that will be ...
[ "Connect", "to", "the", "given", "GitHub", "API", "URL", "template", "by", "replacing", "all", "placeholders", "with", "the", "given", "parameters", "and", "return", "the", "decoded", "JSON", "result", "on", "success", ".", "On", "error", "return", "None", "...
python
train
priestc/moneywagon
moneywagon/tx.py
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L67-L77
def private_key_to_address(self, pk): """ Convert a private key (in hex format) into an address. """ pub = privtopub(pk) pub_byte, priv_byte = get_magic_bytes(self.crypto) if priv_byte >= 128: priv_byte -= 128 #pybitcointools bug return pubtoaddr(pub...
[ "def", "private_key_to_address", "(", "self", ",", "pk", ")", ":", "pub", "=", "privtopub", "(", "pk", ")", "pub_byte", ",", "priv_byte", "=", "get_magic_bytes", "(", "self", ".", "crypto", ")", "if", "priv_byte", ">=", "128", ":", "priv_byte", "-=", "12...
Convert a private key (in hex format) into an address.
[ "Convert", "a", "private", "key", "(", "in", "hex", "format", ")", "into", "an", "address", "." ]
python
train
CiscoDevNet/webexteamssdk
webexteamssdk/restsession.py
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L184-L197
def update_headers(self, headers): """Update the HTTP headers used for requests in this session. Note: Updates provided by the dictionary passed as the `headers` parameter to this method are merged into the session headers by adding new key-value pairs and/or updating the values of exis...
[ "def", "update_headers", "(", "self", ",", "headers", ")", ":", "check_type", "(", "headers", ",", "dict", ",", "may_be_none", "=", "False", ")", "self", ".", "_req_session", ".", "headers", ".", "update", "(", "headers", ")" ]
Update the HTTP headers used for requests in this session. Note: Updates provided by the dictionary passed as the `headers` parameter to this method are merged into the session headers by adding new key-value pairs and/or updating the values of existing keys. The session headers are not...
[ "Update", "the", "HTTP", "headers", "used", "for", "requests", "in", "this", "session", "." ]
python
test
adafruit/Adafruit_Python_GPIO
Adafruit_GPIO/I2C.py
https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/I2C.py#L40-L57
def get_default_bus(): """Return the default bus number based on the device platform. For a Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned. For a Beaglebone Black the first user accessible bus, 1, will be returned. """ plat = Platform.platform_detect() if plat == Pla...
[ "def", "get_default_bus", "(", ")", ":", "plat", "=", "Platform", ".", "platform_detect", "(", ")", "if", "plat", "==", "Platform", ".", "RASPBERRY_PI", ":", "if", "Platform", ".", "pi_revision", "(", ")", "==", "1", ":", "# Revision 1 Pi uses I2C bus 0.", "...
Return the default bus number based on the device platform. For a Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned. For a Beaglebone Black the first user accessible bus, 1, will be returned.
[ "Return", "the", "default", "bus", "number", "based", "on", "the", "device", "platform", ".", "For", "a", "Raspberry", "Pi", "either", "bus", "0", "or", "1", "(", "based", "on", "the", "Pi", "revision", ")", "will", "be", "returned", ".", "For", "a", ...
python
valid
log2timeline/plaso
plaso/cli/log2timeline_tool.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/log2timeline_tool.py#L138-L277
def ParseArguments(self): """Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed. """ loggers.ConfigureLogging() argument_parser = argparse.ArgumentParser( description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False, formatter...
[ "def", "ParseArguments", "(", "self", ")", ":", "loggers", ".", "ConfigureLogging", "(", ")", "argument_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "self", ".", "DESCRIPTION", ",", "epilog", "=", "self", ".", "EPILOG", ",", "add...
Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed.
[ "Parses", "the", "command", "line", "arguments", "." ]
python
train
rix0rrr/gcl
gcl/ast_util.py
https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L75-L98
def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False): """Return a dict of { name => Completions } for the given tuple node. Enumerates all keys that are in scope in a given tuple. The node part of the tuple may be None, in case the binding is a built-in. """ with util.LogTime('enu...
[ "def", "enumerate_scope", "(", "ast_rootpath", ",", "root_env", "=", "None", ",", "include_default_builtins", "=", "False", ")", ":", "with", "util", ".", "LogTime", "(", "'enumerate_scope'", ")", ":", "scope", "=", "{", "}", "for", "node", "in", "reversed",...
Return a dict of { name => Completions } for the given tuple node. Enumerates all keys that are in scope in a given tuple. The node part of the tuple may be None, in case the binding is a built-in.
[ "Return", "a", "dict", "of", "{", "name", "=", ">", "Completions", "}", "for", "the", "given", "tuple", "node", "." ]
python
train
evhub/coconut
coconut/terminal.py
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/terminal.py#L269-L282
def gather_parsing_stats(self): """Times parsing if --verbose.""" if self.verbose: start_time = time.clock() try: yield finally: elapsed_time = time.clock() - start_time printerr("Time while parsing:", elapsed_time, "sec...
[ "def", "gather_parsing_stats", "(", "self", ")", ":", "if", "self", ".", "verbose", ":", "start_time", "=", "time", ".", "clock", "(", ")", "try", ":", "yield", "finally", ":", "elapsed_time", "=", "time", ".", "clock", "(", ")", "-", "start_time", "pr...
Times parsing if --verbose.
[ "Times", "parsing", "if", "--", "verbose", "." ]
python
train