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
django-auth-ldap/django-auth-ldap
django_auth_ldap/backend.py
https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L526-L543
def _search_for_user_dn(self): """ Searches the directory for a user matching AUTH_LDAP_USER_SEARCH. Populates self._user_dn and self._user_attrs. """ search = self.settings.USER_SEARCH if search is None: raise ImproperlyConfigured( "AUTH_LDAP_...
[ "def", "_search_for_user_dn", "(", "self", ")", ":", "search", "=", "self", ".", "settings", ".", "USER_SEARCH", "if", "search", "is", "None", ":", "raise", "ImproperlyConfigured", "(", "\"AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance.\"", ")", "results", "=", ...
Searches the directory for a user matching AUTH_LDAP_USER_SEARCH. Populates self._user_dn and self._user_attrs.
[ "Searches", "the", "directory", "for", "a", "user", "matching", "AUTH_LDAP_USER_SEARCH", ".", "Populates", "self", ".", "_user_dn", "and", "self", ".", "_user_attrs", "." ]
python
train
tensorpack/tensorpack
examples/DynamicFilterNetwork/steering-filter.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L24-L59
def DynamicConvFilter(inputs, filters, out_channel, kernel_shape, stride=1, padding='SAME'): """ see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the co...
[ "def", "DynamicConvFilter", "(", "inputs", ",", "filters", ",", "out_channel", ",", "kernel_shape", ",", "stride", "=", "1", ",", "padding", "=", "'SAME'", ")", ":", "# tf.unstack only works with known batch_size :-(", "batch_size", ",", "h", ",", "w", ",", "in_...
see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the convolution version of a dynamic filter. Args: inputs : unfiltered input [b, h, w, 1] only grayscale images. filters : learned filters of [b, k, k, ...
[ "see", "Dynamic", "Filter", "Networks", "(", "NIPS", "2016", ")", "by", "Bert", "De", "Brabandere", "*", "Xu", "Jia", "*", "Tinne", "Tuytelaars", "and", "Luc", "Van", "Gool" ]
python
train
readbeyond/aeneas
aeneas/globalfunctions.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L446-L469
def config_dict_to_string(dictionary): """ Convert a given config dictionary :: dictionary[key_1] = value_1 dictionary[key_2] = value_2 ... dictionary[key_n] = value_n into the corresponding string :: key_1=value_1|key_2=value_2|...|key_n=value_n :param dict d...
[ "def", "config_dict_to_string", "(", "dictionary", ")", ":", "parameters", "=", "[", "]", "for", "key", "in", "dictionary", ":", "parameters", ".", "append", "(", "u\"%s%s%s\"", "%", "(", "key", ",", "gc", ".", "CONFIG_STRING_ASSIGNMENT_SYMBOL", ",", "dictiona...
Convert a given config dictionary :: dictionary[key_1] = value_1 dictionary[key_2] = value_2 ... dictionary[key_n] = value_n into the corresponding string :: key_1=value_1|key_2=value_2|...|key_n=value_n :param dict dictionary: the config dictionary :rtype: string
[ "Convert", "a", "given", "config", "dictionary", "::" ]
python
train
languitar/pass-git-helper
passgithelper.py
https://github.com/languitar/pass-git-helper/blob/f84376d9ed6f7c47454a499da103da6fc2575a25/passgithelper.py#L206-L214
def get_value(self, entry_name: Text, entry_lines: Sequence[Text]) -> Optional[Text]: """See base class method.""" raw_value = self._get_raw(entry_name, entry_lines) if raw_value is not None: return raw_value[self._prefix_length:] else: ...
[ "def", "get_value", "(", "self", ",", "entry_name", ":", "Text", ",", "entry_lines", ":", "Sequence", "[", "Text", "]", ")", "->", "Optional", "[", "Text", "]", ":", "raw_value", "=", "self", ".", "_get_raw", "(", "entry_name", ",", "entry_lines", ")", ...
See base class method.
[ "See", "base", "class", "method", "." ]
python
train
kobejohn/PQHelper
pqhelper/versus.py
https://github.com/kobejohn/PQHelper/blob/d2b78a22dcb631794295e6a159b06f39c3f10db6/pqhelper/versus.py#L114-L130
def _summarize_result(self, root_action, leaf_eot): """Return a dict with useful information that summarizes this action.""" root_board = root_action.parent.board action_detail = root_action.position_pair score = self._relative_score(root_action, leaf_eot, ...
[ "def", "_summarize_result", "(", "self", ",", "root_action", ",", "leaf_eot", ")", ":", "root_board", "=", "root_action", ".", "parent", ".", "board", "action_detail", "=", "root_action", ".", "position_pair", "score", "=", "self", ".", "_relative_score", "(", ...
Return a dict with useful information that summarizes this action.
[ "Return", "a", "dict", "with", "useful", "information", "that", "summarizes", "this", "action", "." ]
python
train
saltstack/salt
salt/cloud/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L532-L543
def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(al...
[ "def", "get_configured_providers", "(", "self", ")", ":", "providers", "=", "set", "(", ")", "for", "alias", ",", "drivers", "in", "six", ".", "iteritems", "(", "self", ".", "opts", "[", "'providers'", "]", ")", ":", "if", "len", "(", "drivers", ")", ...
Return the configured providers
[ "Return", "the", "configured", "providers" ]
python
train
atlassian-api/atlassian-python-api
examples/confluence-trash-cleaner.py
https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/examples/confluence-trash-cleaner.py#L33-L51
def clean_all_trash_pages_from_all_spaces(confluence): """ Main function for retrieve space keys and provide space for cleaner :param confluence: :return: """ limit = 50 flag = True i = 0 while flag: space_lists = confluence.get_all_spaces(start=i * limit, limit=limit) ...
[ "def", "clean_all_trash_pages_from_all_spaces", "(", "confluence", ")", ":", "limit", "=", "50", "flag", "=", "True", "i", "=", "0", "while", "flag", ":", "space_lists", "=", "confluence", ".", "get_all_spaces", "(", "start", "=", "i", "*", "limit", ",", "...
Main function for retrieve space keys and provide space for cleaner :param confluence: :return:
[ "Main", "function", "for", "retrieve", "space", "keys", "and", "provide", "space", "for", "cleaner", ":", "param", "confluence", ":", ":", "return", ":" ]
python
train
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L152-L178
async def _reconnect(self): """ Called when the remote server is innacessible and the connection has to be restarted """ # 1. Close all transactions for msg_class in self._transactions: _1, _2, _3, coroutine_abrt, _4 = self._msgs_registered[msg_class] if ...
[ "async", "def", "_reconnect", "(", "self", ")", ":", "# 1. Close all transactions", "for", "msg_class", "in", "self", ".", "_transactions", ":", "_1", ",", "_2", ",", "_3", ",", "coroutine_abrt", ",", "_4", "=", "self", ".", "_msgs_registered", "[", "msg_cla...
Called when the remote server is innacessible and the connection has to be restarted
[ "Called", "when", "the", "remote", "server", "is", "innacessible", "and", "the", "connection", "has", "to", "be", "restarted" ]
python
train
python-gitlab/python-gitlab
gitlab/v4/objects.py
https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/v4/objects.py#L3776-L3791
def transfer_project(self, to_namespace, **kwargs): """Transfer a project to the given namespace ID Args: to_namespace (str): ID or path of the namespace to transfer the project to **kwargs: Extra options to send to the server (e.g. sudo) Raises: ...
[ "def", "transfer_project", "(", "self", ",", "to_namespace", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'/projects/%s/transfer'", "%", "(", "self", ".", "id", ",", ")", "self", ".", "manager", ".", "gitlab", ".", "http_put", "(", "path", ",", "po...
Transfer a project to the given namespace ID Args: to_namespace (str): ID or path of the namespace to transfer the project to **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct ...
[ "Transfer", "a", "project", "to", "the", "given", "namespace", "ID" ]
python
train
pennlabs/penn-sdk-python
penn/studyspaces.py
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L30-L48
def _obtain_token(self): """Obtain an auth token from client id and client secret.""" # don't renew token if hasn't expired yet if self.expiration and self.expiration > datetime.datetime.now(): return resp = requests.post("{}/1.1/oauth/token".format(API_URL), data={ ...
[ "def", "_obtain_token", "(", "self", ")", ":", "# don't renew token if hasn't expired yet", "if", "self", ".", "expiration", "and", "self", ".", "expiration", ">", "datetime", ".", "datetime", ".", "now", "(", ")", ":", "return", "resp", "=", "requests", ".", ...
Obtain an auth token from client id and client secret.
[ "Obtain", "an", "auth", "token", "from", "client", "id", "and", "client", "secret", "." ]
python
train
rwl/godot
godot/run.py
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/run.py#L25-L35
def main(): """ Runs Godot. """ application = GodotApplication( id="godot", plugins=[CorePlugin(), PuddlePlugin(), WorkbenchPlugin(), ResourcePlugin(), GodotPlugin()] ) application.run()
[ "def", "main", "(", ")", ":", "application", "=", "GodotApplication", "(", "id", "=", "\"godot\"", ",", "plugins", "=", "[", "CorePlugin", "(", ")", ",", "PuddlePlugin", "(", ")", ",", "WorkbenchPlugin", "(", ")", ",", "ResourcePlugin", "(", ")", ",", ...
Runs Godot.
[ "Runs", "Godot", "." ]
python
test
peri-source/peri
peri/conf.py
https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/conf.py#L55-L61
def read_environment(): """ Read all environment variables to see if they contain PERI """ out = {} for k,v in iteritems(os.environ): if transform(k) in default_conf: out[transform(k)] = v return out
[ "def", "read_environment", "(", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "iteritems", "(", "os", ".", "environ", ")", ":", "if", "transform", "(", "k", ")", "in", "default_conf", ":", "out", "[", "transform", "(", "k", ")", "]"...
Read all environment variables to see if they contain PERI
[ "Read", "all", "environment", "variables", "to", "see", "if", "they", "contain", "PERI" ]
python
valid
mcs07/ChemDataExtractor
chemdataextractor/cli/__init__.py
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L60-L66
def read(ctx, input, output): """Output processed document elements.""" log.info('chemdataextractor.read') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: output.write(u'%s : %s\n=====\n' % (element.__class__.__name__, six.text_type(element)))
[ "def", "read", "(", "ctx", ",", "input", ",", "output", ")", ":", "log", ".", "info", "(", "'chemdataextractor.read'", ")", "log", ".", "info", "(", "'Reading %s'", "%", "input", ".", "name", ")", "doc", "=", "Document", ".", "from_file", "(", "input",...
Output processed document elements.
[ "Output", "processed", "document", "elements", "." ]
python
train
PaulHancock/Aegean
AegeanTools/angle_tools.py
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/angle_tools.py#L38-L59
def dec2dec(dec): """ Convert sexegessimal RA string into a float in degrees. Parameters ---------- dec : string A string separated representing the Dec. Expected format is `[+- ]hh:mm[:ss.s]` Colons can be replaced with any whit space character. Returns ------- ...
[ "def", "dec2dec", "(", "dec", ")", ":", "d", "=", "dec", ".", "replace", "(", "':'", ",", "' '", ")", ".", "split", "(", ")", "if", "len", "(", "d", ")", "==", "2", ":", "d", ".", "append", "(", "0.0", ")", "if", "d", "[", "0", "]", ".", ...
Convert sexegessimal RA string into a float in degrees. Parameters ---------- dec : string A string separated representing the Dec. Expected format is `[+- ]hh:mm[:ss.s]` Colons can be replaced with any whit space character. Returns ------- dec : float The Dec i...
[ "Convert", "sexegessimal", "RA", "string", "into", "a", "float", "in", "degrees", "." ]
python
train
spencerahill/aospy
aospy/calc.py
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L297-L329
def _get_input_data(self, var, start_date, end_date): """Get the data for a single variable over the desired date range.""" logging.info(self._print_verbose("Getting input data:", var)) if isinstance(var, (float, int)): return var else: cond_pfull = ((not hasattr...
[ "def", "_get_input_data", "(", "self", ",", "var", ",", "start_date", ",", "end_date", ")", ":", "logging", ".", "info", "(", "self", ".", "_print_verbose", "(", "\"Getting input data:\"", ",", "var", ")", ")", "if", "isinstance", "(", "var", ",", "(", "...
Get the data for a single variable over the desired date range.
[ "Get", "the", "data", "for", "a", "single", "variable", "over", "the", "desired", "date", "range", "." ]
python
train
thespacedoctor/polyglot
polyglot/printpdf.py
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/printpdf.py#L169-L203
def _print_original_webpage( self): """*print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF """ self.log.debug('starting the ``_print_original_webpage`` method') if not self.title: r = requests.get(self.url)...
[ "def", "_print_original_webpage", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_print_original_webpage`` method'", ")", "if", "not", "self", ".", "title", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "url", ")", ...
*print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF
[ "*", "print", "the", "original", "webpage", "*" ]
python
train
raiden-network/raiden
raiden/waiting.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L70-L105
def wait_for_participant_newbalance( raiden: 'RaidenService', payment_network_id: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, target_address: Address, target_balance: TokenAmount, retry_timeout: float, ) -> None: """Wait until a gi...
[ "def", "wait_for_participant_newbalance", "(", "raiden", ":", "'RaidenService'", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "partner_address", ":", "Address", ",", "target_address", ":", "Address", ",", "target_ba...
Wait until a given channels balance exceeds the target balance. Note: This does not time out, use gevent.Timeout.
[ "Wait", "until", "a", "given", "channels", "balance", "exceeds", "the", "target", "balance", "." ]
python
train
launchdarkly/relayCommander
relay_commander/validator.py
https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/validator.py#L61-L74
def valid_env_vars() -> bool: """Validate that required env vars exist. :returns: True if required env vars exist. .. versionadded:: 0.0.12 """ for envvar in _REQUIRED_ENV_VARS: try: _check_env_var(envvar) except KeyError as ex: LOG.error(ex) sys...
[ "def", "valid_env_vars", "(", ")", "->", "bool", ":", "for", "envvar", "in", "_REQUIRED_ENV_VARS", ":", "try", ":", "_check_env_var", "(", "envvar", ")", "except", "KeyError", "as", "ex", ":", "LOG", ".", "error", "(", "ex", ")", "sys", ".", "exit", "(...
Validate that required env vars exist. :returns: True if required env vars exist. .. versionadded:: 0.0.12
[ "Validate", "that", "required", "env", "vars", "exist", "." ]
python
train
cackharot/suds-py3
suds/bindings/binding.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/bindings/binding.py#L206-L245
def replycomposite(self, rtypes, nodes): """ Construct a I{composite} reply. This method is called when it has been detected that the reply has multiple root nodes. @param rtypes: A list of known return I{types}. @type rtypes: [L{suds.xsd.sxbase.SchemaObject},...] @param...
[ "def", "replycomposite", "(", "self", ",", "rtypes", ",", "nodes", ")", ":", "dictionary", "=", "{", "}", "for", "rt", "in", "rtypes", ":", "dictionary", "[", "rt", ".", "name", "]", "=", "rt", "unmarshaller", "=", "self", ".", "unmarshaller", "(", "...
Construct a I{composite} reply. This method is called when it has been detected that the reply has multiple root nodes. @param rtypes: A list of known return I{types}. @type rtypes: [L{suds.xsd.sxbase.SchemaObject},...] @param nodes: A collection of XML nodes. @type nodes: [L{El...
[ "Construct", "a", "I", "{", "composite", "}", "reply", ".", "This", "method", "is", "called", "when", "it", "has", "been", "detected", "that", "the", "reply", "has", "multiple", "root", "nodes", "." ]
python
train
CyberZHG/keras-word-char-embd
keras_wc_embd/wrapper.py
https://github.com/CyberZHG/keras-word-char-embd/blob/cca6ddff01b6264dd0d12613bb9ed308e1367b8c/keras_wc_embd/wrapper.py#L30-L36
def update_dicts(self, sentence): """Add new sentence to generate dictionaries. :param sentence: A list of strings representing the sentence. """ self.dict_generator(sentence=sentence) self.word_dict, self.char_dict = None, None
[ "def", "update_dicts", "(", "self", ",", "sentence", ")", ":", "self", ".", "dict_generator", "(", "sentence", "=", "sentence", ")", "self", ".", "word_dict", ",", "self", ".", "char_dict", "=", "None", ",", "None" ]
Add new sentence to generate dictionaries. :param sentence: A list of strings representing the sentence.
[ "Add", "new", "sentence", "to", "generate", "dictionaries", "." ]
python
train
twidi/py-dataql
dataql/solvers/filters.py
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/filters.py#L153-L187
def solve(self, value, filter_): """Returns the value of an attribute of the value, or the result of a call to a function. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.Filter An instance of...
[ "def", "solve", "(", "self", ",", "value", ",", "filter_", ")", ":", "args", ",", "kwargs", "=", "filter_", ".", "get_args_and_kwargs", "(", ")", "source", "=", "self", ".", "registry", "[", "value", "]", "return", "source", ".", "solve", "(", "value",...
Returns the value of an attribute of the value, or the result of a call to a function. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.Filter An instance of ``Filter`` to solve with the given value. ...
[ "Returns", "the", "value", "of", "an", "attribute", "of", "the", "value", "or", "the", "result", "of", "a", "call", "to", "a", "function", "." ]
python
train
XuShaohua/bcloud
bcloud/DownloadPage.py
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/DownloadPage.py#L288-L318
def init_db(self): '''这个任务数据库只在程序开始时读入, 在程序关闭时导出. 因为Gtk没有像在Qt中那么方便的使用SQLite, 而必须将所有数据读入一个 liststore中才行. ''' cache_path = os.path.join(Config.CACHE_DIR, self.app.profile['username']) if not os.path.exists(cache_path): os.maked...
[ "def", "init_db", "(", "self", ")", ":", "cache_path", "=", "os", ".", "path", ".", "join", "(", "Config", ".", "CACHE_DIR", ",", "self", ".", "app", ".", "profile", "[", "'username'", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", ...
这个任务数据库只在程序开始时读入, 在程序关闭时导出. 因为Gtk没有像在Qt中那么方便的使用SQLite, 而必须将所有数据读入一个 liststore中才行.
[ "这个任务数据库只在程序开始时读入", "在程序关闭时导出", "." ]
python
train
sam-cox/pytides
pytides/tide.py
https://github.com/sam-cox/pytides/blob/63a2507299002f1979ea55a17a82561158d685f7/pytides/tide.py#L271-L406
def decompose( cls, heights, t = None, t0 = None, interval = None, constituents = constituent.noaa, initial = None, n_period = 2, callback = None, full_output = False ): """ Return an instance of Tide which has been fitted to a series of tidal o...
[ "def", "decompose", "(", "cls", ",", "heights", ",", "t", "=", "None", ",", "t0", "=", "None", ",", "interval", "=", "None", ",", "constituents", "=", "constituent", ".", "noaa", ",", "initial", "=", "None", ",", "n_period", "=", "2", ",", "callback"...
Return an instance of Tide which has been fitted to a series of tidal observations. Arguments: It is not necessary to provide t0 or interval if t is provided. heights -- ndarray of tidal observation heights t -- ndarray of tidal observation times t0 -- datetime representing the time at which heights[0] was re...
[ "Return", "an", "instance", "of", "Tide", "which", "has", "been", "fitted", "to", "a", "series", "of", "tidal", "observations", ".", "Arguments", ":", "It", "is", "not", "necessary", "to", "provide", "t0", "or", "interval", "if", "t", "is", "provided", "...
python
train
diffeo/rejester
rejester/workers.py
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L934-L948
def stop_gracefully(self): '''Refuse to start more processes. This runs in response to SIGINT or SIGTERM; if this isn't a background process, control-C and a normal ``kill`` command cause this. ''' if self.shutting_down: self.log(logging.INFO, ...
[ "def", "stop_gracefully", "(", "self", ")", ":", "if", "self", ".", "shutting_down", ":", "self", ".", "log", "(", "logging", ".", "INFO", ",", "'second shutdown request, shutting down now'", ")", "self", ".", "scram", "(", ")", "else", ":", "self", ".", "...
Refuse to start more processes. This runs in response to SIGINT or SIGTERM; if this isn't a background process, control-C and a normal ``kill`` command cause this.
[ "Refuse", "to", "start", "more", "processes", "." ]
python
train
ashmastaflash/kal-wrapper
kalibrate/fn.py
https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L28-L35
def build_kal_scan_channel_string(kal_bin, channel, args): """Return string for CLI invocation of kal, for channel scan.""" option_mapping = {"gain": "-g", "device": "-d", "error": "-e"} base_string = "%s -v -c %s" % (kal_bin, channel) base_string += options_s...
[ "def", "build_kal_scan_channel_string", "(", "kal_bin", ",", "channel", ",", "args", ")", ":", "option_mapping", "=", "{", "\"gain\"", ":", "\"-g\"", ",", "\"device\"", ":", "\"-d\"", ",", "\"error\"", ":", "\"-e\"", "}", "base_string", "=", "\"%s -v -c %s\"", ...
Return string for CLI invocation of kal, for channel scan.
[ "Return", "string", "for", "CLI", "invocation", "of", "kal", "for", "channel", "scan", "." ]
python
train
Julius2342/pyvlx
pyvlx/frames/frame_command_send.py
https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/pyvlx/frames/frame_command_send.py#L52-L65
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.originator = Originator(payload[2]) self.priority = Priority(payload[3]) len_node_ids = payload[41] if len_node_ids > 20: raise PyVLXExcepti...
[ "def", "from_payload", "(", "self", ",", "payload", ")", ":", "self", ".", "session_id", "=", "payload", "[", "0", "]", "*", "256", "+", "payload", "[", "1", "]", "self", ".", "originator", "=", "Originator", "(", "payload", "[", "2", "]", ")", "se...
Init frame from binary data.
[ "Init", "frame", "from", "binary", "data", "." ]
python
train
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/github.py
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/github.py#L110-L113
def _extract_email(gh): """Get user email from github.""" return next( (x.email for x in gh.emails() if x.verified and x.primary), None)
[ "def", "_extract_email", "(", "gh", ")", ":", "return", "next", "(", "(", "x", ".", "email", "for", "x", "in", "gh", ".", "emails", "(", ")", "if", "x", ".", "verified", "and", "x", ".", "primary", ")", ",", "None", ")" ]
Get user email from github.
[ "Get", "user", "email", "from", "github", "." ]
python
train
numba/llvmlite
llvmlite/binding/module.py
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L184-L190
def functions(self): """ Return an iterator over this module's functions. The iterator will yield a ValueRef for each function. """ it = ffi.lib.LLVMPY_ModuleFunctionsIter(self) return _FunctionsIterator(it, dict(module=self))
[ "def", "functions", "(", "self", ")", ":", "it", "=", "ffi", ".", "lib", ".", "LLVMPY_ModuleFunctionsIter", "(", "self", ")", "return", "_FunctionsIterator", "(", "it", ",", "dict", "(", "module", "=", "self", ")", ")" ]
Return an iterator over this module's functions. The iterator will yield a ValueRef for each function.
[ "Return", "an", "iterator", "over", "this", "module", "s", "functions", ".", "The", "iterator", "will", "yield", "a", "ValueRef", "for", "each", "function", "." ]
python
train
asifpy/django-crudbuilder
crudbuilder/helpers.py
https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/helpers.py#L19-L80
def plural(text): """ >>> plural('activity') 'activities' """ aberrant = { 'knife': 'knives', 'self': 'selves', 'elf': 'elves', 'life': 'lives', 'hoof': 'hooves', 'leaf': 'leaves', 'echo': 'echoes', 'embargo': 'embargoes', ...
[ "def", "plural", "(", "text", ")", ":", "aberrant", "=", "{", "'knife'", ":", "'knives'", ",", "'self'", ":", "'selves'", ",", "'elf'", ":", "'elves'", ",", "'life'", ":", "'lives'", ",", "'hoof'", ":", "'hooves'", ",", "'leaf'", ":", "'leaves'", ",", ...
>>> plural('activity') 'activities'
[ ">>>", "plural", "(", "activity", ")", "activities" ]
python
train
biolink/ontobio
bin/qbiogolr.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/bin/qbiogolr.py#L26-L155
def main(): """ Wrapper for OGR """ parser = argparse.ArgumentParser( description='Command line interface to python-ontobio.golr library' """ Provides command line interface onto the ontobio.golr python library, a high level abstraction layer over Monarch and GO solr in...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Command line interface to python-ontobio.golr library'", "\"\"\"\n\n Provides command line interface onto the ontobio.golr python library, a high level\n abstraction l...
Wrapper for OGR
[ "Wrapper", "for", "OGR" ]
python
train
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/api/core_v1_api.py
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L2363-L2385
def connect_options_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501 """connect_options_namespaced_pod_proxy # noqa: E501 connect OPTIONS requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP req...
[ "def", "connect_options_namespaced_pod_proxy", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":",...
connect_options_namespaced_pod_proxy # noqa: E501 connect OPTIONS requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_options_namespaced_pod_proxy(name,...
[ "connect_options_namespaced_pod_proxy", "#", "noqa", ":", "E501" ]
python
train
pypa/pipenv
pipenv/vendor/cerberus/schema.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L116-L133
def _expand_logical_shortcuts(cls, schema): """ Expand agglutinated rules in a definition-schema. :param schema: The schema-definition to expand. :return: The expanded schema-definition. """ def is_of_rule(x): return isinstance(x, _str_type) and \ x.s...
[ "def", "_expand_logical_shortcuts", "(", "cls", ",", "schema", ")", ":", "def", "is_of_rule", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "_str_type", ")", "and", "x", ".", "startswith", "(", "(", "'allof_'", ",", "'anyof_'", ",", "'noneof...
Expand agglutinated rules in a definition-schema. :param schema: The schema-definition to expand. :return: The expanded schema-definition.
[ "Expand", "agglutinated", "rules", "in", "a", "definition", "-", "schema", "." ]
python
train
dossier/dossier.store
dossier/store/store.py
https://github.com/dossier/dossier.store/blob/b22ffe2470bba9fcc98a30cb55b437bfa1521e7f/dossier/store/store.py#L490-L501
def _index(self, name): '''Returns index transforms for ``name``. :type name: unicode :rtype: ``{ create |--> function, transform |--> function }`` ''' name = name.decode('utf-8') try: return self._indexes[name] except KeyError: raise KeyE...
[ "def", "_index", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "decode", "(", "'utf-8'", ")", "try", ":", "return", "self", ".", "_indexes", "[", "name", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "'Index \"%s\" has not bee...
Returns index transforms for ``name``. :type name: unicode :rtype: ``{ create |--> function, transform |--> function }``
[ "Returns", "index", "transforms", "for", "name", "." ]
python
test
zyga/python-glibc
pyglibc/selectors.py
https://github.com/zyga/python-glibc/blob/d6fdb306b123a995471584a5201155c60a34448a/pyglibc/selectors.py#L229-L238
def get_epoll_events(self): """ Create a bit mask using ``EPOLL*`` family of constants. """ epoll_events = 0 if self & EVENT_READ: epoll_events |= select.EPOLLIN if self & EVENT_WRITE: epoll_events |= select.EPOLLOUT return epoll_events
[ "def", "get_epoll_events", "(", "self", ")", ":", "epoll_events", "=", "0", "if", "self", "&", "EVENT_READ", ":", "epoll_events", "|=", "select", ".", "EPOLLIN", "if", "self", "&", "EVENT_WRITE", ":", "epoll_events", "|=", "select", ".", "EPOLLOUT", "return"...
Create a bit mask using ``EPOLL*`` family of constants.
[ "Create", "a", "bit", "mask", "using", "EPOLL", "*", "family", "of", "constants", "." ]
python
train
bionikspoon/pureyaml
pureyaml/grammar/productions.py
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/grammar/productions.py#L275-L287
def p_scalar_group(self, p): """ scalar_group : SCALAR | scalar_group SCALAR """ if len(p) == 2: p[0] = (str(p[1]),) if len(p) == 3: p[0] = p[1] + (str(p[2]),) if len(p) == 4: p[0] = p[1] + (str(p[3]),)
[ "def", "p_scalar_group", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "(", "str", "(", "p", "[", "1", "]", ")", ",", ")", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "...
scalar_group : SCALAR | scalar_group SCALAR
[ "scalar_group", ":", "SCALAR", "|", "scalar_group", "SCALAR" ]
python
train
postlund/pyatv
pyatv/__main__.py
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L242-L319
async def cli_handler(loop): """Application starts here.""" parser = argparse.ArgumentParser() parser.add_argument('command', nargs='+', help='commands, help, ...') parser.add_argument('--name', help='apple tv name', dest='name', default='Apple TV') p...
[ "async", "def", "cli_handler", "(", "loop", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'command'", ",", "nargs", "=", "'+'", ",", "help", "=", "'commands, help, ...'", ")", "parser", ".", "add...
Application starts here.
[ "Application", "starts", "here", "." ]
python
train
PmagPy/PmagPy
programs/magic_gui.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/magic_gui.py#L446-L460
def highlight_button(self, event): """ Draw a red highlight line around the event object """ wind = event.GetEventObject() pos = wind.GetPosition() size = wind.GetSize() try: dc = wx.PaintDC(self) except wx._core.PyAssertionError: #...
[ "def", "highlight_button", "(", "self", ",", "event", ")", ":", "wind", "=", "event", ".", "GetEventObject", "(", ")", "pos", "=", "wind", ".", "GetPosition", "(", ")", "size", "=", "wind", ".", "GetSize", "(", ")", "try", ":", "dc", "=", "wx", "."...
Draw a red highlight line around the event object
[ "Draw", "a", "red", "highlight", "line", "around", "the", "event", "object" ]
python
train
oscarbranson/latools
latools/latools.py
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/latools.py#L3506-L3594
def sample_stats(self, analytes=None, filt=True, stats=['mean', 'std'], eachtrace=True, csf_dict={}): """ Calculate sample statistics. Returns samples, analytes, and arrays of statistics of shape (samples, analytes). Statistics are calculated ...
[ "def", "sample_stats", "(", "self", ",", "analytes", "=", "None", ",", "filt", "=", "True", ",", "stats", "=", "[", "'mean'", ",", "'std'", "]", ",", "eachtrace", "=", "True", ",", "csf_dict", "=", "{", "}", ")", ":", "if", "analytes", "is", "None"...
Calculate sample statistics. Returns samples, analytes, and arrays of statistics of shape (samples, analytes). Statistics are calculated from the 'focus' data variable, so output depends on how the data have been processed. Included stat functions: * :func:`~latools.st...
[ "Calculate", "sample", "statistics", "." ]
python
test
ouroboroscoding/format-oc-python
FormatOC/__init__.py
https://github.com/ouroboroscoding/format-oc-python/blob/c160b46fe4ff2c92333c776991c712de23991225/FormatOC/__init__.py#L1200-L1378
def minmax(self, minimum=None, maximum=None): """Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, ValueError Returns...
[ "def", "minmax", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ")", ":", "# If neither min or max is set, this is a getter", "if", "minimum", "is", "None", "and", "maximum", "is", "None", ":", "return", "{", "\"minimum\"", ":", "self",...
Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, ValueError Returns: None | dict
[ "Min", "/", "Max" ]
python
train
rflamary/POT
ot/bregman.py
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L796-L965
def sinkhorn_epsilon_scaling(a, b, M, reg, numItermax=100, epsilon0=1e4, numInnerItermax=100, tau=1e3, stopThr=1e-9, warmstart=None, verbose=False, print_period=10, log=False, **kwargs): """ Solve the entropic regularization optimal transport problem with log stabilization and e...
[ "def", "sinkhorn_epsilon_scaling", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "numItermax", "=", "100", ",", "epsilon0", "=", "1e4", ",", "numInnerItermax", "=", "100", ",", "tau", "=", "1e3", ",", "stopThr", "=", "1e-9", ",", "warmstart", "=", "...
Solve the entropic regularization optimal transport problem with log stabilization and epsilon scaling. The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b ...
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "with", "log", "stabilization", "and", "epsilon", "scaling", "." ]
python
train
fuzeman/PyUPnP
pyupnp/util.py
https://github.com/fuzeman/PyUPnP/blob/6dea64be299952346a14300ab6cc7dac42736433/pyupnp/util.py#L24-L32
def twisted_absolute_path(path, request): """Hack to fix twisted not accepting absolute URIs""" parsed = urlparse.urlparse(request.uri) if parsed.scheme != '': path_parts = parsed.path.lstrip('/').split('/') request.prepath = path_parts[0:1] request.postpath = path_parts[1:] ...
[ "def", "twisted_absolute_path", "(", "path", ",", "request", ")", ":", "parsed", "=", "urlparse", ".", "urlparse", "(", "request", ".", "uri", ")", "if", "parsed", ".", "scheme", "!=", "''", ":", "path_parts", "=", "parsed", ".", "path", ".", "lstrip", ...
Hack to fix twisted not accepting absolute URIs
[ "Hack", "to", "fix", "twisted", "not", "accepting", "absolute", "URIs" ]
python
train
michael-lazar/rtv
rtv/packages/praw/objects.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L1281-L1292
def lock(self): """Lock thread. Requires that the currently authenticated user has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server. """ url = self.reddit_session.config['lock'] ...
[ "def", "lock", "(", "self", ")", ":", "url", "=", "self", ".", "reddit_session", ".", "config", "[", "'lock'", "]", "data", "=", "{", "'id'", ":", "self", ".", "fullname", "}", "return", "self", ".", "reddit_session", ".", "request_json", "(", "url", ...
Lock thread. Requires that the currently authenticated user has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server.
[ "Lock", "thread", "." ]
python
train
PlaidWeb/Publ
publ/index.py
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L169-L173
def on_modified(self, event): """ on_modified handler """ logger.debug("file modified: %s", event.src_path) if not event.is_directory: self.update_file(event.src_path)
[ "def", "on_modified", "(", "self", ",", "event", ")", ":", "logger", ".", "debug", "(", "\"file modified: %s\"", ",", "event", ".", "src_path", ")", "if", "not", "event", ".", "is_directory", ":", "self", ".", "update_file", "(", "event", ".", "src_path", ...
on_modified handler
[ "on_modified", "handler" ]
python
train
quantumlib/Cirq
cirq/circuits/text_diagram_drawer.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/text_diagram_drawer.py#L134-L142
def horizontal_line(self, y: Union[int, float], x1: Union[int, float], x2: Union[int, float], emphasize: bool = False ) -> None: """Adds a line from (x1, y) to (x2, y).""" x1, x2 = sor...
[ "def", "horizontal_line", "(", "self", ",", "y", ":", "Union", "[", "int", ",", "float", "]", ",", "x1", ":", "Union", "[", "int", ",", "float", "]", ",", "x2", ":", "Union", "[", "int", ",", "float", "]", ",", "emphasize", ":", "bool", "=", "F...
Adds a line from (x1, y) to (x2, y).
[ "Adds", "a", "line", "from", "(", "x1", "y", ")", "to", "(", "x2", "y", ")", "." ]
python
train
cltk/cltk
cltk/tokenize/word.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/word.py#L433-L445
def tokenize_middle_high_german_words(text): """Tokenizes MHG text""" assert isinstance(text, str) # As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks text = re.sub(r'-\n',r'-', text) text = re.sub(r'\n', r' ', text) text = re.sub(r'(?<=...
[ "def", "tokenize_middle_high_german_words", "(", "text", ")", ":", "assert", "isinstance", "(", "text", ",", "str", ")", "# As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks", "text", "=", "re", ".", "sub", "(", "r'-\\...
Tokenizes MHG text
[ "Tokenizes", "MHG", "text" ]
python
train
Becksteinlab/GromacsWrapper
gromacs/config.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/config.py#L356-L361
def resource_basename(resource): """Last component of a resource (which always uses '/' as sep).""" if resource.endswith('/'): resource = resource[:-1] parts = resource.split('/') return parts[-1]
[ "def", "resource_basename", "(", "resource", ")", ":", "if", "resource", ".", "endswith", "(", "'/'", ")", ":", "resource", "=", "resource", "[", ":", "-", "1", "]", "parts", "=", "resource", ".", "split", "(", "'/'", ")", "return", "parts", "[", "-"...
Last component of a resource (which always uses '/' as sep).
[ "Last", "component", "of", "a", "resource", "(", "which", "always", "uses", "/", "as", "sep", ")", "." ]
python
valid
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4808-L4846
def _gettags(self, codes=None, lock=None): """Return list of (code, TiffTag) from file.""" fh = self.parent.filehandle tiff = self.parent.tiff unpack = struct.unpack lock = NullContext() if lock is None else lock tags = [] with lock: fh.seek(self.offs...
[ "def", "_gettags", "(", "self", ",", "codes", "=", "None", ",", "lock", "=", "None", ")", ":", "fh", "=", "self", ".", "parent", ".", "filehandle", "tiff", "=", "self", ".", "parent", ".", "tiff", "unpack", "=", "struct", ".", "unpack", "lock", "="...
Return list of (code, TiffTag) from file.
[ "Return", "list", "of", "(", "code", "TiffTag", ")", "from", "file", "." ]
python
train
rndusr/torf
torf/_torrent.py
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L555-L559
def infohash_base32(self): """Base32 encoded SHA1 info hash""" self.validate() info = self.convert()[b'info'] return b32encode(sha1(bencode(info)).digest())
[ "def", "infohash_base32", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "info", "=", "self", ".", "convert", "(", ")", "[", "b'info'", "]", "return", "b32encode", "(", "sha1", "(", "bencode", "(", "info", ")", ")", ".", "digest", "(", "...
Base32 encoded SHA1 info hash
[ "Base32", "encoded", "SHA1", "info", "hash" ]
python
train
Infinidat/infi.clickhouse_orm
src/infi/clickhouse_orm/database.py
https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L154-L161
def does_table_exist(self, model_class): ''' Checks whether a table for the given model class already exists. Note that this only checks for existence of a table with the expected name. ''' sql = "SELECT count() FROM system.tables WHERE database = '%s' AND name = '%s'" r ...
[ "def", "does_table_exist", "(", "self", ",", "model_class", ")", ":", "sql", "=", "\"SELECT count() FROM system.tables WHERE database = '%s' AND name = '%s'\"", "r", "=", "self", ".", "_send", "(", "sql", "%", "(", "self", ".", "db_name", ",", "model_class", ".", ...
Checks whether a table for the given model class already exists. Note that this only checks for existence of a table with the expected name.
[ "Checks", "whether", "a", "table", "for", "the", "given", "model", "class", "already", "exists", ".", "Note", "that", "this", "only", "checks", "for", "existence", "of", "a", "table", "with", "the", "expected", "name", "." ]
python
train
SUSE-Enceladus/ipa
ipa/ipa_distro.py
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L150-L168
def update(self, client): """Execute update command on instance.""" update_cmd = "{sudo} '{refresh};{update}'".format( sudo=self.get_sudo_exec_wrapper(), refresh=self.get_refresh_repo_cmd(), update=self.get_update_cmd() ) out = '' try: ...
[ "def", "update", "(", "self", ",", "client", ")", ":", "update_cmd", "=", "\"{sudo} '{refresh};{update}'\"", ".", "format", "(", "sudo", "=", "self", ".", "get_sudo_exec_wrapper", "(", ")", ",", "refresh", "=", "self", ".", "get_refresh_repo_cmd", "(", ")", ...
Execute update command on instance.
[ "Execute", "update", "command", "on", "instance", "." ]
python
train
jrspruitt/ubi_reader
ubireader/ubi/block/layout.py
https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/layout.py#L74-L91
def associate_blocks(blocks, layout_pairs, start_peb_num): """Group block indexes with appropriate layout pairs Arguments: List:blocks -- List of block objects List:layout_pairs -- List of grouped layout blocks Int:start_peb_num -- Number of the PEB to start from. Returns: List --...
[ "def", "associate_blocks", "(", "blocks", ",", "layout_pairs", ",", "start_peb_num", ")", ":", "seq_blocks", "=", "[", "]", "for", "layout_pair", "in", "layout_pairs", ":", "seq_blocks", "=", "sort", ".", "by_image_seq", "(", "blocks", ",", "blocks", "[", "l...
Group block indexes with appropriate layout pairs Arguments: List:blocks -- List of block objects List:layout_pairs -- List of grouped layout blocks Int:start_peb_num -- Number of the PEB to start from. Returns: List -- Layout block pairs grouped with associated block ranges.
[ "Group", "block", "indexes", "with", "appropriate", "layout", "pairs" ]
python
train
rocky/python3-trepan
trepan/post_mortem.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/post_mortem.py#L80-L168
def post_mortem(exc=None, frameno=1, dbg=None): """Enter debugger read loop after your program has crashed. exc is a triple like you get back from sys.exc_info. If no exc parameter, is supplied, the values from sys.last_type, sys.last_value, sys.last_traceback are used. And if these don't exist ei...
[ "def", "post_mortem", "(", "exc", "=", "None", ",", "frameno", "=", "1", ",", "dbg", "=", "None", ")", ":", "if", "dbg", "is", "None", ":", "# Check for a global debugger object", "if", "Mdebugger", ".", "debugger_obj", "is", "None", ":", "Mdebugger", ".",...
Enter debugger read loop after your program has crashed. exc is a triple like you get back from sys.exc_info. If no exc parameter, is supplied, the values from sys.last_type, sys.last_value, sys.last_traceback are used. And if these don't exist either we'll assume that sys.exc_info() contains what we ...
[ "Enter", "debugger", "read", "loop", "after", "your", "program", "has", "crashed", "." ]
python
test
dmaust/rounding
rounding/stochastic.py
https://github.com/dmaust/rounding/blob/06731dff803c30c0741e3199888e7e5266ad99cc/rounding/stochastic.py#L58-L66
def sround(x, precision=0): """ Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round. """ sr = StochasticRound(precision=precision) return sr.round(x)
[ "def", "sround", "(", "x", ",", "precision", "=", "0", ")", ":", "sr", "=", "StochasticRound", "(", "precision", "=", "precision", ")", "return", "sr", ".", "round", "(", "x", ")" ]
Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round.
[ "Round", "a", "single", "number", "using", "default", "non", "-", "deterministic", "generator", "." ]
python
train
exosite-labs/pyonep
pyonep/onep.py
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L501-L512
def wait(self, auth, resource, options, defer=False): """ This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options...
[ "def", "wait", "(", "self", ",", "auth", ",", "resource", ",", "options", ",", "defer", "=", "False", ")", ":", "# let the server control the timeout", "return", "self", ".", "_call", "(", "'wait'", ",", "auth", ",", "[", "resource", ",", "options", "]", ...
This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options: Options for the wait including a timeout (in ms), (max 5min) and...
[ "This", "is", "a", "HTTP", "Long", "Polling", "API", "which", "allows", "a", "user", "to", "wait", "on", "specific", "resources", "to", "be", "updated", "." ]
python
train
commontk/ctk-cli
ctk_cli/module.py
https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L259-L265
def parseValue(self, value): """Parse the given value and return result.""" if self.isVector(): return list(map(self._pythonType, value.split(','))) if self.typ == 'boolean': return _parseBool(value) return self._pythonType(value)
[ "def", "parseValue", "(", "self", ",", "value", ")", ":", "if", "self", ".", "isVector", "(", ")", ":", "return", "list", "(", "map", "(", "self", ".", "_pythonType", ",", "value", ".", "split", "(", "','", ")", ")", ")", "if", "self", ".", "typ"...
Parse the given value and return result.
[ "Parse", "the", "given", "value", "and", "return", "result", "." ]
python
train
dddomodossola/remi
remi/gui.py
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L955-L967
def repr(self, changed_widgets=None): """It is used to automatically represent the object to HTML format packs all the attributes, children and so on. Args: changed_widgets (dict): A dictionary containing a collection of tags that have to be updated. The tag that hav...
[ "def", "repr", "(", "self", ",", "changed_widgets", "=", "None", ")", ":", "if", "changed_widgets", "is", "None", ":", "changed_widgets", "=", "{", "}", "local_changed_widgets", "=", "{", "}", "self", ".", "_set_updated", "(", ")", "return", "''", ".", "...
It is used to automatically represent the object to HTML format packs all the attributes, children and so on. Args: changed_widgets (dict): A dictionary containing a collection of tags that have to be updated. The tag that have to be updated is the key, and the value is its ...
[ "It", "is", "used", "to", "automatically", "represent", "the", "object", "to", "HTML", "format", "packs", "all", "the", "attributes", "children", "and", "so", "on", "." ]
python
train
hover2pi/svo_filters
svo_filters/svo.py
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L393-L415
def flux_units(self, units): """ A setter for the flux units Parameters ---------- units: str, astropy.units.core.PrefixUnit The desired units of the zeropoint flux density """ # Check that the units are valid dtypes = (q.core.PrefixUnit, q.qu...
[ "def", "flux_units", "(", "self", ",", "units", ")", ":", "# Check that the units are valid", "dtypes", "=", "(", "q", ".", "core", ".", "PrefixUnit", ",", "q", ".", "quantity", ".", "Quantity", ",", "q", ".", "core", ".", "CompositeUnit", ")", "if", "no...
A setter for the flux units Parameters ---------- units: str, astropy.units.core.PrefixUnit The desired units of the zeropoint flux density
[ "A", "setter", "for", "the", "flux", "units" ]
python
train
apache/incubator-heron
heron/tools/tracker/src/python/handlers/topologieshandler.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/topologieshandler.py#L60-L108
def get(self): """ get method """ # Get all the values for parameter "cluster". clusters = self.get_arguments(constants.PARAM_CLUSTER) # Get all the values for parameter "environ". environs = self.get_arguments(constants.PARAM_ENVIRON) # Get role role = self.get_argument_role() ret = {}...
[ "def", "get", "(", "self", ")", ":", "# Get all the values for parameter \"cluster\".", "clusters", "=", "self", ".", "get_arguments", "(", "constants", ".", "PARAM_CLUSTER", ")", "# Get all the values for parameter \"environ\".", "environs", "=", "self", ".", "get_argume...
get method
[ "get", "method" ]
python
valid
jmfederico/django-use-email-as-username
django_use_email_as_username/management/commands/create_custom_user_app.py
https://github.com/jmfederico/django-use-email-as-username/blob/401e404b822f7ba5b3ef34b06ce095e564f32912/django_use_email_as_username/management/commands/create_custom_user_app.py#L26-L30
def handle(self, **options): """Call "startapp" to generate app with custom user model.""" template = os.path.dirname(os.path.abspath(__file__)) + "/app_template" name = options.pop("name") call_command("startapp", name, template=template, **options)
[ "def", "handle", "(", "self", ",", "*", "*", "options", ")", ":", "template", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "+", "\"/app_template\"", "name", "=", "options", ".", "pop", "...
Call "startapp" to generate app with custom user model.
[ "Call", "startapp", "to", "generate", "app", "with", "custom", "user", "model", "." ]
python
train
matousc89/padasip
padasip/filters/ap.py
https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/filters/ap.py#L229-L285
def run(self, d, x): """ This function filters multiple samples in a row. **Args:** * `d` : desired value (1 dimensional array) * `x` : input matrix (2-dimensional array). Rows are samples, columns are input arrays. **Returns:** * `y` : output value...
[ "def", "run", "(", "self", ",", "d", ",", "x", ")", ":", "# measure the data and check if the dimmension agree", "N", "=", "len", "(", "x", ")", "if", "not", "len", "(", "d", ")", "==", "N", ":", "raise", "ValueError", "(", "'The length of vector d and matri...
This function filters multiple samples in a row. **Args:** * `d` : desired value (1 dimensional array) * `x` : input matrix (2-dimensional array). Rows are samples, columns are input arrays. **Returns:** * `y` : output value (1 dimensional array). The siz...
[ "This", "function", "filters", "multiple", "samples", "in", "a", "row", "." ]
python
train
GearPlug/payu-python
payu/recurring.py
https://github.com/GearPlug/payu-python/blob/47ec5c9fc89f1f89a53ec0a68c84f358bbe3394e/payu/recurring.py#L240-L303
def create_subscription(self, *, customer_id, credit_card_token, plan_code, quantity=None, installments=None, trial_days=None, immediate_payment=None, extra1=None, extra2=None, delivery_address=None, notify_url=None, recurring_bill_items=None): """ ...
[ "def", "create_subscription", "(", "self", ",", "*", ",", "customer_id", ",", "credit_card_token", ",", "plan_code", ",", "quantity", "=", "None", ",", "installments", "=", "None", ",", "trial_days", "=", "None", ",", "immediate_payment", "=", "None", ",", "...
Creating a new subscription of a client to a plan. Args: customer_id: Customer that will be associated to the subscription. You can find more information in the "Customer" section of this page. credit_card_token: Customer's credit card that is selected to make the payment. ...
[ "Creating", "a", "new", "subscription", "of", "a", "client", "to", "a", "plan", "." ]
python
train
jwodder/txtble
txtble/util.py
https://github.com/jwodder/txtble/blob/31d39ed6c15df13599c704a757cd36e1cd57cdd1/txtble/util.py#L94-L111
def with_color_stripped(f): """ A function decorator for applying to `len` or imitators thereof that strips ANSI color sequences from a string before passing it on. If any color sequences are not followed by a reset sequence, an `UnterminatedColorError` is raised. """ @wraps(f) def colo...
[ "def", "with_color_stripped", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "colored_len", "(", "s", ")", ":", "s2", "=", "re", ".", "sub", "(", "COLOR_BEGIN_RGX", "+", "'(.*?)'", "+", "COLOR_END_RGX", ",", "lambda", "m", ":", "re", ".", ...
A function decorator for applying to `len` or imitators thereof that strips ANSI color sequences from a string before passing it on. If any color sequences are not followed by a reset sequence, an `UnterminatedColorError` is raised.
[ "A", "function", "decorator", "for", "applying", "to", "len", "or", "imitators", "thereof", "that", "strips", "ANSI", "color", "sequences", "from", "a", "string", "before", "passing", "it", "on", ".", "If", "any", "color", "sequences", "are", "not", "followe...
python
train
spacetelescope/acstools
acstools/acszpt.py
https://github.com/spacetelescope/acstools/blob/bbf8dd080cefcbf88529ec87c420f9e1b8002554/acstools/acszpt.py#L206-L248
def _check_inputs(self): """Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not. """ valid_detector = True valid_filter = True valid_date = True # Determine the su...
[ "def", "_check_inputs", "(", "self", ")", ":", "valid_detector", "=", "True", "valid_filter", "=", "True", "valid_date", "=", "True", "# Determine the submitted detector is valid", "if", "self", ".", "detector", "not", "in", "self", ".", "_valid_detectors", ":", "...
Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not.
[ "Check", "the", "inputs", "to", "ensure", "they", "are", "valid", "." ]
python
train
productml/blurr
blurr/runner/spark_runner.py
https://github.com/productml/blurr/blob/1b688b2c4a9bbbb2139c58bf0682ddc05a6c24fa/blurr/runner/spark_runner.py#L95-L115
def get_record_rdd_from_json_files(self, json_files: List[str], data_processor: DataProcessor = SimpleJsonDataProcessor(), spark_session: Optional['SparkSession'] = None) -> 'RDD': """ Re...
[ "def", "get_record_rdd_from_json_files", "(", "self", ",", "json_files", ":", "List", "[", "str", "]", ",", "data_processor", ":", "DataProcessor", "=", "SimpleJsonDataProcessor", "(", ")", ",", "spark_session", ":", "Optional", "[", "'SparkSession'", "]", "=", ...
Reads the data from the given json_files path and converts them into the `Record`s format for processing. `data_processor` is used to process the per event data in those files to convert them into `Record`. :param json_files: List of json file paths. Regular Spark path wildcards are accepted. ...
[ "Reads", "the", "data", "from", "the", "given", "json_files", "path", "and", "converts", "them", "into", "the", "Record", "s", "format", "for", "processing", ".", "data_processor", "is", "used", "to", "process", "the", "per", "event", "data", "in", "those", ...
python
train
frictionlessdata/datapackage-pipelines
datapackage_pipelines/web/server.py
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/web/server.py#L292-L326
def badge_collection(pipeline_path): '''Status badge for a collection of pipelines.''' all_pipeline_ids = sorted(status.all_pipeline_ids()) if not pipeline_path.startswith('./'): pipeline_path = './' + pipeline_path # Filter pipeline ids to only include those that start with pipeline_path. ...
[ "def", "badge_collection", "(", "pipeline_path", ")", ":", "all_pipeline_ids", "=", "sorted", "(", "status", ".", "all_pipeline_ids", "(", ")", ")", "if", "not", "pipeline_path", ".", "startswith", "(", "'./'", ")", ":", "pipeline_path", "=", "'./'", "+", "p...
Status badge for a collection of pipelines.
[ "Status", "badge", "for", "a", "collection", "of", "pipelines", "." ]
python
train
mwarkentin/django-watchman
watchman/decorators.py
https://github.com/mwarkentin/django-watchman/blob/6ef98ba54dc52f27e7b42d42028b59dc67550268/watchman/decorators.py#L57-L111
def token_required(view_func): """ Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set. WATCHMAN_TOKEN_NAME can also be set if the token GET parameter must be customized. """ def _parse_auth_header(auth_header): """ Parse the `Authorization` header ...
[ "def", "token_required", "(", "view_func", ")", ":", "def", "_parse_auth_header", "(", "auth_header", ")", ":", "\"\"\"\n Parse the `Authorization` header\n\n Expected format: `WATCHMAN-TOKEN Token=\"ABC123\"`\n \"\"\"", "# TODO: Figure out full set of allowed characte...
Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set. WATCHMAN_TOKEN_NAME can also be set if the token GET parameter must be customized.
[ "Decorator", "which", "ensures", "that", "one", "of", "the", "WATCHMAN_TOKENS", "is", "provided", "if", "set", "." ]
python
test
DataBiosphere/dsub
dsub/lib/dsub_util.py
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L233-L246
def file_exists(file_path, credentials=None): """Check whether the file exists, on local disk or GCS. Args: file_path: The target file path; should have the 'gs://' prefix if in gcs. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there. """ if ...
[ "def", "file_exists", "(", "file_path", ",", "credentials", "=", "None", ")", ":", "if", "file_path", ".", "startswith", "(", "'gs://'", ")", ":", "return", "_file_exists_in_gcs", "(", "file_path", ",", "credentials", ")", "else", ":", "return", "os", ".", ...
Check whether the file exists, on local disk or GCS. Args: file_path: The target file path; should have the 'gs://' prefix if in gcs. credentials: Optional credential to be used to load the file from gcs. Returns: True if the file's there.
[ "Check", "whether", "the", "file", "exists", "on", "local", "disk", "or", "GCS", "." ]
python
valid
sci-bots/pygtkhelpers
pygtkhelpers/ui/extra_dialogs.py
https://github.com/sci-bots/pygtkhelpers/blob/3a6e6d6340221c686229cd1c951d7537dae81b07/pygtkhelpers/ui/extra_dialogs.py#L27-L39
def combobox_set_model_from_list(cb, items): """Setup a ComboBox or ComboBoxEntry based on a list of strings.""" cb.clear() model = gtk.ListStore(str) for i in items: model.append([i]) cb.set_model(model) if type(cb) == gtk.ComboBoxEntry: cb.set_text_column(0) elif type(cb) =...
[ "def", "combobox_set_model_from_list", "(", "cb", ",", "items", ")", ":", "cb", ".", "clear", "(", ")", "model", "=", "gtk", ".", "ListStore", "(", "str", ")", "for", "i", "in", "items", ":", "model", ".", "append", "(", "[", "i", "]", ")", "cb", ...
Setup a ComboBox or ComboBoxEntry based on a list of strings.
[ "Setup", "a", "ComboBox", "or", "ComboBoxEntry", "based", "on", "a", "list", "of", "strings", "." ]
python
train
pyopenapi/pyswagger
pyswagger/spec/base.py
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L246-L257
def update_field(self, f, obj): """ update a field :param str f: name of field to be updated. :param obj: value of field to be updated. """ n = self.get_private_name(f) if not hasattr(self, n): raise AttributeError('{0} is not in {1}'.format(n, self.__class__...
[ "def", "update_field", "(", "self", ",", "f", ",", "obj", ")", ":", "n", "=", "self", ".", "get_private_name", "(", "f", ")", "if", "not", "hasattr", "(", "self", ",", "n", ")", ":", "raise", "AttributeError", "(", "'{0} is not in {1}'", ".", "format",...
update a field :param str f: name of field to be updated. :param obj: value of field to be updated.
[ "update", "a", "field" ]
python
train
polysquare/polysquare-setuptools-lint
polysquare_setuptools_lint/__init__.py
https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L161-L166
def _run_flake8(filename, stamp_file_name, show_lint_files): """Run flake8, cached by stamp_file_name.""" _debug_linter_status("flake8", filename, show_lint_files) return _stamped_deps(stamp_file_name, _run_flake8_internal, filename)
[ "def", "_run_flake8", "(", "filename", ",", "stamp_file_name", ",", "show_lint_files", ")", ":", "_debug_linter_status", "(", "\"flake8\"", ",", "filename", ",", "show_lint_files", ")", "return", "_stamped_deps", "(", "stamp_file_name", ",", "_run_flake8_internal", ",...
Run flake8, cached by stamp_file_name.
[ "Run", "flake8", "cached", "by", "stamp_file_name", "." ]
python
train
cltk/cltk
cltk/prosody/old_norse/verse.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/old_norse/verse.py#L293-L314
def to_phonetics(self): """ Transcribing words in verse helps find alliteration. """ if len(self.long_lines) == 0: logger.error("No text was imported") self.syllabified_text = [] else: transcriber = Transcriber(DIPHTHONGS_IPA, DIPHTHONGS_IPA_cl...
[ "def", "to_phonetics", "(", "self", ")", ":", "if", "len", "(", "self", ".", "long_lines", ")", "==", "0", ":", "logger", ".", "error", "(", "\"No text was imported\"", ")", "self", ".", "syllabified_text", "=", "[", "]", "else", ":", "transcriber", "=",...
Transcribing words in verse helps find alliteration.
[ "Transcribing", "words", "in", "verse", "helps", "find", "alliteration", "." ]
python
train
has2k1/plotnine
plotnine/guides/guide_colorbar.py
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide_colorbar.py#L295-L321
def add_segmented_colorbar(da, colors, direction): """ Add 'non-rastered' colorbar to DrawingArea """ nbreak = len(colors) if direction == 'vertical': linewidth = da.height/nbreak verts = [None] * nbreak x1, x2 = 0, da.width for i, color in enumerate(colors): ...
[ "def", "add_segmented_colorbar", "(", "da", ",", "colors", ",", "direction", ")", ":", "nbreak", "=", "len", "(", "colors", ")", "if", "direction", "==", "'vertical'", ":", "linewidth", "=", "da", ".", "height", "/", "nbreak", "verts", "=", "[", "None", ...
Add 'non-rastered' colorbar to DrawingArea
[ "Add", "non", "-", "rastered", "colorbar", "to", "DrawingArea" ]
python
train
psss/did
did/utils.py
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L382-L387
def enabled(self): """ True if coloring is currently enabled """ # In auto-detection mode color enabled when terminal attached if self._mode == COLOR_AUTO: return sys.stdout.isatty() return self._mode == COLOR_ON
[ "def", "enabled", "(", "self", ")", ":", "# In auto-detection mode color enabled when terminal attached", "if", "self", ".", "_mode", "==", "COLOR_AUTO", ":", "return", "sys", ".", "stdout", ".", "isatty", "(", ")", "return", "self", ".", "_mode", "==", "COLOR_O...
True if coloring is currently enabled
[ "True", "if", "coloring", "is", "currently", "enabled" ]
python
train
ellmetha/django-machina
machina/apps/forum_conversation/views.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L756-L776
def get_success_url(self): """ Returns the URL to redirect the user to upon valid form processing. """ messages.success(self.request, self.success_message) if self.object.is_topic_head and self.object.is_topic_tail: return reverse( 'forum:forum', kwar...
[ "def", "get_success_url", "(", "self", ")", ":", "messages", ".", "success", "(", "self", ".", "request", ",", "self", ".", "success_message", ")", "if", "self", ".", "object", ".", "is_topic_head", "and", "self", ".", "object", ".", "is_topic_tail", ":", ...
Returns the URL to redirect the user to upon valid form processing.
[ "Returns", "the", "URL", "to", "redirect", "the", "user", "to", "upon", "valid", "form", "processing", "." ]
python
train
emory-libraries/eulxml
eulxml/xmlmap/cerp.py
https://github.com/emory-libraries/eulxml/blob/17d71c7d98c0cebda9932b7f13e72093805e1fe2/eulxml/xmlmap/cerp.py#L219-L314
def from_email_message(cls, message, local_id=None): ''' Convert an :class:`email.message.Message` or compatible message object into a CERP XML :class:`eulxml.xmlmap.cerp.Message`. If an id is specified, it will be stored in the Message <LocalId>. :param message: `email.message....
[ "def", "from_email_message", "(", "cls", ",", "message", ",", "local_id", "=", "None", ")", ":", "result", "=", "cls", "(", ")", "if", "local_id", "is", "not", "None", ":", "result", ".", "local_id", "=", "id", "message_id", "=", "message", ".", "get",...
Convert an :class:`email.message.Message` or compatible message object into a CERP XML :class:`eulxml.xmlmap.cerp.Message`. If an id is specified, it will be stored in the Message <LocalId>. :param message: `email.message.Message` object :param id: optional message id to be set as `loca...
[ "Convert", "an", ":", "class", ":", "email", ".", "message", ".", "Message", "or", "compatible", "message", "object", "into", "a", "CERP", "XML", ":", "class", ":", "eulxml", ".", "xmlmap", ".", "cerp", ".", "Message", ".", "If", "an", "id", "is", "s...
python
train
jupyterhub/jupyter-server-proxy
jupyter_server_proxy/handlers.py
https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/handlers.py#L343-L377
async def ensure_process(self): """ Start the process """ # We don't want multiple requests trying to start the process at the same time # FIXME: Make sure this times out properly? # Invariant here should be: when lock isn't being held, either 'proc' is in state & ...
[ "async", "def", "ensure_process", "(", "self", ")", ":", "# We don't want multiple requests trying to start the process at the same time", "# FIXME: Make sure this times out properly?", "# Invariant here should be: when lock isn't being held, either 'proc' is in state &", "# running, or not.", ...
Start the process
[ "Start", "the", "process" ]
python
train
BerkeleyAutomation/perception
perception/kinect2_sensor.py
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/kinect2_sensor.py#L279-L339
def _frames_and_index_map(self, skip_registration=False): """Retrieve a new frame from the Kinect and return a ColorImage, DepthImage, IrImage, and a map from depth pixels to color pixel indices. Parameters ---------- skip_registration : bool If True, the registratio...
[ "def", "_frames_and_index_map", "(", "self", ",", "skip_registration", "=", "False", ")", ":", "if", "not", "self", ".", "_running", ":", "raise", "RuntimeError", "(", "'Kinect2 device %s not runnning. Cannot read frames'", "%", "(", "self", ".", "_device_num", ")",...
Retrieve a new frame from the Kinect and return a ColorImage, DepthImage, IrImage, and a map from depth pixels to color pixel indices. Parameters ---------- skip_registration : bool If True, the registration step is skipped. Returns ------- :obj:`tup...
[ "Retrieve", "a", "new", "frame", "from", "the", "Kinect", "and", "return", "a", "ColorImage", "DepthImage", "IrImage", "and", "a", "map", "from", "depth", "pixels", "to", "color", "pixel", "indices", "." ]
python
train
Josef-Friedrich/phrydy
phrydy/mediafile.py
https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/mediafile.py#L2189-L2207
def bitrate(self): """The number of bits per seconds used in the audio coding (an int). If this is provided explicitly by the compressed file format, this is a precise reflection of the encoding. Otherwise, it is estimated from the on-disk file size. In this case, some imprecisio...
[ "def", "bitrate", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "mgfile", ".", "info", ",", "'bitrate'", ")", "and", "self", ".", "mgfile", ".", "info", ".", "bitrate", ":", "# Many formats provide it explicitly.", "return", "self", ".", "mgfil...
The number of bits per seconds used in the audio coding (an int). If this is provided explicitly by the compressed file format, this is a precise reflection of the encoding. Otherwise, it is estimated from the on-disk file size. In this case, some imprecision is possible because the file...
[ "The", "number", "of", "bits", "per", "seconds", "used", "in", "the", "audio", "coding", "(", "an", "int", ")", ".", "If", "this", "is", "provided", "explicitly", "by", "the", "compressed", "file", "format", "this", "is", "a", "precise", "reflection", "o...
python
train
omza/azurestoragewrap
azurestoragewrap/queue.py
https://github.com/omza/azurestoragewrap/blob/976878e95d82ff0f7d8a00a5e4a7a3fb6268ab08/azurestoragewrap/queue.py#L62-L73
def getmessage(self) -> str: """ parse self into unicode string as message content """ image = {} for key, default in vars(self.__class__).items(): if not key.startswith('_') and key !='' and (not key in vars(QueueMessage).items()): ...
[ "def", "getmessage", "(", "self", ")", "->", "str", ":", "image", "=", "{", "}", "for", "key", ",", "default", "in", "vars", "(", "self", ".", "__class__", ")", ".", "items", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "'_'", ")", ...
parse self into unicode string as message content
[ "parse", "self", "into", "unicode", "string", "as", "message", "content" ]
python
train
djgagne/hagelslag
hagelslag/processing/ObjectMatcher.py
https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/processing/ObjectMatcher.py#L334-L348
def nonoverlap(item_a, time_a, item_b, time_b, max_value): """ Percentage of pixels in each object that do not overlap with the other object Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in Object...
[ "def", "nonoverlap", "(", "item_a", ",", "time_a", ",", "item_b", ",", "time_b", ",", "max_value", ")", ":", "return", "np", ".", "minimum", "(", "1", "-", "item_a", ".", "count_overlap", "(", "time_a", ",", "item_b", ",", "time_b", ")", ",", "max_valu...
Percentage of pixels in each object that do not overlap with the other object Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value:...
[ "Percentage", "of", "pixels", "in", "each", "object", "that", "do", "not", "overlap", "with", "the", "other", "object" ]
python
train
allenai/allennlp
allennlp/semparse/domain_languages/nlvr_language.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L125-L199
def get_agenda_for_sentence(self, sentence: str) -> List[str]: """ Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The ``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This is a simplistic mapping at this point...
[ "def", "get_agenda_for_sentence", "(", "self", ",", "sentence", ":", "str", ")", "->", "List", "[", "str", "]", ":", "agenda", "=", "[", "]", "sentence", "=", "sentence", ".", "lower", "(", ")", "if", "sentence", ".", "startswith", "(", "\"there is a box...
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The ``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This is a simplistic mapping at this point, and can be expanded. Parameters ---------- sentence : ``...
[ "Given", "a", "sentence", "returns", "a", "list", "of", "actions", "the", "sentence", "triggers", "as", "an", "agenda", ".", "The", "agenda", "can", "be", "used", "while", "by", "a", "parser", "to", "guide", "the", "decoder", ".", "sequences", "as", "pos...
python
train
Jaymon/prom
prom/interface/base.py
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/base.py#L233-L253
def transaction(self, connection=None, **kwargs): """ a simple context manager useful for when you want to wrap a bunch of db calls in a transaction http://docs.python.org/2/library/contextlib.html http://docs.python.org/release/2.5/whatsnew/pep-343.html example -- w...
[ "def", "transaction", "(", "self", ",", "connection", "=", "None", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "connection", "(", "connection", ")", "as", "connection", ":", "name", "=", "connection", ".", "transaction_name", "(", ")", "conne...
a simple context manager useful for when you want to wrap a bunch of db calls in a transaction http://docs.python.org/2/library/contextlib.html http://docs.python.org/release/2.5/whatsnew/pep-343.html example -- with self.transaction() # do a bunch of calls ...
[ "a", "simple", "context", "manager", "useful", "for", "when", "you", "want", "to", "wrap", "a", "bunch", "of", "db", "calls", "in", "a", "transaction", "http", ":", "//", "docs", ".", "python", ".", "org", "/", "2", "/", "library", "/", "contextlib", ...
python
train
ethereum/pyethereum
ethereum/slogging.py
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/slogging.py#L349-L356
def DEBUG(msg, *args, **kwargs): """temporary logger during development that is always on""" logger = getLogger("DEBUG") if len(logger.handlers) == 0: logger.addHandler(StreamHandler()) logger.propagate = False logger.setLevel(logging.DEBUG) logger.DEV(msg, *args, **kwargs)
[ "def", "DEBUG", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", "=", "getLogger", "(", "\"DEBUG\"", ")", "if", "len", "(", "logger", ".", "handlers", ")", "==", "0", ":", "logger", ".", "addHandler", "(", "StreamHandler", ...
temporary logger during development that is always on
[ "temporary", "logger", "during", "development", "that", "is", "always", "on" ]
python
train
mabuchilab/QNET
src/qnet/__init__.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/__init__.py#L23-L52
def _git_version(): """If installed with 'pip installe -e .' from inside a git repo, the current git revision as a string""" import subprocess import os def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.e...
[ "def", "_git_version", "(", ")", ":", "import", "subprocess", "import", "os", "def", "_minimal_ext_cmd", "(", "cmd", ")", ":", "# construct minimal environment", "env", "=", "{", "}", "for", "k", "in", "[", "'SYSTEMROOT'", ",", "'PATH'", "]", ":", "v", "="...
If installed with 'pip installe -e .' from inside a git repo, the current git revision as a string
[ "If", "installed", "with", "pip", "installe", "-", "e", ".", "from", "inside", "a", "git", "repo", "the", "current", "git", "revision", "as", "a", "string" ]
python
train
tensorflow/probability
tensorflow_probability/python/distributions/onehot_categorical.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/onehot_categorical.py#L241-L258
def _kl_categorical_categorical(a, b, name=None): """Calculate the batched KL divergence KL(a || b) with a, b OneHotCategorical. Args: a: instance of a OneHotCategorical distribution object. b: instance of a OneHotCategorical distribution object. name: (optional) Name to use for created operations. ...
[ "def", "_kl_categorical_categorical", "(", "a", ",", "b", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", "or", "\"kl_categorical_categorical\"", ")", ":", "# sum(p ln(p / q))", "return", "tf", ".", "reduce_sum", "(", "input_t...
Calculate the batched KL divergence KL(a || b) with a, b OneHotCategorical. Args: a: instance of a OneHotCategorical distribution object. b: instance of a OneHotCategorical distribution object. name: (optional) Name to use for created operations. default is "kl_categorical_categorical". Returns:...
[ "Calculate", "the", "batched", "KL", "divergence", "KL", "(", "a", "||", "b", ")", "with", "a", "b", "OneHotCategorical", "." ]
python
test
awslabs/sockeye
sockeye/inference.py
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/inference.py#L2209-L2231
def _get_best_word_indices_for_kth_hypotheses(ks: np.ndarray, all_hyp_indices: np.ndarray) -> np.ndarray: """ Traverses the matrix of best hypotheses indices collected during beam search in reversed order by using the kth hypotheses index as a backpointer. Returns an array containing the...
[ "def", "_get_best_word_indices_for_kth_hypotheses", "(", "ks", ":", "np", ".", "ndarray", ",", "all_hyp_indices", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "batch_size", "=", "ks", ".", "shape", "[", "0", "]", "num_steps", "=", "all_...
Traverses the matrix of best hypotheses indices collected during beam search in reversed order by using the kth hypotheses index as a backpointer. Returns an array containing the indices into the best_word_indices collected during beam search to extract the kth hypotheses. :param ks: Th...
[ "Traverses", "the", "matrix", "of", "best", "hypotheses", "indices", "collected", "during", "beam", "search", "in", "reversed", "order", "by", "using", "the", "kth", "hypotheses", "index", "as", "a", "backpointer", ".", "Returns", "an", "array", "containing", ...
python
train
Miserlou/Zappa
zappa/core.py
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L1985-L2014
def undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None): """ Delete a deployed REST API Gateway. """ print("Deleting API Gateway..") api_id = self.get_api_id(lambda_name) if domain_name: # XXX - Remove Route53 smartly here? ...
[ "def", "undeploy_api_gateway", "(", "self", ",", "lambda_name", ",", "domain_name", "=", "None", ",", "base_path", "=", "None", ")", ":", "print", "(", "\"Deleting API Gateway..\"", ")", "api_id", "=", "self", ".", "get_api_id", "(", "lambda_name", ")", "if", ...
Delete a deployed REST API Gateway.
[ "Delete", "a", "deployed", "REST", "API", "Gateway", "." ]
python
train
cloud9ers/gurumate
environment/share/doc/ipython/examples/parallel/davinci/pwordfreq.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/davinci/pwordfreq.py#L20-L37
def pwordfreq(view, fnames): """Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data. """ assert len(fnames) == len(view.targets) view.scatter('fname', fnames, flatten=True) ar = view.apply(wordfreq, Reference('fname')) freqs...
[ "def", "pwordfreq", "(", "view", ",", "fnames", ")", ":", "assert", "len", "(", "fnames", ")", "==", "len", "(", "view", ".", "targets", ")", "view", ".", "scatter", "(", "'fname'", ",", "fnames", ",", "flatten", "=", "True", ")", "ar", "=", "view"...
Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data.
[ "Parallel", "word", "frequency", "counter", ".", "view", "-", "An", "IPython", "DirectView", "fnames", "-", "The", "filenames", "containing", "the", "split", "data", "." ]
python
test
materialsproject/pymatgen
pymatgen/io/qchem/outputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/qchem/outputs.py#L586-L624
def _read_pcm_information(self): """ Parses information from PCM solvent calculations. """ temp_dict = read_pattern( self.text, { "g_electrostatic": r"\s*G_electrostatic\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*", "g_cavitati...
[ "def", "_read_pcm_information", "(", "self", ")", ":", "temp_dict", "=", "read_pattern", "(", "self", ".", "text", ",", "{", "\"g_electrostatic\"", ":", "r\"\\s*G_electrostatic\\s+=\\s+([\\d\\-\\.]+)\\s+hartree\\s+=\\s+([\\d\\-\\.]+)\\s+kcal/mol\\s*\"", ",", "\"g_cavitation\"",...
Parses information from PCM solvent calculations.
[ "Parses", "information", "from", "PCM", "solvent", "calculations", "." ]
python
train
jupyter-widgets/ipywidgets
ipywidgets/widgets/widget.py
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L266-L284
def register(name=''): "For backwards compatibility, we support @register(name) syntax." def reg(widget): """A decorator registering a widget class in the widget registry.""" w = widget.class_traits() Widget.widget_types.register(w['_model_module'].default_value, ...
[ "def", "register", "(", "name", "=", "''", ")", ":", "def", "reg", "(", "widget", ")", ":", "\"\"\"A decorator registering a widget class in the widget registry.\"\"\"", "w", "=", "widget", ".", "class_traits", "(", ")", "Widget", ".", "widget_types", ".", "regist...
For backwards compatibility, we support @register(name) syntax.
[ "For", "backwards", "compatibility", "we", "support" ]
python
train
Karaage-Cluster/karaage
karaage/common/create_update.py
https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/common/create_update.py#L12-L21
def apply_extra_context(extra_context, context): """ Adds items from extra_context dict to context. If a value in extra_context is callable, then it is called and the result is added to context. """ for key, value in six.iteritems(extra_context): if callable(value): context[key]...
[ "def", "apply_extra_context", "(", "extra_context", ",", "context", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "extra_context", ")", ":", "if", "callable", "(", "value", ")", ":", "context", "[", "key", "]", "=", "value", ...
Adds items from extra_context dict to context. If a value in extra_context is callable, then it is called and the result is added to context.
[ "Adds", "items", "from", "extra_context", "dict", "to", "context", ".", "If", "a", "value", "in", "extra_context", "is", "callable", "then", "it", "is", "called", "and", "the", "result", "is", "added", "to", "context", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_lag.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_lag.py#L84-L96
def get_port_channel_detail_output_lacp_aggregator_mode(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_detai...
[ "def", "get_port_channel_detail_output_lacp_aggregator_mode", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_port_channel_detail", "=", "ET", ".", "Element", "(", "\"get_port_channel_detail\"", ")", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
pytroll/satpy
satpy/readers/goes_imager_hrit.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/goes_imager_hrit.py#L430-L443
def _calibrate(self, data): """Calibrate *data*.""" idx = self.mda['calibration_parameters']['indices'] val = self.mda['calibration_parameters']['values'] data.data = da.where(data.data == 0, np.nan, data.data) ddata = data.data.map_blocks(np.interp, idx, val, dtype=val.dtype) ...
[ "def", "_calibrate", "(", "self", ",", "data", ")", ":", "idx", "=", "self", ".", "mda", "[", "'calibration_parameters'", "]", "[", "'indices'", "]", "val", "=", "self", ".", "mda", "[", "'calibration_parameters'", "]", "[", "'values'", "]", "data", ".",...
Calibrate *data*.
[ "Calibrate", "*", "data", "*", "." ]
python
train
Alignak-monitoring/alignak
alignak/objects/service.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1756-L1785
def register_service_dependencies(service, servicedependencies): """ Registers a service dependencies. :param service: The service to register :type service: :param servicedependencies: The servicedependencies container :type servicedependencies: :return: None ...
[ "def", "register_service_dependencies", "(", "service", ",", "servicedependencies", ")", ":", "# We explode service_dependencies into Servicedependency", "# We just create serviceDep with goods values (as STRING!),", "# the link pass will be done after", "sdeps", "=", "[", "d", ".", ...
Registers a service dependencies. :param service: The service to register :type service: :param servicedependencies: The servicedependencies container :type servicedependencies: :return: None
[ "Registers", "a", "service", "dependencies", "." ]
python
train
rande/python-simple-ioc
ioc/locator.py
https://github.com/rande/python-simple-ioc/blob/36ddf667c1213a07a53cd4cdd708d02494e5190b/ioc/locator.py#L26-L38
def split_resource_path(resource): """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ pieces = [] for piece in resource.split('/'): if path.sep in piece \ or (path.altsep and path.altsep in piece)...
[ "def", "split_resource_path", "(", "resource", ")", ":", "pieces", "=", "[", "]", "for", "piece", "in", "resource", ".", "split", "(", "'/'", ")", ":", "if", "path", ".", "sep", "in", "piece", "or", "(", "path", ".", "altsep", "and", "path", ".", "...
Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error.
[ "Split", "a", "path", "into", "segments", "and", "perform", "a", "sanity", "check", ".", "If", "it", "detects", "..", "in", "the", "path", "it", "will", "raise", "a", "TemplateNotFound", "error", "." ]
python
train
explosion/spaCy
spacy/_ml.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L693-L709
def masked_language_model(vocab, model, mask_prob=0.15): """Convert a model into a BERT-style masked language model""" random_words = _RandomWords(vocab) def mlm_forward(docs, drop=0.0): mask, docs = _apply_mask(docs, random_words, mask_prob=mask_prob) mask = model.ops.asarray(mask).reshap...
[ "def", "masked_language_model", "(", "vocab", ",", "model", ",", "mask_prob", "=", "0.15", ")", ":", "random_words", "=", "_RandomWords", "(", "vocab", ")", "def", "mlm_forward", "(", "docs", ",", "drop", "=", "0.0", ")", ":", "mask", ",", "docs", "=", ...
Convert a model into a BERT-style masked language model
[ "Convert", "a", "model", "into", "a", "BERT", "-", "style", "masked", "language", "model" ]
python
train
reorx/torext
torext/sql.py
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/sql.py#L378-L382
def coerce(cls, key, value): """Convert plain list to MutationList""" self = MutationList((MutationObj.coerce(key, v) for v in value)) self._key = key return self
[ "def", "coerce", "(", "cls", ",", "key", ",", "value", ")", ":", "self", "=", "MutationList", "(", "(", "MutationObj", ".", "coerce", "(", "key", ",", "v", ")", "for", "v", "in", "value", ")", ")", "self", ".", "_key", "=", "key", "return", "self...
Convert plain list to MutationList
[ "Convert", "plain", "list", "to", "MutationList" ]
python
train
Pytwitcher/pytwitcherapi
src/pytwitcherapi/session.py
https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/session.py#L543-L556
def get_channel_access_token(self, channel): """Return the token and sig for the given channel :param channel: the channel or channel name to get the access token for :type channel: :class:`channel` | :class:`str` :returns: The token and sig for the given channel :rtype: (:class...
[ "def", "get_channel_access_token", "(", "self", ",", "channel", ")", ":", "if", "isinstance", "(", "channel", ",", "models", ".", "Channel", ")", ":", "channel", "=", "channel", ".", "name", "r", "=", "self", ".", "oldapi_request", "(", "'GET'", ",", "'c...
Return the token and sig for the given channel :param channel: the channel or channel name to get the access token for :type channel: :class:`channel` | :class:`str` :returns: The token and sig for the given channel :rtype: (:class:`unicode`, :class:`unicode`) :raises: None
[ "Return", "the", "token", "and", "sig", "for", "the", "given", "channel" ]
python
train
kibitzr/kibitzr
kibitzr/storage.py
https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/storage.py#L62-L67
def write(self, content): """Save content on disk""" with io.open(self.target, 'w', encoding='utf-8') as fp: fp.write(content) if not content.endswith(u'\n'): fp.write(u'\n')
[ "def", "write", "(", "self", ",", "content", ")", ":", "with", "io", ".", "open", "(", "self", ".", "target", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "fp", ":", "fp", ".", "write", "(", "content", ")", "if", "not", "content", ".",...
Save content on disk
[ "Save", "content", "on", "disk" ]
python
train
envi-idl/envipyarclib
envipyarclib/gptool/parameter/builder.py
https://github.com/envi-idl/envipyarclib/blob/90135652510c3d53c5f51177252c1fea2639bf22/envipyarclib/gptool/parameter/builder.py#L100-L163
def create_param_info(task_params, parameter_map): """ Builds the code block for the GPTool GetParameterInfo method based on the input task_params. :param task_params: A list of task parameters to map to GPTool parameters. :return: A string representing the code block to the GPTool GetParameterInfo met...
[ "def", "create_param_info", "(", "task_params", ",", "parameter_map", ")", ":", "gp_params", "=", "[", "]", "gp_param_list", "=", "[", "]", "gp_param_idx_list", "=", "[", "]", "gp_param_idx", "=", "0", "for", "task_param", "in", "task_params", ":", "# Setup to...
Builds the code block for the GPTool GetParameterInfo method based on the input task_params. :param task_params: A list of task parameters to map to GPTool parameters. :return: A string representing the code block to the GPTool GetParameterInfo method.
[ "Builds", "the", "code", "block", "for", "the", "GPTool", "GetParameterInfo", "method", "based", "on", "the", "input", "task_params", "." ]
python
train