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
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/runsnakerun/runsnake.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/runsnakerun/runsnake.py#L637-L641
def OnMoreSquareToggle( self, event ): """Toggle the more-square view (better looking, but more likely to filter records)""" self.squareMap.square_style = not self.squareMap.square_style self.squareMap.Refresh() self.moreSquareViewItem.Check(self.squareMap.square_style)
[ "def", "OnMoreSquareToggle", "(", "self", ",", "event", ")", ":", "self", ".", "squareMap", ".", "square_style", "=", "not", "self", ".", "squareMap", ".", "square_style", "self", ".", "squareMap", ".", "Refresh", "(", ")", "self", ".", "moreSquareViewItem",...
Toggle the more-square view (better looking, but more likely to filter records)
[ "Toggle", "the", "more", "-", "square", "view", "(", "better", "looking", "but", "more", "likely", "to", "filter", "records", ")" ]
python
train
openpermissions/perch
perch/organisation.py
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L475-L488
def can_update(self, user, **kwargs): """Org admins may not update organisation_id or service_type""" if user.is_admin(): raise Return((True, set([]))) is_creator = self.created_by == user.id if not (user.is_org_admin(self.organisation_id) or is_creator): raise R...
[ "def", "can_update", "(", "self", ",", "user", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_admin", "(", ")", ":", "raise", "Return", "(", "(", "True", ",", "set", "(", "[", "]", ")", ")", ")", "is_creator", "=", "self", ".", "crea...
Org admins may not update organisation_id or service_type
[ "Org", "admins", "may", "not", "update", "organisation_id", "or", "service_type" ]
python
train
twisted/mantissa
xmantissa/sharing.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L470-L487
def _interfacesToNames(interfaces): """ Convert from a list of interfaces to a unicode string of names suitable for storage in the database. @param interfaces: an iterable of Interface objects. @return: a unicode string, a comma-separated list of names of interfaces. @raise ConflictingNames: ...
[ "def", "_interfacesToNames", "(", "interfaces", ")", ":", "if", "interfaces", "is", "ALL_IMPLEMENTED", ":", "names", "=", "ALL_IMPLEMENTED_DB", "else", ":", "_checkConflictingNames", "(", "interfaces", ")", "names", "=", "u','", ".", "join", "(", "map", "(", "...
Convert from a list of interfaces to a unicode string of names suitable for storage in the database. @param interfaces: an iterable of Interface objects. @return: a unicode string, a comma-separated list of names of interfaces. @raise ConflictingNames: if any of the names conflict: see L{_checkCo...
[ "Convert", "from", "a", "list", "of", "interfaces", "to", "a", "unicode", "string", "of", "names", "suitable", "for", "storage", "in", "the", "database", "." ]
python
train
google/prettytensor
prettytensor/scopes.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/scopes.py#L27-L74
def var_and_name_scope(names): """Creates a variable scope and a name scope. If a variable_scope is provided, this will reenter that variable scope. However, if none is provided then the variable scope will match the generated part of the name scope. Args: names: A tuple of name_scope, variable_scope or...
[ "def", "var_and_name_scope", "(", "names", ")", ":", "# pylint: disable=protected-access", "if", "not", "names", ":", "yield", "None", ",", "None", "else", ":", "name", ",", "var_scope", "=", "names", "with", "tf", ".", "name_scope", "(", "name", ")", "as", ...
Creates a variable scope and a name scope. If a variable_scope is provided, this will reenter that variable scope. However, if none is provided then the variable scope will match the generated part of the name scope. Args: names: A tuple of name_scope, variable_scope or None. Yields: The result of n...
[ "Creates", "a", "variable", "scope", "and", "a", "name", "scope", "." ]
python
train
iterative/dvc
dvc/cli.py
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/cli.py#L122-L167
def parse_args(argv=None): """Parses CLI arguments. Args: argv: optional list of arguments to parse. sys.argv is used by default. Raises: dvc.exceptions.DvcParserError: raised for argument parsing errors. """ parent_parser = get_parent_parser() # Main parser desc = "Data V...
[ "def", "parse_args", "(", "argv", "=", "None", ")", ":", "parent_parser", "=", "get_parent_parser", "(", ")", "# Main parser", "desc", "=", "\"Data Version Control\"", "parser", "=", "DvcParser", "(", "prog", "=", "\"dvc\"", ",", "description", "=", "desc", ",...
Parses CLI arguments. Args: argv: optional list of arguments to parse. sys.argv is used by default. Raises: dvc.exceptions.DvcParserError: raised for argument parsing errors.
[ "Parses", "CLI", "arguments", "." ]
python
train
google/textfsm
textfsm/parser.py
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L659-L680
def _Parse(self, template): """Parses template file for FSM structure. Args: template: Valid template file. Raises: TextFSMTemplateError: If template file syntax is invalid. """ if not template: raise TextFSMTemplateError('Null template.') # Parse header with Variables. ...
[ "def", "_Parse", "(", "self", ",", "template", ")", ":", "if", "not", "template", ":", "raise", "TextFSMTemplateError", "(", "'Null template.'", ")", "# Parse header with Variables.", "self", ".", "_ParseFSMVariables", "(", "template", ")", "# Parse States.", "while...
Parses template file for FSM structure. Args: template: Valid template file. Raises: TextFSMTemplateError: If template file syntax is invalid.
[ "Parses", "template", "file", "for", "FSM", "structure", "." ]
python
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsHandle_Edit.py
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsHandle_Edit.py#L2157-L2281
def SetManagedObject(self, inMo, classId=None, params=None, dumpXml=None): """ Modifies Managed Object in UCS. - inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an inMo. It can be a single MO or a list containing multiple managed ...
[ "def", "SetManagedObject", "(", "self", ",", "inMo", ",", "classId", "=", "None", ",", "params", "=", "None", ",", "dumpXml", "=", "None", ")", ":", "from", "UcsBase", "import", "UcsUtils", ",", "ManagedObject", ",", "WriteUcsWarning", ",", "WriteObject", ...
Modifies Managed Object in UCS. - inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an inMo. It can be a single MO or a list containing multiple managed objects. - classId of the managed object/s to be modified. - params contains se...
[ "Modifies", "Managed", "Object", "in", "UCS", ".", "-", "inMo", "if", "provided", "it", "acts", "as", "the", "target", "object", "for", "the", "present", "operation", ".", "It", "should", "be", "None", "unless", "a", "user", "wants", "to", "provide", "an...
python
train
Kunstmord/datalib
src/dataset.py
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L723-L740
def return_features_numpy(self, names='all'): """ Returns a 2d numpy array of extracted features Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', all features will be returned, default ...
[ "def", "return_features_numpy", "(", "self", ",", "names", "=", "'all'", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "raise", "errors", ".", "EmptyDatabase", "(", "self", ".", "dbpath", ")", "else", ":", "return", "return_features_numpy...
Returns a 2d numpy array of extracted features Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', all features will be returned, default value: 'all' Returns ------- A numpy arra...
[ "Returns", "a", "2d", "numpy", "array", "of", "extracted", "features" ]
python
train
swharden/SWHLab
doc/oldcode/swhlab/core/abf.py
https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/abf.py#L506-L517
def loadThing(self,fname,ext=".pkl"): """save any object from /swhlab4/ID_[fname].pkl""" if ext and not ext in fname: fname+=ext fname=self.outpre+fname time1=cm.timethis() thing = pickle.load(open(fname,"rb")) print(" -> loading [%s] (%.01f kB) took %.02f ms"...
[ "def", "loadThing", "(", "self", ",", "fname", ",", "ext", "=", "\".pkl\"", ")", ":", "if", "ext", "and", "not", "ext", "in", "fname", ":", "fname", "+=", "ext", "fname", "=", "self", ".", "outpre", "+", "fname", "time1", "=", "cm", ".", "timethis"...
save any object from /swhlab4/ID_[fname].pkl
[ "save", "any", "object", "from", "/", "swhlab4", "/", "ID_", "[", "fname", "]", ".", "pkl" ]
python
valid
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L163-L278
def embed_ising(source_linear, source_quadratic, embedding, target_adjacency, chain_strength=1.0): """Embeds a logical Ising model onto another graph via an embedding. Args: source_linear (dict): The linear biases to be embedded. Should be a dict of the form {v: bias, ...} where v is a vari...
[ "def", "embed_ising", "(", "source_linear", ",", "source_quadratic", ",", "embedding", ",", "target_adjacency", ",", "chain_strength", "=", "1.0", ")", ":", "# store variables in the target graph that the embedding hasn't used", "unused", "=", "{", "v", "for", "v", "in"...
Embeds a logical Ising model onto another graph via an embedding. Args: source_linear (dict): The linear biases to be embedded. Should be a dict of the form {v: bias, ...} where v is a variable in the source model and bias is the linear bias associated with v. source_quadrat...
[ "Embeds", "a", "logical", "Ising", "model", "onto", "another", "graph", "via", "an", "embedding", "." ]
python
train
flying-sheep/bcode
bcoding.py
https://github.com/flying-sheep/bcode/blob/a50996aa1741685c2daba6a9b4893692f377695a/bcoding.py#L181-L195
def bencode(data, f=None): """ Writes a serializable data piece to f The order of tests is nonarbitrary, as strings and mappings are iterable. If f is None, it writes to a byte buffer and returns a bytestring """ if f is None: f = BytesIO() _bencode_to_file(data, f) return f.getvalue() else: _bencode...
[ "def", "bencode", "(", "data", ",", "f", "=", "None", ")", ":", "if", "f", "is", "None", ":", "f", "=", "BytesIO", "(", ")", "_bencode_to_file", "(", "data", ",", "f", ")", "return", "f", ".", "getvalue", "(", ")", "else", ":", "_bencode_to_file", ...
Writes a serializable data piece to f The order of tests is nonarbitrary, as strings and mappings are iterable. If f is None, it writes to a byte buffer and returns a bytestring
[ "Writes", "a", "serializable", "data", "piece", "to", "f", "The", "order", "of", "tests", "is", "nonarbitrary", "as", "strings", "and", "mappings", "are", "iterable", ".", "If", "f", "is", "None", "it", "writes", "to", "a", "byte", "buffer", "and", "retu...
python
train
Yelp/kafka-utils
kafka_utils/kafka_rolling_restart/main.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L489-L514
def get_task_class(tasks, task_args): """Reads in a list of tasks provided by the user, loads the appropiate task, and returns two lists, pre_stop_tasks and post_stop_tasks :param tasks: list of strings locating tasks to load :type tasks: list :param task_args: list of strings to be used as args...
[ "def", "get_task_class", "(", "tasks", ",", "task_args", ")", ":", "pre_stop_tasks", "=", "[", "]", "post_stop_tasks", "=", "[", "]", "task_to_task_args", "=", "dict", "(", "list", "(", "zip", "(", "tasks", ",", "task_args", ")", ")", ")", "tasks_classes",...
Reads in a list of tasks provided by the user, loads the appropiate task, and returns two lists, pre_stop_tasks and post_stop_tasks :param tasks: list of strings locating tasks to load :type tasks: list :param task_args: list of strings to be used as args :type task_args: list
[ "Reads", "in", "a", "list", "of", "tasks", "provided", "by", "the", "user", "loads", "the", "appropiate", "task", "and", "returns", "two", "lists", "pre_stop_tasks", "and", "post_stop_tasks", ":", "param", "tasks", ":", "list", "of", "strings", "locating", "...
python
train
senaite/senaite.core
bika/lims/content/arimport.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/arimport.py#L712-L776
def validate_headers(self): """Validate headers fields from schema """ pc = getToolByName(self, 'portal_catalog') pu = getToolByName(self, "plone_utils") client = self.aq_parent # Verify Client Name if self.getClientName() != client.Title(): self.er...
[ "def", "validate_headers", "(", "self", ")", ":", "pc", "=", "getToolByName", "(", "self", ",", "'portal_catalog'", ")", "pu", "=", "getToolByName", "(", "self", ",", "\"plone_utils\"", ")", "client", "=", "self", ".", "aq_parent", "# Verify Client Name", "if"...
Validate headers fields from schema
[ "Validate", "headers", "fields", "from", "schema" ]
python
train
aleju/imgaug
imgaug/augmenters/contrast.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/contrast.py#L109-L181
def adjust_contrast_sigmoid(arr, gain, cutoff): """ Adjust contrast by scaling each pixel value to ``255 * 1/(1 + exp(gain*(cutoff - I_ij/255)))``. dtype support:: * ``uint8``: yes; fully tested (1) (2) (3) * ``uint16``: yes; tested (2) (3) * ``uint32``: yes; tested (2) (3) ...
[ "def", "adjust_contrast_sigmoid", "(", "arr", ",", "gain", ",", "cutoff", ")", ":", "# int8 is also possible according to docs", "# https://docs.opencv.org/3.0-beta/modules/core/doc/operations_on_arrays.html#cv2.LUT , but here it seemed", "# like `d` was 0 for CV_8S, causing that to fail", ...
Adjust contrast by scaling each pixel value to ``255 * 1/(1 + exp(gain*(cutoff - I_ij/255)))``. dtype support:: * ``uint8``: yes; fully tested (1) (2) (3) * ``uint16``: yes; tested (2) (3) * ``uint32``: yes; tested (2) (3) * ``uint64``: yes; tested (2) (3) (4) * ``int8``: l...
[ "Adjust", "contrast", "by", "scaling", "each", "pixel", "value", "to", "255", "*", "1", "/", "(", "1", "+", "exp", "(", "gain", "*", "(", "cutoff", "-", "I_ij", "/", "255", ")))", "." ]
python
valid
DLR-RM/RAFCON
source/rafcon/core/states/container_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1404-L1427
def add_scoped_variable(self, name, data_type=None, default_value=None, scoped_variable_id=None): """ Adds a scoped variable to the container state :param name: The name of the scoped variable :param data_type: An optional data type of the scoped variable :param default_value: An option...
[ "def", "add_scoped_variable", "(", "self", ",", "name", ",", "data_type", "=", "None", ",", "default_value", "=", "None", ",", "scoped_variable_id", "=", "None", ")", ":", "if", "scoped_variable_id", "is", "None", ":", "# All data port ids have to passed to the id g...
Adds a scoped variable to the container state :param name: The name of the scoped variable :param data_type: An optional data type of the scoped variable :param default_value: An optional default value of the scoped variable :param scoped_variable_id: An optional scoped variable id of t...
[ "Adds", "a", "scoped", "variable", "to", "the", "container", "state" ]
python
train
palantir/python-language-server
pyls/plugins/jedi_completion.py
https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/jedi_completion.py#L95-L102
def _sort_text(definition): """ Ensure builtins appear at the bottom. Description is of format <type>: <module>.<item> """ # If its 'hidden', put it next last prefix = 'z{}' if definition.name.startswith('_') else 'a{}' return prefix.format(definition.name)
[ "def", "_sort_text", "(", "definition", ")", ":", "# If its 'hidden', put it next last", "prefix", "=", "'z{}'", "if", "definition", ".", "name", ".", "startswith", "(", "'_'", ")", "else", "'a{}'", "return", "prefix", ".", "format", "(", "definition", ".", "n...
Ensure builtins appear at the bottom. Description is of format <type>: <module>.<item>
[ "Ensure", "builtins", "appear", "at", "the", "bottom", ".", "Description", "is", "of", "format", "<type", ">", ":", "<module", ">", ".", "<item", ">" ]
python
train
pixelogik/NearPy
nearpy/hashes/permutation/permutedIndex.py
https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/permutation/permutedIndex.py#L123-L148
def get_neighbour_keys(self, bucket_key, k): """ The computing complexity is O( np*beam*log(np*beam) ) where, np = number of permutations beam = self.beam_size Make sure np*beam is much less than the number of bucket keys, otherwise we could use brute-force to ge...
[ "def", "get_neighbour_keys", "(", "self", ",", "bucket_key", ",", "k", ")", ":", "# convert query_key into bitarray", "query_key", "=", "bitarray", "(", "bucket_key", ")", "topk", "=", "set", "(", ")", "for", "i", "in", "xrange", "(", "len", "(", "self", "...
The computing complexity is O( np*beam*log(np*beam) ) where, np = number of permutations beam = self.beam_size Make sure np*beam is much less than the number of bucket keys, otherwise we could use brute-force to get the neighbours
[ "The", "computing", "complexity", "is", "O", "(", "np", "*", "beam", "*", "log", "(", "np", "*", "beam", ")", ")", "where", "np", "=", "number", "of", "permutations", "beam", "=", "self", ".", "beam_size" ]
python
train
edx/edx-enterprise
enterprise/utils.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L485-L502
def get_enterprise_customer_or_404(enterprise_uuid): """ Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404. Arguments: enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch. Returns: (EnterpriseCustomer): The Ente...
[ "def", "get_enterprise_customer_or_404", "(", "enterprise_uuid", ")", ":", "EnterpriseCustomer", "=", "apps", ".", "get_model", "(", "'enterprise'", ",", "'EnterpriseCustomer'", ")", "# pylint: disable=invalid-name", "try", ":", "enterprise_uuid", "=", "UUID", "(", "ent...
Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404. Arguments: enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch. Returns: (EnterpriseCustomer): The EnterpriseCustomer given the UUID.
[ "Given", "an", "EnterpriseCustomer", "UUID", "return", "the", "corresponding", "EnterpriseCustomer", "or", "raise", "a", "404", "." ]
python
valid
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/app.py
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/app.py#L339-L356
def before_request(): """Checks to ensure that the session is valid and validates the users CSRF token is present Returns: `None` """ if not request.path.startswith('/saml') and not request.path.startswith('/auth'): # Validate the session has the items we need if 'accounts' not ...
[ "def", "before_request", "(", ")", ":", "if", "not", "request", ".", "path", ".", "startswith", "(", "'/saml'", ")", "and", "not", "request", ".", "path", ".", "startswith", "(", "'/auth'", ")", ":", "# Validate the session has the items we need", "if", "'acco...
Checks to ensure that the session is valid and validates the users CSRF token is present Returns: `None`
[ "Checks", "to", "ensure", "that", "the", "session", "is", "valid", "and", "validates", "the", "users", "CSRF", "token", "is", "present" ]
python
train
iDigBio/idigbio-python-client
idigbio/json_client.py
https://github.com/iDigBio/idigbio-python-client/blob/e896075b9fed297fc420caf303b3bb5a2298d969/idigbio/json_client.py#L315-L332
def search_records(self, rq={}, limit=100, offset=0, sort=None, fields=None, fields_exclude=FIELDS_EXCLUDE_DEFAULT): """ rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Record Query Fields fields ...
[ "def", "search_records", "(", "self", ",", "rq", "=", "{", "}", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "sort", "=", "None", ",", "fields", "=", "None", ",", "fields_exclude", "=", "FIELDS_EXCLUDE_DEFAULT", ")", ":", "if", "fields", "...
rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Record Query Fields fields a list of fields to return, specified using the fieldName parameter from Fields with type records fields_exclude a list of fields to exclude, specified...
[ "rq", "Search", "Query", "in", "iDigBio", "Query", "Format", "using", "Record", "Query", "Fields", "sort", "field", "to", "sort", "on", "pick", "from", "Record", "Query", "Fields", "fields", "a", "list", "of", "fields", "to", "return", "specified", "using", ...
python
train
ska-sa/katcp-python
katcp/kattypes.py
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L116-L142
def unpack(self, packed_value, major=DEFAULT_KATCP_MAJOR): """Parse a KATCP parameter into an object. Parameters ---------- packed_value : str The unescaped KATCP string to parse into a value. major : int, optional Major version of KATCP to use when inter...
[ "def", "unpack", "(", "self", ",", "packed_value", ",", "major", "=", "DEFAULT_KATCP_MAJOR", ")", ":", "if", "packed_value", "is", "None", ":", "value", "=", "self", ".", "get_default", "(", ")", "else", ":", "try", ":", "value", "=", "self", ".", "dec...
Parse a KATCP parameter into an object. Parameters ---------- packed_value : str The unescaped KATCP string to parse into a value. major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP versio...
[ "Parse", "a", "KATCP", "parameter", "into", "an", "object", "." ]
python
train
mgoral/subconvert
src/subconvert/utils/VideoPlayer.py
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L144-L148
def stop(self): """Stops playback""" if self.isPlaying is True: self._execute("stop") self._changePlayingState(False)
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "isPlaying", "is", "True", ":", "self", ".", "_execute", "(", "\"stop\"", ")", "self", ".", "_changePlayingState", "(", "False", ")" ]
Stops playback
[ "Stops", "playback" ]
python
train
ktdreyer/txkoji
txkoji/connection.py
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L232-L247
def getBuild(self, build_id, **kwargs): """ Load all information about a build and return a custom Build class. Calls "getBuild" XML-RPC. :param build_id: ``int``, for example 12345 :returns: deferred that when fired returns a Build (Munch, dict-like) object r...
[ "def", "getBuild", "(", "self", ",", "build_id", ",", "*", "*", "kwargs", ")", ":", "buildinfo", "=", "yield", "self", ".", "call", "(", "'getBuild'", ",", "build_id", ",", "*", "*", "kwargs", ")", "build", "=", "Build", ".", "fromDict", "(", "buildi...
Load all information about a build and return a custom Build class. Calls "getBuild" XML-RPC. :param build_id: ``int``, for example 12345 :returns: deferred that when fired returns a Build (Munch, dict-like) object representing this Koji build, or None if no build was ...
[ "Load", "all", "information", "about", "a", "build", "and", "return", "a", "custom", "Build", "class", "." ]
python
train
IntegralDefense/splunklib
splunklib/__init__.py
https://github.com/IntegralDefense/splunklib/blob/c3a02c83daad20cf24838f52b22cd2476f062eed/splunklib/__init__.py#L15-L30
def create_timedelta(timespec): """Utility function to translate DD:HH:MM:SS into a timedelta object.""" duration = timespec.split(':') seconds = int(duration[-1]) minutes = 0 hours = 0 days = 0 if len(duration) > 1: minutes = int(duration[-2]) if len(duration) > 2: hour...
[ "def", "create_timedelta", "(", "timespec", ")", ":", "duration", "=", "timespec", ".", "split", "(", "':'", ")", "seconds", "=", "int", "(", "duration", "[", "-", "1", "]", ")", "minutes", "=", "0", "hours", "=", "0", "days", "=", "0", "if", "len"...
Utility function to translate DD:HH:MM:SS into a timedelta object.
[ "Utility", "function", "to", "translate", "DD", ":", "HH", ":", "MM", ":", "SS", "into", "a", "timedelta", "object", "." ]
python
train
nchopin/particles
book/pmcmc/pmmh_lingauss_varying_scale.py
https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/book/pmcmc/pmmh_lingauss_varying_scale.py#L31-L37
def msjd(theta): """Mean squared jumping distance. """ s = 0. for p in theta.dtype.names: s += np.sum(np.diff(theta[p], axis=0) ** 2) return s
[ "def", "msjd", "(", "theta", ")", ":", "s", "=", "0.", "for", "p", "in", "theta", ".", "dtype", ".", "names", ":", "s", "+=", "np", ".", "sum", "(", "np", ".", "diff", "(", "theta", "[", "p", "]", ",", "axis", "=", "0", ")", "**", "2", ")...
Mean squared jumping distance.
[ "Mean", "squared", "jumping", "distance", "." ]
python
train
snare/scruffy
scruffy/plugin.py
https://github.com/snare/scruffy/blob/0fedc08cfdb6db927ff93c09f25f24ce5a04c541/scruffy/plugin.py#L38-L65
def load_plugins(self, directory): """ Loads plugins from the specified directory. `directory` is the full path to a directory containing python modules which each contain a subclass of the Plugin class. There is no criteria for a valid plugin at this level - any python ...
[ "def", "load_plugins", "(", "self", ",", "directory", ")", ":", "# walk directory", "for", "filename", "in", "os", ".", "listdir", "(", "directory", ")", ":", "# path to file", "filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filena...
Loads plugins from the specified directory. `directory` is the full path to a directory containing python modules which each contain a subclass of the Plugin class. There is no criteria for a valid plugin at this level - any python module found in the directory will be loaded. Only mod...
[ "Loads", "plugins", "from", "the", "specified", "directory", "." ]
python
test
meejah/txtorcon
txtorcon/torconfig.py
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L393-L408
def config_attributes(self): """ Helper method used by TorConfig when generating a torrc file. """ rtn = [('HiddenServiceDir', str(self.dir))] if self.conf._supports['HiddenServiceDirGroupReadable'] \ and self.group_readable: rtn.append(('HiddenServiceDirG...
[ "def", "config_attributes", "(", "self", ")", ":", "rtn", "=", "[", "(", "'HiddenServiceDir'", ",", "str", "(", "self", ".", "dir", ")", ")", "]", "if", "self", ".", "conf", ".", "_supports", "[", "'HiddenServiceDirGroupReadable'", "]", "and", "self", "....
Helper method used by TorConfig when generating a torrc file.
[ "Helper", "method", "used", "by", "TorConfig", "when", "generating", "a", "torrc", "file", "." ]
python
train
spyder-ide/spyder
spyder/widgets/fileswitcher.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L543-L552
def get_plugin_data(self, plugin): """Get the data object of the plugin's current tab manager.""" # The data object is named "data" in the editor plugin while it is # named "clients" in the notebook plugin. try: data = plugin.get_current_tab_manager().data except Attr...
[ "def", "get_plugin_data", "(", "self", ",", "plugin", ")", ":", "# The data object is named \"data\" in the editor plugin while it is", "# named \"clients\" in the notebook plugin.", "try", ":", "data", "=", "plugin", ".", "get_current_tab_manager", "(", ")", ".", "data", "...
Get the data object of the plugin's current tab manager.
[ "Get", "the", "data", "object", "of", "the", "plugin", "s", "current", "tab", "manager", "." ]
python
train
crackinglandia/pype32
pype32/pype32.py
https://github.com/crackinglandia/pype32/blob/192fd14dfc0dd36d953739a81c17fbaf5e3d6076/pype32/pype32.py#L860-L870
def isPeBounded(self): """ Determines if the current L{PE} instance is bounded, i.e. has a C{BOUND_IMPORT_DIRECTORY}. @rtype: bool @return: Returns C{True} if the current L{PE} instance is bounded. Otherwise, returns C{False}. """ boundImportsDir = self.ntHeaders...
[ "def", "isPeBounded", "(", "self", ")", ":", "boundImportsDir", "=", "self", ".", "ntHeaders", ".", "optionalHeader", ".", "dataDirectory", "[", "consts", ".", "BOUND_IMPORT_DIRECTORY", "]", "if", "boundImportsDir", ".", "rva", ".", "value", "and", "boundImports...
Determines if the current L{PE} instance is bounded, i.e. has a C{BOUND_IMPORT_DIRECTORY}. @rtype: bool @return: Returns C{True} if the current L{PE} instance is bounded. Otherwise, returns C{False}.
[ "Determines", "if", "the", "current", "L", "{", "PE", "}", "instance", "is", "bounded", "i", ".", "e", ".", "has", "a", "C", "{", "BOUND_IMPORT_DIRECTORY", "}", "." ]
python
train
codenerix/django-codenerix-invoicing
codenerix_invoicing/models_sales_original.py
https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_original.py#L1009-L1020
def create_albaran_automatic(pk, list_lines): """ creamos de forma automatica el albaran """ line_bd = SalesLineAlbaran.objects.filter(line_order__pk__in=list_lines).values_list('line_order__pk') if line_bd.count() == 0 or len(list_lines) != len(line_bd[0]): # solo aq...
[ "def", "create_albaran_automatic", "(", "pk", ",", "list_lines", ")", ":", "line_bd", "=", "SalesLineAlbaran", ".", "objects", ".", "filter", "(", "line_order__pk__in", "=", "list_lines", ")", ".", "values_list", "(", "'line_order__pk'", ")", "if", "line_bd", "....
creamos de forma automatica el albaran
[ "creamos", "de", "forma", "automatica", "el", "albaran" ]
python
train
ccubed/PyMoe
Pymoe/Kitsu/auth.py
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/auth.py#L50-L66
def refresh(self, refresh_token): """ Renew an oauth token given an appropriate refresh token. :param refresh_token: The Refresh Token :return: A tuple of (token, expiration time in unix time stamp) """ r = requests.post(self.apiurl + "/token", params={"grant_type": "ref...
[ "def", "refresh", "(", "self", ",", "refresh_token", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "apiurl", "+", "\"/token\"", ",", "params", "=", "{", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"client_id\"", ":", "self", ".", ...
Renew an oauth token given an appropriate refresh token. :param refresh_token: The Refresh Token :return: A tuple of (token, expiration time in unix time stamp)
[ "Renew", "an", "oauth", "token", "given", "an", "appropriate", "refresh", "token", "." ]
python
train
saltstack/salt
salt/runners/digicertapi.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/digicertapi.py#L92-L120
def _paginate(url, topkey, *args, **kwargs): ''' Wrapper to assist with paginated responses from Digicert's REST API. ''' ret = salt.utils.http.query(url, **kwargs) if 'errors' in ret['dict']: return ret['dict'] lim = int(ret['dict']['page']['limit']) total = int(ret['dict']['page'...
[ "def", "_paginate", "(", "url", ",", "topkey", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "salt", ".", "utils", ".", "http", ".", "query", "(", "url", ",", "*", "*", "kwargs", ")", "if", "'errors'", "in", "ret", "[", "'dic...
Wrapper to assist with paginated responses from Digicert's REST API.
[ "Wrapper", "to", "assist", "with", "paginated", "responses", "from", "Digicert", "s", "REST", "API", "." ]
python
train
twaldear/flask-secure-headers
flask_secure_headers/core.py
https://github.com/twaldear/flask-secure-headers/blob/3eca972b369608a7669b67cbe66679570a6505ce/flask_secure_headers/core.py#L99-L111
def wrapper(self, updateParams=None): """ create wrapper for flask app route """ def decorator(f): _headers = self._getHeaders(updateParams) """ flask decorator to include headers """ @wraps(f) def decorated_function(*args, **kwargs): resp = make_response(f(*args, **kwargs)) self._setRespHeader(...
[ "def", "wrapper", "(", "self", ",", "updateParams", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "_headers", "=", "self", ".", "_getHeaders", "(", "updateParams", ")", "\"\"\" flask decorator to include headers \"\"\"", "@", "wraps", "(", "f"...
create wrapper for flask app route
[ "create", "wrapper", "for", "flask", "app", "route" ]
python
train
MolSSI-BSE/basis_set_exchange
basis_set_exchange/cli/bsecurate_handlers.py
https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/cli/bsecurate_handlers.py#L78-L82
def _bsecurate_cli_view_graph(args): '''Handles the view-graph subcommand''' curate.view_graph(args.basis, args.version, args.data_dir) return ''
[ "def", "_bsecurate_cli_view_graph", "(", "args", ")", ":", "curate", ".", "view_graph", "(", "args", ".", "basis", ",", "args", ".", "version", ",", "args", ".", "data_dir", ")", "return", "''" ]
Handles the view-graph subcommand
[ "Handles", "the", "view", "-", "graph", "subcommand" ]
python
train
marcomusy/vtkplotter
vtkplotter/vtkio.py
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L635-L678
def convertNeutral2Xml(infile, outfile=None): """Convert Neutral file format to Dolfin XML.""" f = open(infile, "r") lines = f.readlines() f.close() ncoords = int(lines[0]) fdolf_coords = [] for i in range(1, ncoords + 1): x, y, z = lines[i].split() fdolf_coords.append([flo...
[ "def", "convertNeutral2Xml", "(", "infile", ",", "outfile", "=", "None", ")", ":", "f", "=", "open", "(", "infile", ",", "\"r\"", ")", "lines", "=", "f", ".", "readlines", "(", ")", "f", ".", "close", "(", ")", "ncoords", "=", "int", "(", "lines", ...
Convert Neutral file format to Dolfin XML.
[ "Convert", "Neutral", "file", "format", "to", "Dolfin", "XML", "." ]
python
train
limix/numpy-sugar
numpy_sugar/linalg/solve.py
https://github.com/limix/numpy-sugar/blob/4bdfa26913135c76ef3cd542a332f4e5861e948b/numpy_sugar/linalg/solve.py#L31-L98
def hsolve(A, y): r"""Solver for the linear equations of two variables and equations only. It uses Householder reductions to solve ``Ax = y`` in a robust manner. Parameters ---------- A : array_like Coefficient matrix. y : array_like Ordinate values. Returns ------- ...
[ "def", "hsolve", "(", "A", ",", "y", ")", ":", "n", "=", "_norm", "(", "A", "[", "0", ",", "0", "]", ",", "A", "[", "1", ",", "0", "]", ")", "u0", "=", "A", "[", "0", ",", "0", "]", "-", "n", "u1", "=", "A", "[", "1", ",", "0", "]...
r"""Solver for the linear equations of two variables and equations only. It uses Householder reductions to solve ``Ax = y`` in a robust manner. Parameters ---------- A : array_like Coefficient matrix. y : array_like Ordinate values. Returns ------- :class:`numpy.ndarra...
[ "r", "Solver", "for", "the", "linear", "equations", "of", "two", "variables", "and", "equations", "only", "." ]
python
train
apache/incubator-mxnet
example/ctc/lstm_ocr_infer.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm_ocr_infer.py#L65-L88
def main(): """Program entry point""" parser = argparse.ArgumentParser() parser.add_argument("path", help="Path to the CAPTCHA image file") parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr') parser.add_argument("--epoch", help="Checkpoint epoch [Default 100]", t...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"path\"", ",", "help", "=", "\"Path to the CAPTCHA image file\"", ")", "parser", ".", "add_argument", "(", "\"--prefix\"", ",", "hel...
Program entry point
[ "Program", "entry", "point" ]
python
train
mongodb/mongo-python-driver
pymongo/mongo_client.py
https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/mongo_client.py#L1941-L1989
def get_default_database(self, default=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None): """Get the database named in the MongoDB connection URI. >>> uri = 'mongodb://host/my_database' >>> client = MongoClient(uri) >>> db = client.get_de...
[ "def", "get_default_database", "(", "self", ",", "default", "=", "None", ",", "codec_options", "=", "None", ",", "read_preference", "=", "None", ",", "write_concern", "=", "None", ",", "read_concern", "=", "None", ")", ":", "if", "self", ".", "__default_data...
Get the database named in the MongoDB connection URI. >>> uri = 'mongodb://host/my_database' >>> client = MongoClient(uri) >>> db = client.get_default_database() >>> assert db.name == 'my_database' >>> db = client.get_database() >>> assert db.name == 'my_database' ...
[ "Get", "the", "database", "named", "in", "the", "MongoDB", "connection", "URI", "." ]
python
train
fermiPy/fermipy
fermipy/scripts/cluster_sources.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/scripts/cluster_sources.py#L157-L184
def make_rev_dict_unique(cdict): """ Make a reverse dictionary Parameters ---------- in_dict : dict(int:dict(int:True)) A dictionary of clusters. Each cluster is a source index and the dictionary of other sources in the cluster. Returns ------- rev_dict : dict(int:dict(i...
[ "def", "make_rev_dict_unique", "(", "cdict", ")", ":", "rev_dict", "=", "{", "}", "for", "k", ",", "v", "in", "cdict", ".", "items", "(", ")", ":", "if", "k", "in", "rev_dict", ":", "rev_dict", "[", "k", "]", "[", "k", "]", "=", "True", "else", ...
Make a reverse dictionary Parameters ---------- in_dict : dict(int:dict(int:True)) A dictionary of clusters. Each cluster is a source index and the dictionary of other sources in the cluster. Returns ------- rev_dict : dict(int:dict(int:True)) A dictionary pointin...
[ "Make", "a", "reverse", "dictionary" ]
python
train
TUT-ARG/sed_eval
sed_eval/sound_event.py
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/sound_event.py#L1705-L1741
def overall_error_rate(self): """Overall error rate metrics (error_rate, substitution_rate, deletion_rate, and insertion_rate) Returns ------- dict results in a dictionary format """ substitution_rate = metric.substitution_rate( Nref=self.overal...
[ "def", "overall_error_rate", "(", "self", ")", ":", "substitution_rate", "=", "metric", ".", "substitution_rate", "(", "Nref", "=", "self", ".", "overall", "[", "'Nref'", "]", ",", "Nsubstitutions", "=", "self", ".", "overall", "[", "'Nsubs'", "]", ")", "d...
Overall error rate metrics (error_rate, substitution_rate, deletion_rate, and insertion_rate) Returns ------- dict results in a dictionary format
[ "Overall", "error", "rate", "metrics", "(", "error_rate", "substitution_rate", "deletion_rate", "and", "insertion_rate", ")" ]
python
train
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L401-L468
async def remove(self, index=""): """ The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##' """ if not self.state == 'ready': logger.debug("Trying to remove from wrong state '{}'".format(self.sta...
[ "async", "def", "remove", "(", "self", ",", "index", "=", "\"\"", ")", ":", "if", "not", "self", ".", "state", "==", "'ready'", ":", "logger", ".", "debug", "(", "\"Trying to remove from wrong state '{}'\"", ".", "format", "(", "self", ".", "state", ")", ...
The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##'
[ "The", "remove", "command" ]
python
train
xeroc/python-graphenelib
graphenecommon/blockchain.py
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L224-L248
def stream(self, opNames=[], *args, **kwargs): """ Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the ch...
[ "def", "stream", "(", "self", ",", "opNames", "=", "[", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "op", "in", "self", ".", "ops", "(", "*", "*", "kwargs", ")", ":", "if", "not", "opNames", "or", "op", "[", "\"op\"", "]"...
Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the choice between * "head": the last block ...
[ "Yield", "specific", "operations", "(", "e", ".", "g", ".", "comments", ")", "only" ]
python
valid
docker/docker-py
docker/models/images.py
https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/models/images.py#L41-L48
def tags(self): """ The image's tags. """ tags = self.attrs.get('RepoTags') if tags is None: tags = [] return [tag for tag in tags if tag != '<none>:<none>']
[ "def", "tags", "(", "self", ")", ":", "tags", "=", "self", ".", "attrs", ".", "get", "(", "'RepoTags'", ")", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "return", "[", "tag", "for", "tag", "in", "tags", "if", "tag", "!=", "'<none>:<no...
The image's tags.
[ "The", "image", "s", "tags", "." ]
python
train
spantaleev/flask-sijax
flask_sijax.py
https://github.com/spantaleev/flask-sijax/blob/df9f6d9b8385b3375c119a51aa100491d5445e17/flask_sijax.py#L85-L97
def register_comet_callback(self, *args, **kwargs): """Registers a single Comet callback function (see :ref:`comet-plugin`). Refer to :func:`sijax.plugin.comet.register_comet_callback` for more details - its signature differs slightly. This method's signature is the same, excep...
[ "def", "register_comet_callback", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sijax", ".", "plugin", ".", "comet", ".", "register_comet_callback", "(", "self", ".", "_sijax", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Registers a single Comet callback function (see :ref:`comet-plugin`). Refer to :func:`sijax.plugin.comet.register_comet_callback` for more details - its signature differs slightly. This method's signature is the same, except that the first argument that :func:`sijax.plugin.come...
[ "Registers", "a", "single", "Comet", "callback", "function", "(", "see", ":", "ref", ":", "comet", "-", "plugin", ")", "." ]
python
train
hyperledger/indy-sdk
wrappers/python/indy/did.py
https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/did.py#L245-L275
async def get_key_metadata(wallet_handle: int, verkey: str) -> str: """ Retrieves the meta information for the giving key in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param verkey: The key (verkey, key id) to retrieve metadata. :return: me...
[ "async", "def", "get_key_metadata", "(", "wallet_handle", ":", "int", ",", "verkey", ":", "str", ")", "->", "str", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"get_key_metadata: >>> wallet_handle: %r, ver...
Retrieves the meta information for the giving key in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param verkey: The key (verkey, key id) to retrieve metadata. :return: metadata: The meta information stored with the key; Can be null if no metadata was saved for this key.
[ "Retrieves", "the", "meta", "information", "for", "the", "giving", "key", "in", "the", "wallet", "." ]
python
train
basho/riak-python-client
riak/transports/tcp/transport.py
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/transports/tcp/transport.py#L286-L299
def set_bucket_props(self, bucket, props): """ Serialize set bucket property request and deserialize response """ if not self.pb_all_bucket_props(): for key in props: if key not in ('n_val', 'allow_mult'): raise NotImplementedError('Server ...
[ "def", "set_bucket_props", "(", "self", ",", "bucket", ",", "props", ")", ":", "if", "not", "self", ".", "pb_all_bucket_props", "(", ")", ":", "for", "key", "in", "props", ":", "if", "key", "not", "in", "(", "'n_val'", ",", "'allow_mult'", ")", ":", ...
Serialize set bucket property request and deserialize response
[ "Serialize", "set", "bucket", "property", "request", "and", "deserialize", "response" ]
python
train
B2W-BIT/aiologger
aiologger/handlers/files.py
https://github.com/B2W-BIT/aiologger/blob/0b366597a8305d5577a267305e81d5e4784cd398/aiologger/handlers/files.py#L106-L120
async def emit(self, record: LogRecord): # type: ignore """ Emit a record. Output the record to the file, catering for rollover as described in `do_rollover`. """ try: if self.should_rollover(record): async with self._rollover_lock: ...
[ "async", "def", "emit", "(", "self", ",", "record", ":", "LogRecord", ")", ":", "# type: ignore", "try", ":", "if", "self", ".", "should_rollover", "(", "record", ")", ":", "async", "with", "self", ".", "_rollover_lock", ":", "if", "self", ".", "should_r...
Emit a record. Output the record to the file, catering for rollover as described in `do_rollover`.
[ "Emit", "a", "record", "." ]
python
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ml.py
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ml.py#L231-L255
def flush_job(self, job_id, body=None, params=None): """ `<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-flush-job.html>`_ :arg job_id: The name of the job to flush :arg body: Flush parameters :arg advance_time: Advances time to the given value generating res...
[ "def", "flush_job", "(", "self", ",", "job_id", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "if", "job_id", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'job_id'.\"", ")", "return", "sel...
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-flush-job.html>`_ :arg job_id: The name of the job to flush :arg body: Flush parameters :arg advance_time: Advances time to the given value generating results and updating the model for the advanced interval ...
[ "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ml", "-", "flush", "-", "job", ".", "html", ">", "_" ]
python
train
jorgenschaefer/elpy
elpy/server.py
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L210-L215
def rpc_fix_code(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code(source, directory)
[ "def", "rpc_fix_code", "(", "self", ",", "source", ",", "directory", ")", ":", "source", "=", "get_source", "(", "source", ")", "return", "fix_code", "(", "source", ",", "directory", ")" ]
Formats Python code to conform to the PEP 8 style guide.
[ "Formats", "Python", "code", "to", "conform", "to", "the", "PEP", "8", "style", "guide", "." ]
python
train
apple/turicreate
src/unity/python/turicreate/toolkits/distances/_util.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/distances/_util.py#L24-L126
def compute_composite_distance(distance, x, y): """ Compute the value of a composite distance function on two dictionaries, typically SFrame rows. Parameters ---------- distance : list[list] A composite distance function. Composite distance functions are a weighted sum of standa...
[ "def", "compute_composite_distance", "(", "distance", ",", "x", ",", "y", ")", ":", "## Validate inputs", "_validate_composite_distance", "(", "distance", ")", "distance", "=", "_convert_distance_names_to_functions", "(", "distance", ")", "if", "not", "isinstance", "(...
Compute the value of a composite distance function on two dictionaries, typically SFrame rows. Parameters ---------- distance : list[list] A composite distance function. Composite distance functions are a weighted sum of standard distance functions, each of which applies to its ...
[ "Compute", "the", "value", "of", "a", "composite", "distance", "function", "on", "two", "dictionaries", "typically", "SFrame", "rows", "." ]
python
train
PyMySQL/PyMySQL
pymysql/protocol.py
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L63-L75
def read(self, size): """Read the first 'size' bytes in packet and advance cursor past them.""" result = self._data[self._position:(self._position+size)] if len(result) != size: error = ('Result length not requested length:\n' 'Expected=%s. Actual=%s. Position:...
[ "def", "read", "(", "self", ",", "size", ")", ":", "result", "=", "self", ".", "_data", "[", "self", ".", "_position", ":", "(", "self", ".", "_position", "+", "size", ")", "]", "if", "len", "(", "result", ")", "!=", "size", ":", "error", "=", ...
Read the first 'size' bytes in packet and advance cursor past them.
[ "Read", "the", "first", "size", "bytes", "in", "packet", "and", "advance", "cursor", "past", "them", "." ]
python
train
AlecAivazis/graphql-over-kafka
nautilus/services/apiGateway.py
https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L210-L293
async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters): """ This function resolves a given object in the remote backend services """ try: # check if an object with that name has been registered registered = [model ...
[ "async", "def", "object_resolver", "(", "self", ",", "object_name", ",", "fields", ",", "obey_auth", "=", "False", ",", "current_user", "=", "None", ",", "*", "*", "filters", ")", ":", "try", ":", "# check if an object with that name has been registered", "registe...
This function resolves a given object in the remote backend services
[ "This", "function", "resolves", "a", "given", "object", "in", "the", "remote", "backend", "services" ]
python
train
SeabornGames/Table
seaborn_table/table.py
https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L1579-L1589
def _key_on_columns(key_on, columns): """ :param key_on: str of column :param columns: list of str of columns :return: list of str with the key_on in the front of the list """ if key_on is not None: if key_on in columns: columns.remove(key_on) ...
[ "def", "_key_on_columns", "(", "key_on", ",", "columns", ")", ":", "if", "key_on", "is", "not", "None", ":", "if", "key_on", "in", "columns", ":", "columns", ".", "remove", "(", "key_on", ")", "columns", "=", "[", "key_on", "]", "+", "columns", "return...
:param key_on: str of column :param columns: list of str of columns :return: list of str with the key_on in the front of the list
[ ":", "param", "key_on", ":", "str", "of", "column", ":", "param", "columns", ":", "list", "of", "str", "of", "columns", ":", "return", ":", "list", "of", "str", "with", "the", "key_on", "in", "the", "front", "of", "the", "list" ]
python
train
gem/oq-engine
openquake/hazardlib/gsim/campbell_bozorgnia_2014.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L243-L252
def _get_hanging_wall_coeffs_mag(self, C, mag): """ Returns the hanging wall magnitude term defined in equation 14 """ if mag < 5.5: return 0.0 elif mag > 6.5: return 1.0 + C["a2"] * (mag - 6.5) else: return (mag - 5.5) * (1.0 + C["a2"]...
[ "def", "_get_hanging_wall_coeffs_mag", "(", "self", ",", "C", ",", "mag", ")", ":", "if", "mag", "<", "5.5", ":", "return", "0.0", "elif", "mag", ">", "6.5", ":", "return", "1.0", "+", "C", "[", "\"a2\"", "]", "*", "(", "mag", "-", "6.5", ")", "e...
Returns the hanging wall magnitude term defined in equation 14
[ "Returns", "the", "hanging", "wall", "magnitude", "term", "defined", "in", "equation", "14" ]
python
train
arista-eosplus/pyeapi
pyeapi/api/vrrp.py
https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/vrrp.py#L462-L507
def set_primary_ip(self, name, vrid, value=None, disable=False, default=False, run=True): """Set the primary_ip property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. va...
[ "def", "set_primary_ip", "(", "self", ",", "name", ",", "vrid", ",", "value", "=", "None", ",", "disable", "=", "False", ",", "default", "=", "False", ",", "run", "=", "True", ")", ":", "if", "default", "is", "True", ":", "vrrps", "=", "self", ".",...
Set the primary_ip property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (string): IP address to be set. disable (boolean): Unset primary ip if True. default (boolean): ...
[ "Set", "the", "primary_ip", "property", "of", "the", "vrrp" ]
python
train
chrippa/python-librtmp
librtmp/stream.py
https://github.com/chrippa/python-librtmp/blob/6efefd5edd76cad7a3b53f7c87c1c7350448224d/librtmp/stream.py#L45-L67
def write(self, data): """Writes data to the stream. :param data: bytes, FLV data to write to the stream The data passed can contain multiple FLV tags, but it MUST always contain complete tags or undefined behaviour might occur. Raises :exc:`IOError` on error. ...
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "bytearray", ")", ":", "data", "=", "bytes", "(", "data", ")", "if", "not", "isinstance", "(", "data", ",", "byte_types", ")", ":", "raise", "ValueError", "(", ...
Writes data to the stream. :param data: bytes, FLV data to write to the stream The data passed can contain multiple FLV tags, but it MUST always contain complete tags or undefined behaviour might occur. Raises :exc:`IOError` on error.
[ "Writes", "data", "to", "the", "stream", "." ]
python
train
CZ-NIC/yangson
yangson/schemanode.py
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemanode.py#L1138-L1143
def _active_case(self, value: ObjectValue) -> Optional["CaseNode"]: """Return receiver's case that's active in an instance node value.""" for c in self.children: for cc in c.data_children(): if cc.iname() in value: return c
[ "def", "_active_case", "(", "self", ",", "value", ":", "ObjectValue", ")", "->", "Optional", "[", "\"CaseNode\"", "]", ":", "for", "c", "in", "self", ".", "children", ":", "for", "cc", "in", "c", ".", "data_children", "(", ")", ":", "if", "cc", ".", ...
Return receiver's case that's active in an instance node value.
[ "Return", "receiver", "s", "case", "that", "s", "active", "in", "an", "instance", "node", "value", "." ]
python
train
grigi/talkey
talkey/utils.py
https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L40-L63
def check_network_connection(server, port): ''' Checks if jasper can connect a network server. Arguments: server -- (optional) the server to connect with (Default: "www.google.com") Returns: True or False ''' logger = logging.getLogger(__name__) logger.debug...
[ "def", "check_network_connection", "(", "server", ",", "port", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"Checking network connection to server '%s'...\"", ",", "server", ")", "try", ":", "# see if w...
Checks if jasper can connect a network server. Arguments: server -- (optional) the server to connect with (Default: "www.google.com") Returns: True or False
[ "Checks", "if", "jasper", "can", "connect", "a", "network", "server", ".", "Arguments", ":", "server", "--", "(", "optional", ")", "the", "server", "to", "connect", "with", "(", "Default", ":", "www", ".", "google", ".", "com", ")", "Returns", ":", "Tr...
python
train
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L372-L380
def get_nodes(cluster): """Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes') """ gk = get_api_client() site = get_cluster_site(cluster) return gk.sites[site].clusters[cluster].nodes.list()
[ "def", "get_nodes", "(", "cluster", ")", ":", "gk", "=", "get_api_client", "(", ")", "site", "=", "get_cluster_site", "(", "cluster", ")", "return", "gk", ".", "sites", "[", "site", "]", ".", "clusters", "[", "cluster", "]", ".", "nodes", ".", "list", ...
Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes')
[ "Get", "all", "the", "nodes", "of", "a", "given", "cluster", "." ]
python
train
a1ezzz/wasp-general
wasp_general/task/registry.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/registry.py#L201-L211
def tasks_by_tag(self, registry_tag): """ Get tasks from registry by its tag :param registry_tag: any hash-able object :return: Return task (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is not True) or \ list of tasks """ if registry_tag not in self.__registry.keys(): return None tasks ...
[ "def", "tasks_by_tag", "(", "self", ",", "registry_tag", ")", ":", "if", "registry_tag", "not", "in", "self", ".", "__registry", ".", "keys", "(", ")", ":", "return", "None", "tasks", "=", "self", ".", "__registry", "[", "registry_tag", "]", "return", "t...
Get tasks from registry by its tag :param registry_tag: any hash-able object :return: Return task (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is not True) or \ list of tasks
[ "Get", "tasks", "from", "registry", "by", "its", "tag" ]
python
train
jmgilman/Neolib
neolib/pyamf/remoting/gateway/__init__.py
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/gateway/__init__.py#L451-L472
def authenticateRequest(self, service_request, username, password, **kwargs): """ Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will sto...
[ "def", "authenticateRequest", "(", "self", ",", "service_request", ",", "username", ",", "password", ",", "*", "*", "kwargs", ")", ":", "authenticator", "=", "self", ".", "getAuthenticator", "(", "service_request", ")", "if", "authenticator", "is", "None", ":"...
Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will stop processing the request and return an error to the client. @rtype: C{bool}
[ "Processes", "an", "authentication", "request", ".", "If", "no", "authenticator", "is", "supplied", "then", "authentication", "succeeds", "." ]
python
train
deepmind/pysc2
pysc2/lib/renderer_human.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L934-L941
def _abilities(self, fn=None): """Return the list of abilities filtered by `fn`.""" out = {} for cmd in self._obs.observation.abilities: ability = _Ability(cmd, self._static_data.abilities) if not fn or fn(ability): out[ability.ability_id] = ability return list(out.values())
[ "def", "_abilities", "(", "self", ",", "fn", "=", "None", ")", ":", "out", "=", "{", "}", "for", "cmd", "in", "self", ".", "_obs", ".", "observation", ".", "abilities", ":", "ability", "=", "_Ability", "(", "cmd", ",", "self", ".", "_static_data", ...
Return the list of abilities filtered by `fn`.
[ "Return", "the", "list", "of", "abilities", "filtered", "by", "fn", "." ]
python
train
etcher-be/epab
epab/utils/_repo.py
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L301-L341
def commit( self, message: str, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, allow_empty: bool = False, ): """ Commits changes to the repo :param message: first line of the message :type message: str ...
[ "def", "commit", "(", "self", ",", "message", ":", "str", ",", "files_to_add", ":", "typing", ".", "Optional", "[", "typing", ".", "Union", "[", "typing", ".", "List", "[", "str", "]", ",", "str", "]", "]", "=", "None", ",", "allow_empty", ":", "bo...
Commits changes to the repo :param message: first line of the message :type message: str :param files_to_add: files to commit :type files_to_add: optional list of str :param allow_empty: allow dummy commit :type allow_empty: bool
[ "Commits", "changes", "to", "the", "repo" ]
python
train
geopy/geopy
geopy/geocoders/arcgis.py
https://github.com/geopy/geopy/blob/02c838d965e76497f3c3d61f53808c86b5c58224/geopy/geocoders/arcgis.py#L308-L337
def _refresh_authentication_token(self): """ POST to ArcGIS requesting a new token. """ if self.retry == self._MAX_RETRIES: raise GeocoderAuthenticationFailure( 'Too many retries for auth: %s' % self.retry ) token_request_arguments = { ...
[ "def", "_refresh_authentication_token", "(", "self", ")", ":", "if", "self", ".", "retry", "==", "self", ".", "_MAX_RETRIES", ":", "raise", "GeocoderAuthenticationFailure", "(", "'Too many retries for auth: %s'", "%", "self", ".", "retry", ")", "token_request_argument...
POST to ArcGIS requesting a new token.
[ "POST", "to", "ArcGIS", "requesting", "a", "new", "token", "." ]
python
train
gwastro/pycbc
pycbc/tmpltbank/partitioned_bank.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L611-L640
def output_all_points(self): """Return all points in the bank. Return all points in the bank as lists of m1, m2, spin1z, spin2z. Returns ------- mass1 : list List of mass1 values. mass2 : list List of mass2 values. spin1z : list ...
[ "def", "output_all_points", "(", "self", ")", ":", "mass1", "=", "[", "]", "mass2", "=", "[", "]", "spin1z", "=", "[", "]", "spin2z", "=", "[", "]", "for", "i", "in", "self", ".", "massbank", ".", "keys", "(", ")", ":", "for", "j", "in", "self"...
Return all points in the bank. Return all points in the bank as lists of m1, m2, spin1z, spin2z. Returns ------- mass1 : list List of mass1 values. mass2 : list List of mass2 values. spin1z : list List of spin1z values. spin2z...
[ "Return", "all", "points", "in", "the", "bank", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py#L460-L473
def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") hide_ext_community_list_holder = ET.SubElement(...
[ "def", "ip_hide_ext_community_list_holder_extcommunity_list_ext_community_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\"", ",",...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
aiortc/aiortc
aiortc/rtcsctptransport.py
https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcsctptransport.py#L734-L744
def _set_extensions(self, params): """ Sets what extensions are supported by the local party. """ extensions = [] if self._local_partial_reliability: params.append((SCTP_PRSCTP_SUPPORTED, b'')) extensions.append(ForwardTsnChunk.type) extensions.ap...
[ "def", "_set_extensions", "(", "self", ",", "params", ")", ":", "extensions", "=", "[", "]", "if", "self", ".", "_local_partial_reliability", ":", "params", ".", "append", "(", "(", "SCTP_PRSCTP_SUPPORTED", ",", "b''", ")", ")", "extensions", ".", "append", ...
Sets what extensions are supported by the local party.
[ "Sets", "what", "extensions", "are", "supported", "by", "the", "local", "party", "." ]
python
train
EndurantDevs/webargs-sanic
webargs_sanic/sanicparser.py
https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/webargs_sanic/sanicparser.py#L74-L81
def parse_json(self, req, name, field): """Pull a json value from the request.""" if not (req.body and is_json_request(req)): return core.missing json_data = req.json if json_data is None: return core.missing return core.get_value(json_data, name, field, a...
[ "def", "parse_json", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "if", "not", "(", "req", ".", "body", "and", "is_json_request", "(", "req", ")", ")", ":", "return", "core", ".", "missing", "json_data", "=", "req", ".", "json", "i...
Pull a json value from the request.
[ "Pull", "a", "json", "value", "from", "the", "request", "." ]
python
train
ninuxorg/nodeshot
nodeshot/interop/sync/management/commands/sync.py
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/management/commands/sync.py#L76-L129
def handle(self, *args, **options): """ execute sync command """ # store verbosity level in instance attribute for later use self.verbosity = int(options.get('verbosity')) # blank line self.stdout.write('\r\n') # retrieve layers layers = self.retrieve_layers(*args...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# store verbosity level in instance attribute for later use", "self", ".", "verbosity", "=", "int", "(", "options", ".", "get", "(", "'verbosity'", ")", ")", "# blank line", "...
execute sync command
[ "execute", "sync", "command" ]
python
train
datacamp/pythonwhat
pythonwhat/sct_syntax.py
https://github.com/datacamp/pythonwhat/blob/ffbf7f8436a51f77c22f3bed75ba3bc37a5c666f/pythonwhat/sct_syntax.py#L13-L27
def multi_dec(f): """Decorator for multi to remove nodes for original test functions from root node""" @wraps(f) def wrapper(*args, **kwargs): args = ( args[0] if len(args) == 1 and isinstance(args[0], (list, tuple)) else args ) for arg in args: if isinstance...
[ "def", "multi_dec", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "(", "args", "[", "0", "]", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance"...
Decorator for multi to remove nodes for original test functions from root node
[ "Decorator", "for", "multi", "to", "remove", "nodes", "for", "original", "test", "functions", "from", "root", "node" ]
python
test
reiinakano/xcessiv
xcessiv/views.py
https://github.com/reiinakano/xcessiv/blob/a48dff7d370c84eb5c243bde87164c1f5fd096d5/xcessiv/views.py#L428-L476
def get_automated_runs(): """Return all automated runs""" path = functions.get_path_from_query_string(request) if request.method == 'GET': with functions.DBContextManager(path) as session: automated_runs = session.query(models.AutomatedRun).all() return jsonify(list(map(lamb...
[ "def", "get_automated_runs", "(", ")", ":", "path", "=", "functions", ".", "get_path_from_query_string", "(", "request", ")", "if", "request", ".", "method", "==", "'GET'", ":", "with", "functions", ".", "DBContextManager", "(", "path", ")", "as", "session", ...
Return all automated runs
[ "Return", "all", "automated", "runs" ]
python
train
user-cont/conu
conu/backend/docker/container.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/docker/container.py#L350-L363
def get_ports(self): """ get ports specified in container metadata :return: list of str """ ports = [] container_ports = self.inspect(refresh=True)["NetworkSettings"]["Ports"] if not container_ports: return ports for p in container_ports: ...
[ "def", "get_ports", "(", "self", ")", ":", "ports", "=", "[", "]", "container_ports", "=", "self", ".", "inspect", "(", "refresh", "=", "True", ")", "[", "\"NetworkSettings\"", "]", "[", "\"Ports\"", "]", "if", "not", "container_ports", ":", "return", "p...
get ports specified in container metadata :return: list of str
[ "get", "ports", "specified", "in", "container", "metadata" ]
python
train
Kronuz/pyScss
scss/cssdefs.py
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L208-L224
def convert_units_to_base_units(units): """Convert a set of units into a set of "base" units. Returns a 2-tuple of `factor, new_units`. """ total_factor = 1 new_units = [] for unit in units: if unit not in BASE_UNIT_CONVERSIONS: continue factor, new_unit = BASE_UNIT...
[ "def", "convert_units_to_base_units", "(", "units", ")", ":", "total_factor", "=", "1", "new_units", "=", "[", "]", "for", "unit", "in", "units", ":", "if", "unit", "not", "in", "BASE_UNIT_CONVERSIONS", ":", "continue", "factor", ",", "new_unit", "=", "BASE_...
Convert a set of units into a set of "base" units. Returns a 2-tuple of `factor, new_units`.
[ "Convert", "a", "set", "of", "units", "into", "a", "set", "of", "base", "units", "." ]
python
train
cqparts/cqparts
src/cqparts/utils/wrappers.py
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/wrappers.py#L2-L42
def as_part(func): """ Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) ...
[ "def", "as_part", "(", "func", ")", ":", "from", ".", ".", "import", "Part", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "part_class", "=", "type", "(", "func", ".", "__name__", ",", "(", "Part", ",", ")", ",", "{", "'m...
Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) ...
[ "Converts", "a", "function", "to", "a", ":", "class", ":", "Part", "<cqparts", ".", "Part", ">", "instance", "." ]
python
train
mlperf/training
compliance/mlperf_compliance/tf_mlperf_log.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/mlperf_compliance/tf_mlperf_log.py#L33-L62
def log_deferred(op, log_id, every_n=1, first_n=None): """Helper method inserting compliance logging ops. Note: This helper is not guaranteed to be efficient, as it will insert ops and control dependencies. If this proves to be a bottleneck, submitters may wish to consider other methods such as ext...
[ "def", "log_deferred", "(", "op", ",", "log_id", ",", "every_n", "=", "1", ",", "first_n", "=", "None", ")", ":", "prefix", "=", "\":::MLPv0.5.0 [{}]\"", ".", "format", "(", "log_id", ")", "if", "not", "first_n", "is", "not", "None", "and", "first_n", ...
Helper method inserting compliance logging ops. Note: This helper is not guaranteed to be efficient, as it will insert ops and control dependencies. If this proves to be a bottleneck, submitters may wish to consider other methods such as extracting values from an .events file. Args: op...
[ "Helper", "method", "inserting", "compliance", "logging", "ops", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xchartwidget/xchartruler.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartruler.py#L355-L419
def percentAt( self, value ): """ Returns the percentage where the given value lies between this rulers minimum and maximum values. If the value equals the minimum, then the percent is 0, if it equals the maximum, then the percent is 1 - any value between will be a floating...
[ "def", "percentAt", "(", "self", ",", "value", ")", ":", "if", "(", "value", "is", "None", ")", ":", "return", "0.0", "minim", "=", "self", ".", "minimum", "(", ")", "maxim", "=", "self", ".", "maximum", "(", ")", "rtype", "=", "self", ".", "rule...
Returns the percentage where the given value lies between this rulers minimum and maximum values. If the value equals the minimum, then the percent is 0, if it equals the maximum, then the percent is 1 - any value between will be a floating point. If the ruler is a custom type, the...
[ "Returns", "the", "percentage", "where", "the", "given", "value", "lies", "between", "this", "rulers", "minimum", "and", "maximum", "values", ".", "If", "the", "value", "equals", "the", "minimum", "then", "the", "percent", "is", "0", "if", "it", "equals", ...
python
train
godaddy/gdapi-python
gdapi.py
https://github.com/godaddy/gdapi-python/blob/79d7784df9d9aae92c1c808c3e4936970ad72abf/gdapi.py#L544-L586
def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left', separateRows=False, prefix='', postfix='', wrapfunc=lambda x: x): '''Indents a table by column. - rows: A sequence of sequences of items, one sequence per row. - hasHeader: True if the first row c...
[ "def", "indent", "(", "rows", ",", "hasHeader", "=", "False", ",", "headerChar", "=", "'-'", ",", "delim", "=", "' | '", ",", "justify", "=", "'left'", ",", "separateRows", "=", "False", ",", "prefix", "=", "''", ",", "postfix", "=", "''", ",", "wrap...
Indents a table by column. - rows: A sequence of sequences of items, one sequence per row. - hasHeader: True if the first row consists of the columns' names. - headerChar: Character to be used for the row separator line (if hasHeader==True or separateRows==True). ...
[ "Indents", "a", "table", "by", "column", ".", "-", "rows", ":", "A", "sequence", "of", "sequences", "of", "items", "one", "sequence", "per", "row", ".", "-", "hasHeader", ":", "True", "if", "the", "first", "row", "consists", "of", "the", "columns", "na...
python
train
tanghaibao/jcvi
jcvi/assembly/gaps.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/gaps.py#L284-L330
def flanks(args): """ %prog flanks gaps.bed fastafile Create sequences flanking the gaps. """ p = OptionParser(flanks.__doc__) p.add_option("--extend", default=2000, type="int", help="Extend seq flanking the gaps [default: %default]") opts, args = p.parse_args(args) if...
[ "def", "flanks", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "flanks", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--extend\"", ",", "default", "=", "2000", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Extend seq flanking the gaps [...
%prog flanks gaps.bed fastafile Create sequences flanking the gaps.
[ "%prog", "flanks", "gaps", ".", "bed", "fastafile" ]
python
train
mbedmicro/pyOCD
pyocd/flash/flash.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/flash/flash.py#L340-L353
def erase_sector(self, address): """! @brief Erase one sector. @exception FlashEraseFailure """ assert self._active_operation == self.Operation.ERASE # update core register to execute the erase_sector subroutine result = self._call_function_and_wait(self...
[ "def", "erase_sector", "(", "self", ",", "address", ")", ":", "assert", "self", ".", "_active_operation", "==", "self", ".", "Operation", ".", "ERASE", "# update core register to execute the erase_sector subroutine", "result", "=", "self", ".", "_call_function_and_wait"...
! @brief Erase one sector. @exception FlashEraseFailure
[ "!" ]
python
train
xeroc/python-graphenelib
graphenecommon/account.py
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L101-L110
def balances(self): """ List balances of an account. This call returns instances of :class:`amount.Amount`. """ balances = self.blockchain.rpc.get_account_balances(self["id"], []) return [ self.amount_class(b, blockchain_instance=self.blockchain) for b...
[ "def", "balances", "(", "self", ")", ":", "balances", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_account_balances", "(", "self", "[", "\"id\"", "]", ",", "[", "]", ")", "return", "[", "self", ".", "amount_class", "(", "b", ",", "blockchain_i...
List balances of an account. This call returns instances of :class:`amount.Amount`.
[ "List", "balances", "of", "an", "account", ".", "This", "call", "returns", "instances", "of", ":", "class", ":", "amount", ".", "Amount", "." ]
python
valid
hyperledger/indy-sdk
wrappers/python/indy/wallet.py
https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/wallet.py#L9-L63
async def create_wallet(config: str, credentials: str) -> None: """ Creates a new secure wallet with the given unique name. :param config: Wallet configuration json. { "id": string, Identifier of the wallet. Configured storage uses this identifier to lookup ...
[ "async", "def", "create_wallet", "(", "config", ":", "str", ",", "credentials", ":", "str", ")", "->", "None", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"create_wallet: >>> config: %r, credentials: %r\"...
Creates a new secure wallet with the given unique name. :param config: Wallet configuration json. { "id": string, Identifier of the wallet. Configured storage uses this identifier to lookup exact wallet data placement. "storage_type": optional<string>, Type of the wallet storage. De...
[ "Creates", "a", "new", "secure", "wallet", "with", "the", "given", "unique", "name", "." ]
python
train
DataONEorg/d1_python
lib_common/src/d1_common/multipart.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/multipart.py#L44-L68
def parse_str(mmp_bytes, content_type, encoding='utf-8'): """Parse multipart document bytes into a tuple of BodyPart objects. Args: mmp_bytes: bytes Multipart document. content_type : str Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where ``<BOUNDARY>`...
[ "def", "parse_str", "(", "mmp_bytes", ",", "content_type", ",", "encoding", "=", "'utf-8'", ")", ":", "return", "requests_toolbelt", ".", "multipart", ".", "decoder", ".", "MultipartDecoder", "(", "mmp_bytes", ",", "content_type", ",", "encoding", ")", ".", "p...
Parse multipart document bytes into a tuple of BodyPart objects. Args: mmp_bytes: bytes Multipart document. content_type : str Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where ``<BOUNDARY>`` is the string that separates the parts of the multipart documen...
[ "Parse", "multipart", "document", "bytes", "into", "a", "tuple", "of", "BodyPart", "objects", "." ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/module.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1999-L2016
def _notify_unload_dll(self, event): """ Notify the release of a loaded module. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{UnloadDLLEvent} @param event: Unload DLL event. @rtype: bool @retu...
[ "def", "_notify_unload_dll", "(", "self", ",", "event", ")", ":", "lpBaseOfDll", "=", "event", ".", "get_module_base", "(", ")", "## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan", "if", "lpBaseOfDll", "in", "self", ".", "__moduleDict", ":", "...
Notify the release of a loaded module. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{UnloadDLLEvent} @param event: Unload DLL event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} oth...
[ "Notify", "the", "release", "of", "a", "loaded", "module", "." ]
python
train
havardgulldahl/jottalib
src/jottalib/JFS.py
https://github.com/havardgulldahl/jottalib/blob/4d015e4309b1d9055e561ec757363fb2632b4eb7/src/jottalib/JFS.py#L92-L105
def calculate_md5(fileobject, size=2**16): """Utility function to calculate md5 hashes while being light on memory usage. By reading the fileobject piece by piece, we are able to process content that is larger than available memory""" fileobject.seek(0) md5 = hashlib.md5() for data in iter(lamb...
[ "def", "calculate_md5", "(", "fileobject", ",", "size", "=", "2", "**", "16", ")", ":", "fileobject", ".", "seek", "(", "0", ")", "md5", "=", "hashlib", ".", "md5", "(", ")", "for", "data", "in", "iter", "(", "lambda", ":", "fileobject", ".", "read...
Utility function to calculate md5 hashes while being light on memory usage. By reading the fileobject piece by piece, we are able to process content that is larger than available memory
[ "Utility", "function", "to", "calculate", "md5", "hashes", "while", "being", "light", "on", "memory", "usage", "." ]
python
train
streamlink/streamlink
src/streamlink_cli/utils/progress.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink_cli/utils/progress.py#L83-L97
def format_time(elapsed): """Formats elapsed seconds into a human readable format.""" hours = int(elapsed / (60 * 60)) minutes = int((elapsed % (60 * 60)) / 60) seconds = int(elapsed % 60) rval = "" if hours: rval += "{0}h".format(hours) if elapsed > 60: rval += "{0}m".form...
[ "def", "format_time", "(", "elapsed", ")", ":", "hours", "=", "int", "(", "elapsed", "/", "(", "60", "*", "60", ")", ")", "minutes", "=", "int", "(", "(", "elapsed", "%", "(", "60", "*", "60", ")", ")", "/", "60", ")", "seconds", "=", "int", ...
Formats elapsed seconds into a human readable format.
[ "Formats", "elapsed", "seconds", "into", "a", "human", "readable", "format", "." ]
python
test
globus/globus-cli
globus_cli/commands/endpoint/my_shared_endpoint_list.py
https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/endpoint/my_shared_endpoint_list.py#L14-L21
def my_shared_endpoint_list(endpoint_id): """ Executor for `globus endpoint my-shared-endpoint-list` """ client = get_client() ep_iterator = client.my_shared_endpoint_list(endpoint_id) formatted_print(ep_iterator, fields=ENDPOINT_LIST_FIELDS)
[ "def", "my_shared_endpoint_list", "(", "endpoint_id", ")", ":", "client", "=", "get_client", "(", ")", "ep_iterator", "=", "client", ".", "my_shared_endpoint_list", "(", "endpoint_id", ")", "formatted_print", "(", "ep_iterator", ",", "fields", "=", "ENDPOINT_LIST_FI...
Executor for `globus endpoint my-shared-endpoint-list`
[ "Executor", "for", "globus", "endpoint", "my", "-", "shared", "-", "endpoint", "-", "list" ]
python
train
raiden-network/raiden-contracts
raiden_contracts/utils/transaction.py
https://github.com/raiden-network/raiden-contracts/blob/a7e72a9477f2204b03f3706360ea8d9c0a8e7063/raiden_contracts/utils/transaction.py#L7-L22
def check_successful_tx(web3: Web3, txid: str, timeout=180) -> Tuple[dict, dict]: """See if transaction went through (Solidity code did not throw). :return: Transaction receipt and transaction info """ receipt = wait_for_transaction_receipt(web3=web3, txid=txid, timeout=timeout) txinfo = web3.eth.ge...
[ "def", "check_successful_tx", "(", "web3", ":", "Web3", ",", "txid", ":", "str", ",", "timeout", "=", "180", ")", "->", "Tuple", "[", "dict", ",", "dict", "]", ":", "receipt", "=", "wait_for_transaction_receipt", "(", "web3", "=", "web3", ",", "txid", ...
See if transaction went through (Solidity code did not throw). :return: Transaction receipt and transaction info
[ "See", "if", "transaction", "went", "through", "(", "Solidity", "code", "did", "not", "throw", ")", ".", ":", "return", ":", "Transaction", "receipt", "and", "transaction", "info" ]
python
train
bwohlberg/sporco
docs/source/docntbk.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L253-L304
def rst_to_docs_rst(infile, outfile): """Convert an rst file to a sphinx docs rst file.""" # Read infile into a list of lines with open(infile, 'r') as fin: rst = fin.readlines() # Inspect outfile path components to determine whether outfile # is in the root of the examples directory or in...
[ "def", "rst_to_docs_rst", "(", "infile", ",", "outfile", ")", ":", "# Read infile into a list of lines", "with", "open", "(", "infile", ",", "'r'", ")", "as", "fin", ":", "rst", "=", "fin", ".", "readlines", "(", ")", "# Inspect outfile path components to determin...
Convert an rst file to a sphinx docs rst file.
[ "Convert", "an", "rst", "file", "to", "a", "sphinx", "docs", "rst", "file", "." ]
python
train
sdispater/pendulum
pendulum/datetime.py
https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/datetime.py#L779-L793
def diff(self, dt=None, abs=True): """ Returns the difference between two DateTime objects represented as a Duration. :type dt: DateTime or None :param abs: Whether to return an absolute interval or not :type abs: bool :rtype: Period """ if dt is None: ...
[ "def", "diff", "(", "self", ",", "dt", "=", "None", ",", "abs", "=", "True", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "self", ".", "now", "(", "self", ".", "tz", ")", "return", "Period", "(", "self", ",", "dt", ",", "absolute", "="...
Returns the difference between two DateTime objects represented as a Duration. :type dt: DateTime or None :param abs: Whether to return an absolute interval or not :type abs: bool :rtype: Period
[ "Returns", "the", "difference", "between", "two", "DateTime", "objects", "represented", "as", "a", "Duration", "." ]
python
train
eventbrite/conformity
conformity/fields/structures.py
https://github.com/eventbrite/conformity/blob/12014fe4e14f66869ffda9f9ca09cd20a985c769/conformity/fields/structures.py#L170-L205
def extend( self, contents=None, optional_keys=None, allow_extra_keys=None, description=None, replace_optional_keys=False, ): """ This method allows you to create a new `Dictionary` that extends the current `Dictionary` with additional contents...
[ "def", "extend", "(", "self", ",", "contents", "=", "None", ",", "optional_keys", "=", "None", ",", "allow_extra_keys", "=", "None", ",", "description", "=", "None", ",", "replace_optional_keys", "=", "False", ",", ")", ":", "optional_keys", "=", "set", "(...
This method allows you to create a new `Dictionary` that extends the current `Dictionary` with additional contents and/or optional keys, and/or replaces the `allow_extra_keys` and/or `description` attributes. :param contents: More contents, if any, to extend the current contents :type contents:...
[ "This", "method", "allows", "you", "to", "create", "a", "new", "Dictionary", "that", "extends", "the", "current", "Dictionary", "with", "additional", "contents", "and", "/", "or", "optional", "keys", "and", "/", "or", "replaces", "the", "allow_extra_keys", "an...
python
train
buildbot/buildbot
master/buildbot/changes/mail.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/changes/mail.py#L96-L263
def parse(self, m, prefix=None): """Parse messages sent by the 'buildbot-cvs-mail' program. """ # The mail is sent from the person doing the checkin. Assume that the # local username is enough to identify them (this assumes a one-server # cvs-over-rsh environment rather than the ...
[ "def", "parse", "(", "self", ",", "m", ",", "prefix", "=", "None", ")", ":", "# The mail is sent from the person doing the checkin. Assume that the", "# local username is enough to identify them (this assumes a one-server", "# cvs-over-rsh environment rather than the server-dirs-shared-o...
Parse messages sent by the 'buildbot-cvs-mail' program.
[ "Parse", "messages", "sent", "by", "the", "buildbot", "-", "cvs", "-", "mail", "program", "." ]
python
train
CalebBell/thermo
thermo/heat_capacity.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L662-L711
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which t...
[ "def", "load_all_methods", "(", "self", ")", ":", "methods", "=", "[", "]", "Tmins", ",", "Tmaxs", "=", "[", "]", ",", "[", "]", "if", "self", ".", "CASRN", "in", "TRC_gas_data", ".", "index", ":", "methods", ".", "append", "(", "TRCIG", ")", "_", ...
r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which the data exists for. Called ...
[ "r", "Method", "which", "picks", "out", "coefficients", "for", "the", "specified", "chemical", "from", "the", "various", "dictionaries", "and", "DataFrames", "storing", "it", ".", "All", "data", "is", "stored", "as", "attributes", ".", "This", "method", "also"...
python
valid
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Dir.py#L32-L37
def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw)
[ "def", "DirScanner", "(", "*", "*", "kw", ")", ":", "kw", "[", "'node_factory'", "]", "=", "SCons", ".", "Node", ".", "FS", ".", "Entry", "kw", "[", "'recursive'", "]", "=", "only_dirs", "return", "SCons", ".", "Scanner", ".", "Base", "(", "scan_on_d...
Return a prototype Scanner instance for scanning directories for on-disk files
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "directories", "for", "on", "-", "disk", "files" ]
python
train
autokey/autokey
lib/autokey/scripting.py
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L349-L382
def list_menu_multi(self, options, title="Choose one or more values", message="Choose one or more values", defaults: list=None, **kwargs): """ Show a multiple-selection list menu Usage: C{dialog.list_menu_multi(options, title="Choose one or more values", message=...
[ "def", "list_menu_multi", "(", "self", ",", "options", ",", "title", "=", "\"Choose one or more values\"", ",", "message", "=", "\"Choose one or more values\"", ",", "defaults", ":", "list", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "defaults", "is...
Show a multiple-selection list menu Usage: C{dialog.list_menu_multi(options, title="Choose one or more values", message="Choose one or more values", defaults=[], **kwargs)} @param options: list of options (strings) for the dialog @param title: window title for the dialog ...
[ "Show", "a", "multiple", "-", "selection", "list", "menu", "Usage", ":", "C", "{", "dialog", ".", "list_menu_multi", "(", "options", "title", "=", "Choose", "one", "or", "more", "values", "message", "=", "Choose", "one", "or", "more", "values", "defaults",...
python
train
Accelize/pycosio
pycosio/storage/azure.py
https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L48-L68
def _properties_model_to_dict(properties): """ Convert properties model to dict. Args: properties: Properties model. Returns: dict: Converted model. """ result = {} for attr in properties.__dict__: value = getattr(properties, attr) if hasattr(value, '__modu...
[ "def", "_properties_model_to_dict", "(", "properties", ")", ":", "result", "=", "{", "}", "for", "attr", "in", "properties", ".", "__dict__", ":", "value", "=", "getattr", "(", "properties", ",", "attr", ")", "if", "hasattr", "(", "value", ",", "'__module_...
Convert properties model to dict. Args: properties: Properties model. Returns: dict: Converted model.
[ "Convert", "properties", "model", "to", "dict", "." ]
python
train
limodou/uliweb
uliweb/contrib/auth/__init__.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/auth/__init__.py#L90-L125
def set_user_session(user): """ Set user session :param user: user object chould be model instance or dict :return: """ from uliweb import settings, request user_fieldname = settings.get_var('AUTH/GET_AUTH_USER_FIELDNAME', 'id') share_session = settings.get_var('AUTH/AUTH_SHARE...
[ "def", "set_user_session", "(", "user", ")", ":", "from", "uliweb", "import", "settings", ",", "request", "user_fieldname", "=", "settings", ".", "get_var", "(", "'AUTH/GET_AUTH_USER_FIELDNAME'", ",", "'id'", ")", "share_session", "=", "settings", ".", "get_var", ...
Set user session :param user: user object chould be model instance or dict :return:
[ "Set", "user", "session", ":", "param", "user", ":", "user", "object", "chould", "be", "model", "instance", "or", "dict", ":", "return", ":" ]
python
train
Erotemic/ubelt
ubelt/util_str.py
https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_str.py#L148-L169
def ensure_unicode(text): r""" Casts bytes into utf8 (mostly for python2 compatibility) References: http://stackoverflow.com/questions/12561063/extract-data-from-file Example: >>> from ubelt.util_str import * >>> import codecs # NOQA >>> assert ensure_unicode('my ünicô...
[ "def", "ensure_unicode", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "six", ".", "text_type", ")", ":", "return", "text", "elif", "isinstance", "(", "text", ",", "six", ".", "binary_type", ")", ":", "return", "text", ".", "decode", "("...
r""" Casts bytes into utf8 (mostly for python2 compatibility) References: http://stackoverflow.com/questions/12561063/extract-data-from-file Example: >>> from ubelt.util_str import * >>> import codecs # NOQA >>> assert ensure_unicode('my ünicôdé strįng') == 'my ünicôdé str...
[ "r", "Casts", "bytes", "into", "utf8", "(", "mostly", "for", "python2", "compatibility", ")" ]
python
valid
knipknap/SpiffWorkflow
SpiffWorkflow/bpmn/parser/ProcessParser.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/ProcessParser.py#L118-L129
def get_spec(self): """ Parse this process (if it has not already been parsed), and return the workflow spec. """ if self.is_parsed: return self.spec if self.parsing_started: raise NotImplementedError( 'Recursive call Activities are...
[ "def", "get_spec", "(", "self", ")", ":", "if", "self", ".", "is_parsed", ":", "return", "self", ".", "spec", "if", "self", ".", "parsing_started", ":", "raise", "NotImplementedError", "(", "'Recursive call Activities are not supported.'", ")", "self", ".", "_pa...
Parse this process (if it has not already been parsed), and return the workflow spec.
[ "Parse", "this", "process", "(", "if", "it", "has", "not", "already", "been", "parsed", ")", "and", "return", "the", "workflow", "spec", "." ]
python
valid
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L450-L464
def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'...
[ "def", "vocab_account_type", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'user-account'", ":", "try", ...
Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary.
[ "Ensure", "a", "user", "-", "account", "objects", "account", "-", "type", "property", "is", "from", "the", "account", "-", "type", "-", "ov", "vocabulary", "." ]
python
train
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/update_service/apis/default_api.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/update_service/apis/default_api.py#L1563-L1583
def update_campaign_retrieve(self, campaign_id, **kwargs): # noqa: E501 """Get a campaign. # noqa: E501 Get an update campaign. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread...
[ "def", "update_campaign_retrieve", "(", "self", ",", "campaign_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ...
Get a campaign. # noqa: E501 Get an update campaign. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.update_campaign_retrieve(campaign_id, asynchronous=True) >>> result =...
[ "Get", "a", "campaign", ".", "#", "noqa", ":", "E501" ]
python
train