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
swistakm/graceful
src/graceful/authentication.py
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L490-L495
def identify(self, req, resp, resource, uri_kwargs): """Initialize X-Api-Key authentication middleware.""" try: return req.get_header('X-Api-Key', True) except (KeyError, HTTPMissingHeader): pass
[ "def", "identify", "(", "self", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "try", ":", "return", "req", ".", "get_header", "(", "'X-Api-Key'", ",", "True", ")", "except", "(", "KeyError", ",", "HTTPMissingHeader", ")", ":", ...
Initialize X-Api-Key authentication middleware.
[ "Initialize", "X", "-", "Api", "-", "Key", "authentication", "middleware", "." ]
python
train
Azure/blobxfer
blobxfer/models/metadata.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/metadata.py#L143-L176
def fileattr_from_metadata(md): # type: (dict) -> collections.namedtuple """Convert fileattr metadata in json metadata :param dict md: metadata dictionary :rtype: PosixFileAttr or WindowsFileAttr or None :return: fileattr metadata """ try: mdattr = json.loads( md[JSON_KEY...
[ "def", "fileattr_from_metadata", "(", "md", ")", ":", "# type: (dict) -> collections.namedtuple", "try", ":", "mdattr", "=", "json", ".", "loads", "(", "md", "[", "JSON_KEY_BLOBXFER_METADATA", "]", ")", "[", "_JSON_KEY_FILE_ATTRIBUTES", "]", "except", "(", "KeyError...
Convert fileattr metadata in json metadata :param dict md: metadata dictionary :rtype: PosixFileAttr or WindowsFileAttr or None :return: fileattr metadata
[ "Convert", "fileattr", "metadata", "in", "json", "metadata", ":", "param", "dict", "md", ":", "metadata", "dictionary", ":", "rtype", ":", "PosixFileAttr", "or", "WindowsFileAttr", "or", "None", ":", "return", ":", "fileattr", "metadata" ]
python
train
BerkeleyAutomation/perception
perception/detector.py
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/detector.py#L149-L217
def detect(self, color_im, depth_im, cfg, camera_intr=None, T_camera_world=None, segmask=None): """ Detects all relevant objects in an rgbd image pair using foreground masking. Parameters ---------- color_im : :obj:`ColorImage` color image for detectio...
[ "def", "detect", "(", "self", ",", "color_im", ",", "depth_im", ",", "cfg", ",", "camera_intr", "=", "None", ",", "T_camera_world", "=", "None", ",", "segmask", "=", "None", ")", ":", "# read params", "foreground_mask_tolerance", "=", "cfg", "[", "'foregroun...
Detects all relevant objects in an rgbd image pair using foreground masking. Parameters ---------- color_im : :obj:`ColorImage` color image for detection depth_im : :obj:`DepthImage` depth image for detection (corresponds to color image) cfg : :obj:`YamlC...
[ "Detects", "all", "relevant", "objects", "in", "an", "rgbd", "image", "pair", "using", "foreground", "masking", "." ]
python
train
fhs/pyhdf
pyhdf/V.py
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L851-L872
def getid(self, ref): """Obtain the reference number of the vgroup following the vgroup with the given reference number . Args:: ref reference number of the vgroup after which to search; set to -1 to start the search at the start of the HDF file ...
[ "def", "getid", "(", "self", ",", "ref", ")", ":", "num", "=", "_C", ".", "Vgetid", "(", "self", ".", "_hdf_inst", ".", "_id", ",", "ref", ")", "_checkErr", "(", "'getid'", ",", "num", ",", "\"bad arguments or last vgroup reached\"", ")", "return", "num"...
Obtain the reference number of the vgroup following the vgroup with the given reference number . Args:: ref reference number of the vgroup after which to search; set to -1 to start the search at the start of the HDF file Returns:: refe...
[ "Obtain", "the", "reference", "number", "of", "the", "vgroup", "following", "the", "vgroup", "with", "the", "given", "reference", "number", "." ]
python
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L302-L319
def remove_instance(self, instance): """Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None """ # External instances need to be close before (proce...
[ "def", "remove_instance", "(", "self", ",", "instance", ")", ":", "# External instances need to be close before (process + queues)", "if", "instance", ".", "is_external", ":", "logger", ".", "info", "(", "\"Request external process to stop for %s\"", ",", "instance", ".", ...
Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None
[ "Request", "to", "cleanly", "remove", "the", "given", "instance", ".", "If", "instance", "is", "external", "also", "shutdown", "it", "cleanly" ]
python
train
xtuml/pyxtuml
bridgepoint/oal.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1060-L1063
def t_TIMES(self, t): r"\*" t.endlexpos = t.lexpos + len(t.value) return t
[ "def", "t_TIMES", "(", "self", ",", "t", ")", ":", "t", ".", "endlexpos", "=", "t", ".", "lexpos", "+", "len", "(", "t", ".", "value", ")", "return", "t" ]
r"\*
[ "r", "\\", "*" ]
python
test
fracpete/python-weka-wrapper3
python/weka/experiments.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L500-L509
def set_col_name(self, index, name): """ Sets the column name. :param index: the 0-based row index :type index: int :param name: the name of the column :type name: str """ javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", index, name)
[ "def", "set_col_name", "(", "self", ",", "index", ",", "name", ")", ":", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"setColName\"", ",", "\"(ILjava/lang/String;)V\"", ",", "index", ",", "name", ")" ]
Sets the column name. :param index: the 0-based row index :type index: int :param name: the name of the column :type name: str
[ "Sets", "the", "column", "name", "." ]
python
train
deginner/mq-client
mq_client.py
https://github.com/deginner/mq-client/blob/a20ab50ea18870c01e8d142b049233c355858872/mq_client.py#L150-L156
def add_on_connection_close_callback(self): """ Add an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ self._logger.debug('Adding connection close callback') self._connection.add_on_close_callback(self....
[ "def", "add_on_connection_close_callback", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Adding connection close callback'", ")", "self", ".", "_connection", ".", "add_on_close_callback", "(", "self", ".", "on_connection_closed", ")" ]
Add an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly.
[ "Add", "an", "on", "close", "callback", "that", "will", "be", "invoked", "by", "pika", "when", "RabbitMQ", "closes", "the", "connection", "to", "the", "publisher", "unexpectedly", "." ]
python
train
edx/edx-val
edxval/utils.py
https://github.com/edx/edx-val/blob/30df48061e77641edb5272895b7c7f7f25eb7aa7/edxval/utils.py#L203-L218
def get_transcript_format(transcript_content): """ Returns transcript format. Arguments: transcript_content (str): Transcript file content. """ try: sjson_obj = json.loads(transcript_content) except ValueError: # With error handling (set to 'ERROR_RAISE'), we will be get...
[ "def", "get_transcript_format", "(", "transcript_content", ")", ":", "try", ":", "sjson_obj", "=", "json", ".", "loads", "(", "transcript_content", ")", "except", "ValueError", ":", "# With error handling (set to 'ERROR_RAISE'), we will be getting", "# the exception if someth...
Returns transcript format. Arguments: transcript_content (str): Transcript file content.
[ "Returns", "transcript", "format", "." ]
python
train
codelv/enaml-web
web/impl/lxml_raw.py
https://github.com/codelv/enaml-web/blob/88f1131a7b3ba9e83467b4f44bc3bab6f0de7559/web/impl/lxml_raw.py#L21-L27
def init_widget(self): """ Initialize the widget with the source. """ d = self.declaration if d.source: self.set_source(d.source) else: super(RawComponent, self).init_widget()
[ "def", "init_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "source", ":", "self", ".", "set_source", "(", "d", ".", "source", ")", "else", ":", "super", "(", "RawComponent", ",", "self", ")", ".", "init_widget"...
Initialize the widget with the source.
[ "Initialize", "the", "widget", "with", "the", "source", "." ]
python
test
tumblr/pytumblr
pytumblr/__init__.py
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L351-L369
def create_link(self, blogname, **kwargs): """ Create a link post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a st...
[ "def", "create_link", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"type\"", ":", "\"link\"", "}", ")", "return", "self", ".", "_send_post", "(", "blogname", ",", "kwargs", ")" ]
Create a link post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a...
[ "Create", "a", "link", "post", "on", "a", "blog" ]
python
train
rodynnz/xccdf
src/xccdf/models/html_element.py
https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/html_element.py#L116-L133
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) ...
[ "def", "update_xml_element", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'xml_element'", ")", ":", "self", ".", "xml_element", "=", "etree", ".", "Element", "(", "self", ".", "name", ",", "nsmap", "=", "NSMAP", ")", "for", "elemen...
Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element
[ "Updates", "the", "xml", "element", "contents", "to", "matches", "the", "instance", "contents", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L9035-L9053
def raw_imu_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should always contain the true raw values without any scaling to allow data capture and sys...
[ "def", "raw_imu_encode", "(", "self", ",", "time_usec", ",", "xacc", ",", "yacc", ",", "zacc", ",", "xgyro", ",", "ygyro", ",", "zgyro", ",", "xmag", ",", "ymag", ",", "zmag", ")", ":", "return", "MAVLink_raw_imu_message", "(", "time_usec", ",", "xacc", ...
The RAW IMU readings for the usual 9DOF sensor setup. This message should always contain the true raw values without any scaling to allow data capture and system debugging. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system ...
[ "The", "RAW", "IMU", "readings", "for", "the", "usual", "9DOF", "sensor", "setup", ".", "This", "message", "should", "always", "contain", "the", "true", "raw", "values", "without", "any", "scaling", "to", "allow", "data", "capture", "and", "system", "debuggi...
python
train
kivy/python-for-android
pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/compiler.py
https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/compiler.py#L205-L212
def find_shadowed(self, extra=()): """Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped. """ i = self.identifiers return (i.declared | i.outer_undeclared) & \ (i.declared_locally | i.decla...
[ "def", "find_shadowed", "(", "self", ",", "extra", "=", "(", ")", ")", ":", "i", "=", "self", ".", "identifiers", "return", "(", "i", ".", "declared", "|", "i", ".", "outer_undeclared", ")", "&", "(", "i", ".", "declared_locally", "|", "i", ".", "d...
Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped.
[ "Find", "all", "the", "shadowed", "names", ".", "extra", "is", "an", "iterable", "of", "variables", "that", "may", "be", "defined", "with", "add_special", "which", "may", "occour", "scoped", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L279-L323
def _wiki_articles(shard_id, wikis_dir=None): """Generates WikipediaArticles from GCS that are part of shard shard_id.""" if not wikis_dir: wikis_dir = WIKI_CONTENT_DIR with tf.Graph().as_default(): dataset = tf.data.TFRecordDataset( cc_utils.readahead( os.path.join(wikis_dir, WIKI_CON...
[ "def", "_wiki_articles", "(", "shard_id", ",", "wikis_dir", "=", "None", ")", ":", "if", "not", "wikis_dir", ":", "wikis_dir", "=", "WIKI_CONTENT_DIR", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "dataset", "=", "tf", ".", "...
Generates WikipediaArticles from GCS that are part of shard shard_id.
[ "Generates", "WikipediaArticles", "from", "GCS", "that", "are", "part", "of", "shard", "shard_id", "." ]
python
train
Tanganelli/CoAPthon3
coapthon/caching/cache.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/caching/cache.py#L131-L141
def mark(self, element): """ marks the requested resource in the cache as not fresh :param element: :return: """ logger.debug("Element : {elm}".format(elm=str(element))) if element is not None: logger.debug("Mark as not fresh") element.fres...
[ "def", "mark", "(", "self", ",", "element", ")", ":", "logger", ".", "debug", "(", "\"Element : {elm}\"", ".", "format", "(", "elm", "=", "str", "(", "element", ")", ")", ")", "if", "element", "is", "not", "None", ":", "logger", ".", "debug", "(", ...
marks the requested resource in the cache as not fresh :param element: :return:
[ "marks", "the", "requested", "resource", "in", "the", "cache", "as", "not", "fresh", ":", "param", "element", ":", ":", "return", ":" ]
python
train
codeinn/vcs
vcs/cli.py
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/cli.py#L57-L69
def get_vcsrc(self): """ Returns in-memory created module pointing at user's configuration and extra code/commands. By default tries to create module from :setting:`VCSRC_PATH`. """ try: vimrc = create_module('vcsrc', settings.VCSRC_PATH) except IOErro...
[ "def", "get_vcsrc", "(", "self", ")", ":", "try", ":", "vimrc", "=", "create_module", "(", "'vcsrc'", ",", "settings", ".", "VCSRC_PATH", ")", "except", "IOError", ":", "self", ".", "stderr", ".", "write", "(", "\"No module or package at %s\\n\"", "%", "sett...
Returns in-memory created module pointing at user's configuration and extra code/commands. By default tries to create module from :setting:`VCSRC_PATH`.
[ "Returns", "in", "-", "memory", "created", "module", "pointing", "at", "user", "s", "configuration", "and", "extra", "code", "/", "commands", ".", "By", "default", "tries", "to", "create", "module", "from", ":", "setting", ":", "VCSRC_PATH", "." ]
python
train
IntegralDefense/critsapi
critsapi/critsdbapi.py
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L119-L132
def find_distinct(self, collection, key): """ Search a collection for the distinct key values provided. Args: collection: The db collection. See main class documentation. key: The name of the key to find distinct values. For example with the indicators c...
[ "def", "find_distinct", "(", "self", ",", "collection", ",", "key", ")", ":", "obj", "=", "getattr", "(", "self", ".", "db", ",", "collection", ")", "result", "=", "obj", ".", "distinct", "(", "key", ")", "return", "result" ]
Search a collection for the distinct key values provided. Args: collection: The db collection. See main class documentation. key: The name of the key to find distinct values. For example with the indicators collection, the key could be "type". Returns: ...
[ "Search", "a", "collection", "for", "the", "distinct", "key", "values", "provided", "." ]
python
train
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L4337-L4341
def view_export(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/views#export-view" api_path = "/api/v2/views/{id}/export.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "view_export", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/views/{id}/export.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path", ...
https://developer.zendesk.com/rest_api/docs/core/views#export-view
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "views#export", "-", "view" ]
python
train
acorg/pymds
pymds/mds.py
https://github.com/acorg/pymds/blob/b82939c9df0d434538bd30b7b548908a40f70bbe/pymds/mds.py#L133-L176
def optimize(self, start=None, n=2): """Run multidimensional scaling on this distance matrix. Args: start (`None` or `array-like`): Starting coordinates. If `start=None`, random starting coordinates are used. If `array-like` must have shape [`m` * `n`, ]. ...
[ "def", "optimize", "(", "self", ",", "start", "=", "None", ",", "n", "=", "2", ")", ":", "self", ".", "n", "=", "n", "if", "start", "is", "None", ":", "start", "=", "np", ".", "random", ".", "rand", "(", "self", ".", "m", "*", "self", ".", ...
Run multidimensional scaling on this distance matrix. Args: start (`None` or `array-like`): Starting coordinates. If `start=None`, random starting coordinates are used. If `array-like` must have shape [`m` * `n`, ]. n (`int`): Number of dimensions to embe...
[ "Run", "multidimensional", "scaling", "on", "this", "distance", "matrix", "." ]
python
train
saltstack/salt
salt/netapi/rest_wsgi.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L182-L189
def read_body(environ): ''' Pull the body from the request and return it ''' length = environ.get('CONTENT_LENGTH', '0') length = 0 if length == '' else int(length) return environ['wsgi.input'].read(length)
[ "def", "read_body", "(", "environ", ")", ":", "length", "=", "environ", ".", "get", "(", "'CONTENT_LENGTH'", ",", "'0'", ")", "length", "=", "0", "if", "length", "==", "''", "else", "int", "(", "length", ")", "return", "environ", "[", "'wsgi.input'", "...
Pull the body from the request and return it
[ "Pull", "the", "body", "from", "the", "request", "and", "return", "it" ]
python
train
ambitioninc/django-entity
entity/models.py
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/models.py#L98-L106
def is_sub_to_any(self, *super_entities): """ Given a list of super entities, return the entities that have super entities that interset with those provided. """ if super_entities: return self.filter(id__in=EntityRelationship.objects.filter( super_entity__in=s...
[ "def", "is_sub_to_any", "(", "self", ",", "*", "super_entities", ")", ":", "if", "super_entities", ":", "return", "self", ".", "filter", "(", "id__in", "=", "EntityRelationship", ".", "objects", ".", "filter", "(", "super_entity__in", "=", "super_entities", ")...
Given a list of super entities, return the entities that have super entities that interset with those provided.
[ "Given", "a", "list", "of", "super", "entities", "return", "the", "entities", "that", "have", "super", "entities", "that", "interset", "with", "those", "provided", "." ]
python
train
leonidessaguisagjr/unicodeutil
unicodeutil/unicodeutil.py
https://github.com/leonidessaguisagjr/unicodeutil/blob/c25c882cf9cb38c123df49fad365be67e5818928/unicodeutil/unicodeutil.py#L473-L489
def _build_casefold_map(self): """ Function for parsing the case folding data from the Unicode Character Database (UCD) and generating a lookup table. For more info on the UCD, see the following website: https://www.unicode.org/ucd/ """ self._casefold_map = defaultdict(d...
[ "def", "_build_casefold_map", "(", "self", ")", ":", "self", ".", "_casefold_map", "=", "defaultdict", "(", "dict", ")", "filename", "=", "\"CaseFolding.txt\"", "current_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", ...
Function for parsing the case folding data from the Unicode Character Database (UCD) and generating a lookup table. For more info on the UCD, see the following website: https://www.unicode.org/ucd/
[ "Function", "for", "parsing", "the", "case", "folding", "data", "from", "the", "Unicode", "Character", "Database", "(", "UCD", ")", "and", "generating", "a", "lookup", "table", ".", "For", "more", "info", "on", "the", "UCD", "see", "the", "following", "web...
python
train
networks-lab/metaknowledge
metaknowledge/diffusion.py
https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/diffusion.py#L139-L349
def diffusionCount(source, target, sourceType = "raw", extraValue = None, pandasFriendly = False, compareCounts = False, numAuthors = True, useAllAuthors = True, _ProgBar = None, extraMapping = None): """Takes in two [RecordCollections](../classes/RecordCollection.html#metaknowledge.RecordCollection) and produces ...
[ "def", "diffusionCount", "(", "source", ",", "target", ",", "sourceType", "=", "\"raw\"", ",", "extraValue", "=", "None", ",", "pandasFriendly", "=", "False", ",", "compareCounts", "=", "False", ",", "numAuthors", "=", "True", ",", "useAllAuthors", "=", "Tru...
Takes in two [RecordCollections](../classes/RecordCollection.html#metaknowledge.RecordCollection) and produces a `dict` counting the citations of _source_ by the [Records](../classes/Record.html#metaknowledge.Record) of _target_. By default the `dict` uses `Record` objects as keys but this can be changed with the _sour...
[ "Takes", "in", "two", "[", "RecordCollections", "]", "(", "..", "/", "classes", "/", "RecordCollection", ".", "html#metaknowledge", ".", "RecordCollection", ")", "and", "produces", "a", "dict", "counting", "the", "citations", "of", "_source_", "by", "the", "["...
python
train
looplab/skal
skal/core.py
https://github.com/looplab/skal/blob/af2ce460d9addd07ad2459125511308cfa7cdb44/skal/core.py#L108-L123
def run(self, args=None): """Applicatin starting point. This will run the associated method/function/module or print a help list if it's an unknown keyword or the syntax is incorrect. Keyword arguments: args -- Custom application arguments (default sys.argv) """ ...
[ "def", "run", "(", "self", ",", "args", "=", "None", ")", ":", "# TODO: Add tests to how command line arguments are passed in", "raw_args", "=", "self", ".", "__parser", ".", "parse_args", "(", "args", "=", "args", ")", "args", "=", "vars", "(", "raw_args", ")...
Applicatin starting point. This will run the associated method/function/module or print a help list if it's an unknown keyword or the syntax is incorrect. Keyword arguments: args -- Custom application arguments (default sys.argv)
[ "Applicatin", "starting", "point", "." ]
python
train
pgjones/quart
quart/app.py
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1164-L1181
def teardown_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable: """Add a teardown websocket function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.teardown_websocket def func(): ... ...
[ "def", "teardown_websocket", "(", "self", ",", "func", ":", "Callable", ",", "name", ":", "AppOrBlueprintKey", "=", "None", ")", "->", "Callable", ":", "handler", "=", "ensure_coroutine", "(", "func", ")", "self", ".", "teardown_websocket_funcs", "[", "name", ...
Add a teardown websocket function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.teardown_websocket def func(): ... Arguments: func: The teardown websocket function itself. name: Optio...
[ "Add", "a", "teardown", "websocket", "function", "." ]
python
train
Apitax/Apitax
apitax/api/controllers/migrations/developers_controller.py
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/developers_controller.py#L83-L102
def rename_script(rename=None): # noqa: E501 """Rename a script Rename a script # noqa: E501 :param rename: The data needed to save this script :type rename: dict | bytes :rtype: Response """ if connexion.request.is_json: rename = Rename.from_dict(connexion.request.get_json()) #...
[ "def", "rename_script", "(", "rename", "=", "None", ")", ":", "# noqa: E501", "if", "connexion", ".", "request", ".", "is_json", ":", "rename", "=", "Rename", ".", "from_dict", "(", "connexion", ".", "request", ".", "get_json", "(", ")", ")", "# noqa: E501...
Rename a script Rename a script # noqa: E501 :param rename: The data needed to save this script :type rename: dict | bytes :rtype: Response
[ "Rename", "a", "script" ]
python
train
jhuapl-boss/intern
intern/remote/boss/remote.py
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L952-L970
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs): """ Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step. Args: resource (intern.resource.Resource): Resource compatible w...
[ "def", "get_neuroglancer_link", "(", "self", ",", "resource", ",", "resolution", ",", "x_range", ",", "y_range", ",", "z_range", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_volume", ".", "get_neuroglancer_link", "(", "resource", ",", "resolut...
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step. Args: resource (intern.resource.Resource): Resource compatible with cutout operations. resolution (int): 0 indicates native resolution. x_range (list[in...
[ "Get", "a", "neuroglancer", "link", "of", "the", "cutout", "specified", "from", "the", "host", "specified", "in", "the", "remote", "configuration", "step", "." ]
python
train
hyperledger/indy-plenum
plenum/server/node.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L3001-L3049
def checkPerformance(self) -> Optional[bool]: """ Check if master instance is slow and send an instance change request. :returns True if master performance is OK, False if performance degraded, None if the check was needed """ logger.trace("{} checking its performance".fo...
[ "def", "checkPerformance", "(", "self", ")", "->", "Optional", "[", "bool", "]", ":", "logger", ".", "trace", "(", "\"{} checking its performance\"", ".", "format", "(", "self", ")", ")", "# Move ahead only if the node has synchronized its state with other", "# nodes", ...
Check if master instance is slow and send an instance change request. :returns True if master performance is OK, False if performance degraded, None if the check was needed
[ "Check", "if", "master", "instance", "is", "slow", "and", "send", "an", "instance", "change", "request", ".", ":", "returns", "True", "if", "master", "performance", "is", "OK", "False", "if", "performance", "degraded", "None", "if", "the", "check", "was", ...
python
train
apache/incubator-heron
third_party/python/cpplint/cpplint.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5773-L5834
def CheckRedundantVirtual(filename, clean_lines, linenum, error): """Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The functio...
[ "def", "CheckRedundantVirtual", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Look for \"virtual\" on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "virtual", "=", "Match", "(", "r'^(.*)(\\bvirtual\...
Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
[ "Check", "if", "line", "contains", "a", "redundant", "virtual", "function", "-", "specifier", "." ]
python
valid
pyviz/holoviews
holoviews/core/ndmapping.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/ndmapping.py#L526-L528
def items(self): "Returns all elements as a list in (key,value) format." return list(zip(list(self.keys()), list(self.values())))
[ "def", "items", "(", "self", ")", ":", "return", "list", "(", "zip", "(", "list", "(", "self", ".", "keys", "(", ")", ")", ",", "list", "(", "self", ".", "values", "(", ")", ")", ")", ")" ]
Returns all elements as a list in (key,value) format.
[ "Returns", "all", "elements", "as", "a", "list", "in", "(", "key", "value", ")", "format", "." ]
python
train
aarongarrett/inspyred
inspyred/ec/observers.py
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/observers.py#L113-L132
def population_observer(population, num_generations, num_evaluations, args): """Print the current population of the evolutionary computation to the screen. This function displays the current population of the evolutionary computation to the screen in fitness-sorted order. .. Arguments: ...
[ "def", "population_observer", "(", "population", ",", "num_generations", ",", "num_evaluations", ",", "args", ")", ":", "population", ".", "sort", "(", "reverse", "=", "True", ")", "print", "(", "'---------------------------------------------------------------------------...
Print the current population of the evolutionary computation to the screen. This function displays the current population of the evolutionary computation to the screen in fitness-sorted order. .. Arguments: population -- the population of Individuals num_generations -- the number o...
[ "Print", "the", "current", "population", "of", "the", "evolutionary", "computation", "to", "the", "screen", ".", "This", "function", "displays", "the", "current", "population", "of", "the", "evolutionary", "computation", "to", "the", "screen", "in", "fitness", "...
python
train
pantsbuild/pants
src/python/pants/backend/jvm/tasks/coverage/jacoco.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/coverage/jacoco.py#L189-L199
def _make_multiple_arg(self, arg_name, arg_list): """Jacoco cli allows the specification of multiple values for certain args by repeating the argument with a new value. E.g. --classfiles a.class --classfiles b.class, etc. This method creates a list of strings interleaved with the arg name to satisfy that fo...
[ "def", "_make_multiple_arg", "(", "self", ",", "arg_name", ",", "arg_list", ")", ":", "unique_args", "=", "list", "(", "set", "(", "arg_list", ")", ")", "args", "=", "[", "(", "arg_name", ",", "f", ")", "for", "f", "in", "unique_args", "]", "flattened"...
Jacoco cli allows the specification of multiple values for certain args by repeating the argument with a new value. E.g. --classfiles a.class --classfiles b.class, etc. This method creates a list of strings interleaved with the arg name to satisfy that format.
[ "Jacoco", "cli", "allows", "the", "specification", "of", "multiple", "values", "for", "certain", "args", "by", "repeating", "the", "argument", "with", "a", "new", "value", ".", "E", ".", "g", ".", "--", "classfiles", "a", ".", "class", "--", "classfiles", ...
python
train
Qiskit/qiskit-terra
qiskit/converters/ast_to_dag.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/converters/ast_to_dag.py#L174-L188
def _process_cnot(self, node): """Process a CNOT gate node.""" id0 = self._process_bit_id(node.children[0]) id1 = self._process_bit_id(node.children[1]) if not(len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1): raise QiskitError("internal error: qreg size mismatch", ...
[ "def", "_process_cnot", "(", "self", ",", "node", ")", ":", "id0", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "0", "]", ")", "id1", "=", "self", ".", "_process_bit_id", "(", "node", ".", "children", "[", "1", "]", ")", ...
Process a CNOT gate node.
[ "Process", "a", "CNOT", "gate", "node", "." ]
python
test
nornir-automation/nornir
nornir/core/exceptions.py
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/core/exceptions.py#L75-L79
def failed_hosts(self) -> Dict[str, "MultiResult"]: """ Hosts that failed to complete the task """ return {k: v for k, v in self.result.items() if v.failed}
[ "def", "failed_hosts", "(", "self", ")", "->", "Dict", "[", "str", ",", "\"MultiResult\"", "]", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "result", ".", "items", "(", ")", "if", "v", ".", "failed", "}" ]
Hosts that failed to complete the task
[ "Hosts", "that", "failed", "to", "complete", "the", "task" ]
python
train
deepmipt/DeepPavlov
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L545-L556
def _make_reversed_operation_costs(self): """ Заполняет массив _reversed_operation_costs на основе имеющегося массива operation_costs """ _reversed_operation_costs = dict() for up, costs in self.operation_costs.items(): for low, cost in costs.items(): ...
[ "def", "_make_reversed_operation_costs", "(", "self", ")", ":", "_reversed_operation_costs", "=", "dict", "(", ")", "for", "up", ",", "costs", "in", "self", ".", "operation_costs", ".", "items", "(", ")", ":", "for", "low", ",", "cost", "in", "costs", ".",...
Заполняет массив _reversed_operation_costs на основе имеющегося массива operation_costs
[ "Заполняет", "массив", "_reversed_operation_costs", "на", "основе", "имеющегося", "массива", "operation_costs" ]
python
test
note35/sinon
sinon/lib/util/CollectionHandler.py
https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L101-L113
def obj_in_list_always(target_list, obj): """ >>> l = [1,1,1] >>> obj_in_list_always(l, 1) True >>> l.append(2) >>> obj_in_list_always(l, 1) False """ for item in set(target_list): if item is not obj: return False return True
[ "def", "obj_in_list_always", "(", "target_list", ",", "obj", ")", ":", "for", "item", "in", "set", "(", "target_list", ")", ":", "if", "item", "is", "not", "obj", ":", "return", "False", "return", "True" ]
>>> l = [1,1,1] >>> obj_in_list_always(l, 1) True >>> l.append(2) >>> obj_in_list_always(l, 1) False
[ ">>>", "l", "=", "[", "1", "1", "1", "]", ">>>", "obj_in_list_always", "(", "l", "1", ")", "True", ">>>", "l", ".", "append", "(", "2", ")", ">>>", "obj_in_list_always", "(", "l", "1", ")", "False" ]
python
train
michael-lazar/rtv
rtv/content.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/content.py#L1106-L1114
def _clear_timeouts(self, cache_timeout): """ Clear the cache of timed out results. """ for key in list(self.timeouts): if timer() - self.timeouts[key] > cache_timeout: del self.timeouts[key] del self.cache[key]
[ "def", "_clear_timeouts", "(", "self", ",", "cache_timeout", ")", ":", "for", "key", "in", "list", "(", "self", ".", "timeouts", ")", ":", "if", "timer", "(", ")", "-", "self", ".", "timeouts", "[", "key", "]", ">", "cache_timeout", ":", "del", "self...
Clear the cache of timed out results.
[ "Clear", "the", "cache", "of", "timed", "out", "results", "." ]
python
train
CxAalto/gtfspy
gtfspy/gtfs.py
https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L805-L830
def get_closest_stop(self, lat, lon): """ Get closest stop to a given location. Parameters ---------- lat: float latitude coordinate of the location lon: float longitude coordinate of the location Returns ------- stop_I: i...
[ "def", "get_closest_stop", "(", "self", ",", "lat", ",", "lon", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "min_dist", "=", "float", "(", "\"inf\"", ")", "min_stop_I", "=", "None", "rows", "=", "cur", ".", "execute", "(", "...
Get closest stop to a given location. Parameters ---------- lat: float latitude coordinate of the location lon: float longitude coordinate of the location Returns ------- stop_I: int the index of the stop in the database
[ "Get", "closest", "stop", "to", "a", "given", "location", "." ]
python
valid
glomex/gcdt
gcdt/route53.py
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/route53.py#L73-L105
def _retrieve_stack_host_zone_name(awsclient, default_stack_name=None): """ Use service discovery to get the host zone name from the default stack :return: Host zone name as string """ global _host_zone_name if _host_zone_name is not None: return _host_zone_name env = get_env() ...
[ "def", "_retrieve_stack_host_zone_name", "(", "awsclient", ",", "default_stack_name", "=", "None", ")", ":", "global", "_host_zone_name", "if", "_host_zone_name", "is", "not", "None", ":", "return", "_host_zone_name", "env", "=", "get_env", "(", ")", "if", "env", ...
Use service discovery to get the host zone name from the default stack :return: Host zone name as string
[ "Use", "service", "discovery", "to", "get", "the", "host", "zone", "name", "from", "the", "default", "stack" ]
python
train
thumbor/thumbor
thumbor/engines/extensions/pil.py
https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/engines/extensions/pil.py#L348-L380
def convertImagesToPIL(self, images, dither, nq=0): """ convertImagesToPIL(images, nq=0) Convert images to Paletted PIL images, which can then be written to a single animaged GIF. """ # Convert to PIL images images2 = [] for im in images: if isinsta...
[ "def", "convertImagesToPIL", "(", "self", ",", "images", ",", "dither", ",", "nq", "=", "0", ")", ":", "# Convert to PIL images", "images2", "=", "[", "]", "for", "im", "in", "images", ":", "if", "isinstance", "(", "im", ",", "Image", ".", "Image", ")"...
convertImagesToPIL(images, nq=0) Convert images to Paletted PIL images, which can then be written to a single animaged GIF.
[ "convertImagesToPIL", "(", "images", "nq", "=", "0", ")" ]
python
train
NuGrid/NuGridPy
nugridpy/ppn.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L609-L688
def getElement(self, attri, fname, numtype='cycNum'): ''' In this method instead of getting a particular column of data, the program gets a particular row of data for a particular element name. attri : string The name of the attribute we are looking for. A complete ...
[ "def", "getElement", "(", "self", ",", "attri", ",", "fname", ",", "numtype", "=", "'cycNum'", ")", ":", "element", "=", "[", "]", "#Variable for holding the list of element names", "number", "=", "[", "]", "#Variable for holding the array of numbers", "z", "=", "...
In this method instead of getting a particular column of data, the program gets a particular row of data for a particular element name. attri : string The name of the attribute we are looking for. A complete list of them can be obtained by calling >>> get('e...
[ "In", "this", "method", "instead", "of", "getting", "a", "particular", "column", "of", "data", "the", "program", "gets", "a", "particular", "row", "of", "data", "for", "a", "particular", "element", "name", "." ]
python
train
tensorflow/probability
tensorflow_probability/python/distributions/joint_distribution_sequential.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution_sequential.py#L333-L340
def _entropy(self): """Shannon entropy in nats.""" if any(self._dist_fn_args): raise ValueError( 'Can only compute entropy when all distributions are independent.') return sum(joint_distribution_lib.maybe_check_wont_broadcast( (d().entropy() for d in self._dist_fn_wrapped), s...
[ "def", "_entropy", "(", "self", ")", ":", "if", "any", "(", "self", ".", "_dist_fn_args", ")", ":", "raise", "ValueError", "(", "'Can only compute entropy when all distributions are independent.'", ")", "return", "sum", "(", "joint_distribution_lib", ".", "maybe_check...
Shannon entropy in nats.
[ "Shannon", "entropy", "in", "nats", "." ]
python
test
dougalsutherland/skl-groups
skl_groups/divergences/knn.py
https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L580-L592
def alpha_div(alphas, Ks, dim, num_q, rhos, nus): r''' Estimate the alpha divergence between distributions: \int p^\alpha q^(1-\alpha) based on kNN distances. Used in Renyi, Hellinger, Bhattacharyya, Tsallis divergences. Enforces that estimates are >= 0. Returns divergence estimates w...
[ "def", "alpha_div", "(", "alphas", ",", "Ks", ",", "dim", ",", "num_q", ",", "rhos", ",", "nus", ")", ":", "return", "_get_alpha_div", "(", "alphas", ",", "Ks", ",", "dim", ")", "(", "num_q", ",", "rhos", ",", "nus", ")" ]
r''' Estimate the alpha divergence between distributions: \int p^\alpha q^(1-\alpha) based on kNN distances. Used in Renyi, Hellinger, Bhattacharyya, Tsallis divergences. Enforces that estimates are >= 0. Returns divergence estimates with shape (num_alphas, num_Ks).
[ "r", "Estimate", "the", "alpha", "divergence", "between", "distributions", ":", "\\", "int", "p^", "\\", "alpha", "q^", "(", "1", "-", "\\", "alpha", ")", "based", "on", "kNN", "distances", "." ]
python
valid
openxc/openxc-python
fabfile.py
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/fabfile.py#L36-L61
def compare_versions(x, y): """ Expects 2 strings in the format of 'X.Y.Z' where X, Y and Z are integers. It will compare the items which will organize things properly by their major, minor and bugfix version. :: >>> my_list = ['v1.13', 'v1.14.2', 'v1.14.1', 'v1.9', 'v1.1'] >>> sort...
[ "def", "compare_versions", "(", "x", ",", "y", ")", ":", "def", "version_to_tuple", "(", "version", ")", ":", "# Trim off the leading v", "version_list", "=", "version", "[", "1", ":", "]", ".", "split", "(", "'.'", ",", "2", ")", "if", "len", "(", "ve...
Expects 2 strings in the format of 'X.Y.Z' where X, Y and Z are integers. It will compare the items which will organize things properly by their major, minor and bugfix version. :: >>> my_list = ['v1.13', 'v1.14.2', 'v1.14.1', 'v1.9', 'v1.1'] >>> sorted(my_list, cmp=compare_versions) ...
[ "Expects", "2", "strings", "in", "the", "format", "of", "X", ".", "Y", ".", "Z", "where", "X", "Y", "and", "Z", "are", "integers", ".", "It", "will", "compare", "the", "items", "which", "will", "organize", "things", "properly", "by", "their", "major", ...
python
train
StackStorm/pybind
pybind/nos/v6_0_2f/hardware/custom_profile/kap_custom_profile/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/hardware/custom_profile/kap_custom_profile/__init__.py#L308-L329
def _set_bfd_l3(self, v, load=False): """ Setter method for bfd_l3, mapped from YANG variable /hardware/custom_profile/kap_custom_profile/bfd_l3 (container) If this variable is read-only (config: false) in the source YANG file, then _set_bfd_l3 is considered as a private method. Backends looking to ...
[ "def", "_set_bfd_l3", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for bfd_l3, mapped from YANG variable /hardware/custom_profile/kap_custom_profile/bfd_l3 (container) If this variable is read-only (config: false) in the source YANG file, then _set_bfd_l3 is considered as a private method. Backends looking to populate this variable should do so via callin...
[ "Setter", "method", "for", "bfd_l3", "mapped", "from", "YANG", "variable", "/", "hardware", "/", "custom_profile", "/", "kap_custom_profile", "/", "bfd_l3", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "fals...
python
train
JoelBender/bacpypes
py34/bacpypes/bvll.py
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/bvll.py#L406-L418
def bvlpdu_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" # make/extend the dictionary of content if use_dict is None: use_dict = as_class() # save the content use_dict.__setitem__('address', str(self.fdAddress)) ...
[ "def", "bvlpdu_contents", "(", "self", ",", "use_dict", "=", "None", ",", "as_class", "=", "dict", ")", ":", "# make/extend the dictionary of content", "if", "use_dict", "is", "None", ":", "use_dict", "=", "as_class", "(", ")", "# save the content", "use_dict", ...
Return the contents of an object as a dict.
[ "Return", "the", "contents", "of", "an", "object", "as", "a", "dict", "." ]
python
train
seanodonnell/django_mce_spellcheck
django_mce_spellcheck/views.py
https://github.com/seanodonnell/django_mce_spellcheck/blob/8c54f4b343db4034c6b6dfc5ed57ff57d901cf2c/django_mce_spellcheck/views.py#L8-L40
def spellcheck(request): """ Returns a HttpResponse that implements the TinyMCE spellchecker protocol. """ try: raw = request.raw_post_data input = json.loads(raw) id = input['id'] method = input['method'] params = input['params'] lang = params[0] arg = pa...
[ "def", "spellcheck", "(", "request", ")", ":", "try", ":", "raw", "=", "request", ".", "raw_post_data", "input", "=", "json", ".", "loads", "(", "raw", ")", "id", "=", "input", "[", "'id'", "]", "method", "=", "input", "[", "'method'", "]", "params",...
Returns a HttpResponse that implements the TinyMCE spellchecker protocol.
[ "Returns", "a", "HttpResponse", "that", "implements", "the", "TinyMCE", "spellchecker", "protocol", "." ]
python
train
apache/incubator-mxnet
python/mxnet/ndarray/random.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/random.py#L279-L329
def exponential(scale=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): r"""Draw samples from an exponential distribution. Its probability density function is .. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}), for x > 0 and 0 elsewhere. \beta is the scale parameter, w...
[ "def", "exponential", "(", "scale", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_exp...
r"""Draw samples from an exponential distribution. Its probability density function is .. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}), for x > 0 and 0 elsewhere. \beta is the scale parameter, which is the inverse of the rate parameter \lambda = 1/\beta. Parameters -...
[ "r", "Draw", "samples", "from", "an", "exponential", "distribution", "." ]
python
train
pypa/pipenv
pipenv/vendor/pexpect/utils.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L130-L156
def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None): '''This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). ''' # if select...
[ "def", "select_ignore_interrupts", "(", "iwtd", ",", "owtd", ",", "ewtd", ",", "timeout", "=", "None", ")", ":", "# if select() is interrupted by a signal (errno==EINTR) then", "# we loop back and enter the select() again.", "if", "timeout", "is", "not", "None", ":", "end...
This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize).
[ "This", "is", "a", "wrapper", "around", "select", ".", "select", "()", "that", "ignores", "signals", ".", "If", "select", ".", "select", "raises", "a", "select", ".", "error", "exception", "and", "errno", "is", "an", "EINTR", "error", "then", "it", "is",...
python
train
ajenhl/tacl
tacl/data_store.py
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L121-L142
def _add_text_ngrams(self, witness, minimum, maximum): """Adds n-gram data from `witness` to the data store. :param witness: witness to get n-grams from :type witness: `WitnessText` :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram s...
[ "def", "_add_text_ngrams", "(", "self", ",", "witness", ",", "minimum", ",", "maximum", ")", ":", "text_id", "=", "self", ".", "_get_text_id", "(", "witness", ")", "self", ".", "_logger", ".", "info", "(", "'Adding n-grams ({} <= n <= {}) for {}'", ".", "forma...
Adds n-gram data from `witness` to the data store. :param witness: witness to get n-grams from :type witness: `WitnessText` :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int`
[ "Adds", "n", "-", "gram", "data", "from", "witness", "to", "the", "data", "store", "." ]
python
train
Azure/azure-event-hubs-python
azure/eventprocessorhost/eh_partition_pump.py
https://github.com/Azure/azure-event-hubs-python/blob/737c5f966557ada2cf10fa0d8f3c19671ae96348/azure/eventprocessorhost/eh_partition_pump.py#L81-L90
async def clean_up_clients_async(self): """ Resets the pump swallows all exceptions. """ if self.partition_receiver: if self.eh_client: await self.eh_client.stop_async() self.partition_receiver = None self.partition_receive_hand...
[ "async", "def", "clean_up_clients_async", "(", "self", ")", ":", "if", "self", ".", "partition_receiver", ":", "if", "self", ".", "eh_client", ":", "await", "self", ".", "eh_client", ".", "stop_async", "(", ")", "self", ".", "partition_receiver", "=", "None"...
Resets the pump swallows all exceptions.
[ "Resets", "the", "pump", "swallows", "all", "exceptions", "." ]
python
train
bertrandvidal/parse_this
parse_this/__init__.py
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/__init__.py#L159-L187
def _set_class_parser(self, init_parser, methods_to_parse, cls): """Creates the complete argument parser for the decorated class. Args: init_parser: argument parser for the __init__ method or None methods_to_parse: dict of method name pointing to their associated arg...
[ "def", "_set_class_parser", "(", "self", ",", "init_parser", ",", "methods_to_parse", ",", "cls", ")", ":", "top_level_parents", "=", "[", "init_parser", "]", "if", "init_parser", "else", "[", "]", "description", "=", "self", ".", "_description", "or", "cls", ...
Creates the complete argument parser for the decorated class. Args: init_parser: argument parser for the __init__ method or None methods_to_parse: dict of method name pointing to their associated argument parser cls: the class we are decorating Returns: ...
[ "Creates", "the", "complete", "argument", "parser", "for", "the", "decorated", "class", "." ]
python
train
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L3306-L3309
def target_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/targets#create-target" api_path = "/api/v2/targets.json" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "target_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/targets.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",", "*", "*", "...
https://developer.zendesk.com/rest_api/docs/core/targets#create-target
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "targets#create", "-", "target" ]
python
train
ambitioninc/django-entity
entity/models.py
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/models.py#L317-L343
def get_membership_cache(self, group_ids=None, is_active=True): """ Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all gr...
[ "def", "get_membership_cache", "(", "self", ",", "group_ids", "=", "None", ",", "is_active", "=", "True", ")", ":", "membership_queryset", "=", "EntityGroupMembership", ".", "objects", ".", "filter", "(", "Q", "(", "entity__isnull", "=", "True", ")", "|", "(...
Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all groups will be fetched :param is_active: Flag indicating whether to filter on...
[ "Build", "a", "dict", "cache", "with", "the", "group", "membership", "info", ".", "Keyed", "off", "the", "group", "id", "and", "the", "values", "are", "a", "2", "element", "list", "of", "entity", "id", "and", "entity", "kind", "id", "(", "same", "value...
python
train
icgood/pymap
pymap/fetch.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/fetch.py#L77-L89
def get(self, attr: FetchAttribute) -> MaybeBytes: """Return the bytes representation of the given message attribue. Args: attr: The fetch attribute. Raises: :class:`NotFetchable` """ attr_name = attr.value.decode('ascii') method = getattr(self,...
[ "def", "get", "(", "self", ",", "attr", ":", "FetchAttribute", ")", "->", "MaybeBytes", ":", "attr_name", "=", "attr", ".", "value", ".", "decode", "(", "'ascii'", ")", "method", "=", "getattr", "(", "self", ",", "'_get_'", "+", "attr_name", ".", "repl...
Return the bytes representation of the given message attribue. Args: attr: The fetch attribute. Raises: :class:`NotFetchable`
[ "Return", "the", "bytes", "representation", "of", "the", "given", "message", "attribue", "." ]
python
train
flowersteam/explauto
explauto/interest_model/tree.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L265-L288
def sample_greedy(self): """ Sample a point in the leaf with the max progress. """ if self.leafnode: return self.sample_bounds() else: lp = self.lower.max_leaf_progress gp = self.greater.max_leaf_progress maxp =...
[ "def", "sample_greedy", "(", "self", ")", ":", "if", "self", ".", "leafnode", ":", "return", "self", ".", "sample_bounds", "(", ")", "else", ":", "lp", "=", "self", ".", "lower", ".", "max_leaf_progress", "gp", "=", "self", ".", "greater", ".", "max_le...
Sample a point in the leaf with the max progress.
[ "Sample", "a", "point", "in", "the", "leaf", "with", "the", "max", "progress", "." ]
python
train
saltstack/salt
salt/modules/virt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L836-L925
def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: ...
[ "def", "_qemu_image_create", "(", "disk", ",", "create_overlay", "=", "False", ",", "saltenv", "=", "'base'", ")", ":", "disk_size", "=", "disk", ".", "get", "(", "'size'", ",", "None", ")", "disk_image", "=", "disk", ".", "get", "(", "'image'", ",", "...
Create the image file using specified disk_size or/and disk_image Return path to the created image file
[ "Create", "the", "image", "file", "using", "specified", "disk_size", "or", "/", "and", "disk_image" ]
python
train
openvax/isovar
isovar/assembly.py
https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/assembly.py#L118-L146
def iterative_overlap_assembly( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequen...
[ "def", "iterative_overlap_assembly", "(", "variant_sequences", ",", "min_overlap_size", "=", "MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE", ")", ":", "if", "len", "(", "variant_sequences", ")", "<=", "1", ":", "# if we don't have at least two sequences to start with then", "# sk...
Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequence which contains them. Returns a list of variant sequences, sorted by decreasing read support.
[ "Assembles", "longer", "sequences", "from", "reads", "centered", "on", "a", "variant", "by", "between", "merging", "all", "pairs", "of", "overlapping", "sequences", "and", "collapsing", "shorter", "sequences", "onto", "every", "longer", "sequence", "which", "conta...
python
train
hazelcast/hazelcast-python-client
hazelcast/transaction.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/transaction.py#L119-L135
def commit(self): """ Commits this transaction. """ self._check_thread() if self.state != _STATE_ACTIVE: raise TransactionError("Transaction is not active.") try: self._check_timeout() request = transaction_commit_codec.encode_request(s...
[ "def", "commit", "(", "self", ")", ":", "self", ".", "_check_thread", "(", ")", "if", "self", ".", "state", "!=", "_STATE_ACTIVE", ":", "raise", "TransactionError", "(", "\"Transaction is not active.\"", ")", "try", ":", "self", ".", "_check_timeout", "(", "...
Commits this transaction.
[ "Commits", "this", "transaction", "." ]
python
train
sorgerlab/indra
indra/sources/biopax/api.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/api.py#L104-L143
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1, database_filter=None): """Returns a BiopaxProcessor for a PathwayCommons paths-from-to query. The paths-from-to query finds the paths from a set of source genes to a set of target genes. http://www.path...
[ "def", "process_pc_pathsfromto", "(", "source_genes", ",", "target_genes", ",", "neighbor_limit", "=", "1", ",", "database_filter", "=", "None", ")", ":", "model", "=", "pcc", ".", "graph_query", "(", "'pathsfromto'", ",", "source_genes", ",", "target_genes", ",...
Returns a BiopaxProcessor for a PathwayCommons paths-from-to query. The paths-from-to query finds the paths from a set of source genes to a set of target genes. http://www.pathwaycommons.org/pc2/#graph http://www.pathwaycommons.org/pc2/#graph_kind Parameters ---------- source_genes : lis...
[ "Returns", "a", "BiopaxProcessor", "for", "a", "PathwayCommons", "paths", "-", "from", "-", "to", "query", "." ]
python
train
pandas-dev/pandas
pandas/core/common.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L145-L160
def cast_scalar_indexer(val): """ To avoid numpy DeprecationWarnings, cast float to integer where valid. Parameters ---------- val : scalar Returns ------- outval : scalar """ # assumes lib.is_scalar(val) if lib.is_float(val) and val == int(val): return int(val) ...
[ "def", "cast_scalar_indexer", "(", "val", ")", ":", "# assumes lib.is_scalar(val)", "if", "lib", ".", "is_float", "(", "val", ")", "and", "val", "==", "int", "(", "val", ")", ":", "return", "int", "(", "val", ")", "return", "val" ]
To avoid numpy DeprecationWarnings, cast float to integer where valid. Parameters ---------- val : scalar Returns ------- outval : scalar
[ "To", "avoid", "numpy", "DeprecationWarnings", "cast", "float", "to", "integer", "where", "valid", "." ]
python
train
saltstack/salt
salt/cloud/clouds/proxmox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L420-L440
def avail_images(call=None, location='local'): ''' Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must ...
[ "def", "avail_images", "(", "call", "=", "None", ",", "location", "=", "'local'", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_images function must be called with '", "'-f or --function, or with the --list-images option'", ...
Return a list of the images that are on the provider CLI Example: .. code-block:: bash salt-cloud --list-images my-proxmox-config
[ "Return", "a", "list", "of", "the", "images", "that", "are", "on", "the", "provider" ]
python
train
LucidtechAI/las-sdk-python
las/client.py
https://github.com/LucidtechAI/las-sdk-python/blob/5f39dee7983baff28a1deb93c12d36414d835d12/las/client.py#L117-L140
def put_document(document_path: str, content_type: str, presigned_url: str) -> str: """Convenience method for putting a document to presigned url. >>> from las import Client >>> client = Client(endpoint='<api endpoint>') >>> client.put_document(document_path='document.jpeg', content_typ...
[ "def", "put_document", "(", "document_path", ":", "str", ",", "content_type", ":", "str", ",", "presigned_url", ":", "str", ")", "->", "str", ":", "body", "=", "pathlib", ".", "Path", "(", "document_path", ")", ".", "read_bytes", "(", ")", "headers", "="...
Convenience method for putting a document to presigned url. >>> from las import Client >>> client = Client(endpoint='<api endpoint>') >>> client.put_document(document_path='document.jpeg', content_type='image/jpeg', >>> presigned_url='<presigned url>') :param document_path: Pat...
[ "Convenience", "method", "for", "putting", "a", "document", "to", "presigned", "url", "." ]
python
train
chbrown/viz
viz/geom.py
https://github.com/chbrown/viz/blob/683a8f91630582d74250690a0e8ea7743ab94058/viz/geom.py#L60-L93
def points(ys, width=None): '''Usage: import scipy.stats def walk(steps, position=0): for step in steps: position += step yield position positions = list(walk(scipy.stats.norm.rvs(size=1000))) points(positions) ''' if width is None: width = terminal.wi...
[ "def", "points", "(", "ys", ",", "width", "=", "None", ")", ":", "if", "width", "is", "None", ":", "width", "=", "terminal", ".", "width", "(", ")", "ys", "=", "np", ".", "array", "(", "ys", ")", "n", "=", "len", "(", "ys", ")", "y_min", ",",...
Usage: import scipy.stats def walk(steps, position=0): for step in steps: position += step yield position positions = list(walk(scipy.stats.norm.rvs(size=1000))) points(positions)
[ "Usage", ":", "import", "scipy", ".", "stats", "def", "walk", "(", "steps", "position", "=", "0", ")", ":", "for", "step", "in", "steps", ":", "position", "+", "=", "step", "yield", "position", "positions", "=", "list", "(", "walk", "(", "scipy", "."...
python
train
faucamp/python-gsmmodem
gsmmodem/modem.py
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L449-L462
def signalStrength(self): """ Checks the modem's cellular network signal strength :raise CommandError: if an error occurs :return: The network signal strength as an integer between 0 and 99, or -1 if it is unknown :rtype: int """ csq = self.CSQ_REGEX.mat...
[ "def", "signalStrength", "(", "self", ")", ":", "csq", "=", "self", ".", "CSQ_REGEX", ".", "match", "(", "self", ".", "write", "(", "'AT+CSQ'", ")", "[", "0", "]", ")", "if", "csq", ":", "ss", "=", "int", "(", "csq", ".", "group", "(", "1", ")"...
Checks the modem's cellular network signal strength :raise CommandError: if an error occurs :return: The network signal strength as an integer between 0 and 99, or -1 if it is unknown :rtype: int
[ "Checks", "the", "modem", "s", "cellular", "network", "signal", "strength", ":", "raise", "CommandError", ":", "if", "an", "error", "occurs", ":", "return", ":", "The", "network", "signal", "strength", "as", "an", "integer", "between", "0", "and", "99", "o...
python
train
idlesign/torrentool
torrentool/utils.py
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/utils.py#L20-L34
def humanize_filesize(bytes_size): """Returns human readable filesize. :param int bytes_size: :rtype: str """ if not bytes_size: return '0 B' names = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') name_idx = int(math.floor(math.log(bytes_size, 1024))) size = round(b...
[ "def", "humanize_filesize", "(", "bytes_size", ")", ":", "if", "not", "bytes_size", ":", "return", "'0 B'", "names", "=", "(", "'B'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", ",", "'EB'", ",", "'ZB'", ",", "'YB'", ")", "name_i...
Returns human readable filesize. :param int bytes_size: :rtype: str
[ "Returns", "human", "readable", "filesize", "." ]
python
train
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L522-L530
def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.style...
[ "def", "render_file", "(", "self", ",", "filename", ")", ":", "dirname", ",", "basename", "=", "split", "(", "filename", ")", "with", "changedir", "(", "dirname", ")", ":", "infile", "=", "abspath", "(", "basename", ")", "outfile", "=", "abspath", "(", ...
Convert a reST file to HTML.
[ "Convert", "a", "reST", "file", "to", "HTML", "." ]
python
train
bgruening/galaxy_ie_helpers
galaxy_ie_helpers/__init__.py
https://github.com/bgruening/galaxy_ie_helpers/blob/22d0f77d9e35297e0e6ca4136d5057409699d137/galaxy_ie_helpers/__init__.py#L116-L143
def get(datasets_identifiers, identifier_type='hid', history_id=None): """ Given the history_id that is displayed to the user, this function will download the file[s] from the history and stores them under /import/ Return value[s] are the path[s] to the dataset[s] stored under /import/ "...
[ "def", "get", "(", "datasets_identifiers", ",", "identifier_type", "=", "'hid'", ",", "history_id", "=", "None", ")", ":", "history_id", "=", "history_id", "or", "os", ".", "environ", "[", "'HISTORY_ID'", "]", "# The object version of bioblend is to slow in retrieving...
Given the history_id that is displayed to the user, this function will download the file[s] from the history and stores them under /import/ Return value[s] are the path[s] to the dataset[s] stored under /import/
[ "Given", "the", "history_id", "that", "is", "displayed", "to", "the", "user", "this", "function", "will", "download", "the", "file", "[", "s", "]", "from", "the", "history", "and", "stores", "them", "under", "/", "import", "/", "Return", "value", "[", "s...
python
train
tjvr/kurt
kurt/__init__.py
https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2347-L2356
def load(self, path): """Load sound from wave file. Uses :attr:`Waveform.load`, but will set the Waveform's name based on the sound filename. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Sound(name, Waveform....
[ "def", "load", "(", "self", ",", "path", ")", ":", "(", "folder", ",", "filename", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", "(", "name", ",", "extension", ")", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "...
Load sound from wave file. Uses :attr:`Waveform.load`, but will set the Waveform's name based on the sound filename.
[ "Load", "sound", "from", "wave", "file", "." ]
python
train
biolink/ontobio
ontobio/sparql/sparql_ontol_utils.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/sparql/sparql_ontol_utils.py#L120-L140
def get_terms_in_subset(ont, subset): """ Find all nodes in a subset. We assume the oboInOwl encoding of subsets, and subset IDs are IRIs """ namedGraph = get_named_graph(ont) # note subsets have an unusual encoding query = """ prefix oboInOwl: <http://www.geneontology.org/formats/oboI...
[ "def", "get_terms_in_subset", "(", "ont", ",", "subset", ")", ":", "namedGraph", "=", "get_named_graph", "(", "ont", ")", "# note subsets have an unusual encoding", "query", "=", "\"\"\"\n prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>\n SELECT ?c ? WHERE {{...
Find all nodes in a subset. We assume the oboInOwl encoding of subsets, and subset IDs are IRIs
[ "Find", "all", "nodes", "in", "a", "subset", "." ]
python
train
Qiskit/qiskit-terra
qiskit/circuit/instruction.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L268-L279
def qasm(self): """Return a default OpenQASM string for the instruction. Derived instructions may override this to print in a different format (e.g. measure q[0] -> c[0];). """ name_param = self.name if self.params: name_param = "%s(%s)" % (name_param, ",".jo...
[ "def", "qasm", "(", "self", ")", ":", "name_param", "=", "self", ".", "name", "if", "self", ".", "params", ":", "name_param", "=", "\"%s(%s)\"", "%", "(", "name_param", ",", "\",\"", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", ...
Return a default OpenQASM string for the instruction. Derived instructions may override this to print in a different format (e.g. measure q[0] -> c[0];).
[ "Return", "a", "default", "OpenQASM", "string", "for", "the", "instruction", "." ]
python
test
ionelmc/python-aspectlib
src/aspectlib/contrib.py
https://github.com/ionelmc/python-aspectlib/blob/7dba7651ab76160b9ce66c9c11e770f7844e95ec/src/aspectlib/contrib.py#L9-L60
def retry(func=None, retries=5, backoff=None, exceptions=(IOError, OSError, EOFError), cleanup=None, sleep=time.sleep): """ Decorator that retries the call ``retries`` times if ``func`` raises ``exceptions``. Can use a ``backoff`` function to sleep till next retry. Example:: >>> should_fail = ...
[ "def", "retry", "(", "func", "=", "None", ",", "retries", "=", "5", ",", "backoff", "=", "None", ",", "exceptions", "=", "(", "IOError", ",", "OSError", ",", "EOFError", ")", ",", "cleanup", "=", "None", ",", "sleep", "=", "time", ".", "sleep", ")"...
Decorator that retries the call ``retries`` times if ``func`` raises ``exceptions``. Can use a ``backoff`` function to sleep till next retry. Example:: >>> should_fail = lambda foo=[1,2,3]: foo and foo.pop() >>> @retry ... def flaky_func(): ... if should_fail(): ......
[ "Decorator", "that", "retries", "the", "call", "retries", "times", "if", "func", "raises", "exceptions", ".", "Can", "use", "a", "backoff", "function", "to", "sleep", "till", "next", "retry", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/structural/delly.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/delly.py#L143-L185
def run(items): """Perform detection of structural variations with delly. Performs post-call filtering with a custom filter tuned based on NA12878 Moleculo and PacBio data, using calls prepared by @ryanlayer and @cc2qe Filters using the high quality variant pairs (DV) compared with high qualit...
[ "def", "run", "(", "items", ")", ":", "work_dir", "=", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "items", "[", "0", "]", "[", "\"dirs\"", "]", "[", "\"work\"", "]", ",", "\"structural\"", ",", "dd", ".", "get_sample_name...
Perform detection of structural variations with delly. Performs post-call filtering with a custom filter tuned based on NA12878 Moleculo and PacBio data, using calls prepared by @ryanlayer and @cc2qe Filters using the high quality variant pairs (DV) compared with high quality reference pairs (DR).
[ "Perform", "detection", "of", "structural", "variations", "with", "delly", "." ]
python
train
dw/mitogen
ansible_mitogen/services.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/services.py#L305-L316
def _on_context_disconnect(self, context): """ Respond to Context disconnect event by deleting any record of the no longer reachable context. This method runs in the Broker thread and must not to block. """ self._lock.acquire() try: LOG.info('%r: Forg...
[ "def", "_on_context_disconnect", "(", "self", ",", "context", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "LOG", ".", "info", "(", "'%r: Forgetting %r due to stream disconnect'", ",", "self", ",", "context", ")", "self", ".", "_forg...
Respond to Context disconnect event by deleting any record of the no longer reachable context. This method runs in the Broker thread and must not to block.
[ "Respond", "to", "Context", "disconnect", "event", "by", "deleting", "any", "record", "of", "the", "no", "longer", "reachable", "context", ".", "This", "method", "runs", "in", "the", "Broker", "thread", "and", "must", "not", "to", "block", "." ]
python
train
vsergeev/python-periphery
periphery/gpio.py
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/gpio.py#L103-L130
def read(self): """Read the state of the GPIO. Returns: bool: ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs. """ # Read value try: buf = os.read(self._fd, 2) except OSError ...
[ "def", "read", "(", "self", ")", ":", "# Read value", "try", ":", "buf", "=", "os", ".", "read", "(", "self", ".", "_fd", ",", "2", ")", "except", "OSError", "as", "e", ":", "raise", "GPIOError", "(", "e", ".", "errno", ",", "\"Reading GPIO: \"", "...
Read the state of the GPIO. Returns: bool: ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs.
[ "Read", "the", "state", "of", "the", "GPIO", "." ]
python
train
psss/did
did/plugins/bugzilla.py
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L167-L173
def verified(self): """ True if bug was verified in given time frame """ for who, record in self.logs: if record["field_name"] == "status" \ and record["added"] == "VERIFIED": return True return False
[ "def", "verified", "(", "self", ")", ":", "for", "who", ",", "record", "in", "self", ".", "logs", ":", "if", "record", "[", "\"field_name\"", "]", "==", "\"status\"", "and", "record", "[", "\"added\"", "]", "==", "\"VERIFIED\"", ":", "return", "True", ...
True if bug was verified in given time frame
[ "True", "if", "bug", "was", "verified", "in", "given", "time", "frame" ]
python
train
bambinos/bambi
bambi/backends/stan.py
https://github.com/bambinos/bambi/blob/b4a0ced917968bb99ca20915317417d708387946/bambi/backends/stan.py#L82-L289
def build(self, spec, reset=True): ''' Compile the Stan model from an abstract model specification. Args: spec (Model): A bambi Model instance containing the abstract specification of the model to compile. reset (bool): if True (default), resets the StanBa...
[ "def", "build", "(", "self", ",", "spec", ",", "reset", "=", "True", ")", ":", "if", "reset", ":", "self", ".", "reset", "(", ")", "n_cases", "=", "len", "(", "spec", ".", "y", ".", "data", ")", "self", ".", "data", ".", "append", "(", "'int<lo...
Compile the Stan model from an abstract model specification. Args: spec (Model): A bambi Model instance containing the abstract specification of the model to compile. reset (bool): if True (default), resets the StanBackEnd instance before compiling.
[ "Compile", "the", "Stan", "model", "from", "an", "abstract", "model", "specification", ".", "Args", ":", "spec", "(", "Model", ")", ":", "A", "bambi", "Model", "instance", "containing", "the", "abstract", "specification", "of", "the", "model", "to", "compile...
python
train
athre0z/wasm
wasm/formatter.py
https://github.com/athre0z/wasm/blob/bc9c7e3f40242a2a8fc9650c4b994f0cddf8d755/wasm/formatter.py#L46-L80
def format_function( func_body, func_type=None, indent=2, format_locals=True, ): """ Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string representation of the function line by line. The function type is required for formatting function parameter and return value ...
[ "def", "format_function", "(", "func_body", ",", "func_type", "=", "None", ",", "indent", "=", "2", ",", "format_locals", "=", "True", ",", ")", ":", "if", "func_type", "is", "None", ":", "yield", "'func'", "else", ":", "param_section", "=", "' (param {})'...
Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string representation of the function line by line. The function type is required for formatting function parameter and return value information.
[ "Takes", "a", "FunctionBody", "and", "optionally", "a", "FunctionType", "yielding", "the", "string", "representation", "of", "the", "function", "line", "by", "line", ".", "The", "function", "type", "is", "required", "for", "formatting", "function", "parameter", ...
python
test
studionow/pybrightcove
pybrightcove/video.py
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L633-L643
def activate(video_id, _connection=None): """ Mark a video as Active """ c = _connection if not c: c = connection.APIConnection() data = c.post('update_video', video={ 'id': video_id, 'itemState': enums.ItemStateEnum.ACTIVE}) re...
[ "def", "activate", "(", "video_id", ",", "_connection", "=", "None", ")", ":", "c", "=", "_connection", "if", "not", "c", ":", "c", "=", "connection", ".", "APIConnection", "(", ")", "data", "=", "c", ".", "post", "(", "'update_video'", ",", "video", ...
Mark a video as Active
[ "Mark", "a", "video", "as", "Active" ]
python
train
sorgerlab/indra
indra/tools/assemble_corpus.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L122-L201
def merge_groundings(stmts_in): """Gather and merge original grounding information from evidences. Each Statement's evidences are traversed to find original grounding information. These groundings are then merged into an overall consensus grounding dict with as much detail as possible. The current...
[ "def", "merge_groundings", "(", "stmts_in", ")", ":", "def", "surface_grounding", "(", "stmt", ")", ":", "# Find the \"best\" grounding for a given concept and its evidences", "# and surface that", "for", "idx", ",", "concept", "in", "enumerate", "(", "stmt", ".", "agen...
Gather and merge original grounding information from evidences. Each Statement's evidences are traversed to find original grounding information. These groundings are then merged into an overall consensus grounding dict with as much detail as possible. The current implementation is only applicable to S...
[ "Gather", "and", "merge", "original", "grounding", "information", "from", "evidences", "." ]
python
train
jobovy/galpy
galpy/util/bovy_coords.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_coords.py#L953-L1008
def galcenrect_to_XYZ(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True): """ NAME: galcenrect_to_XYZ PURPOSE: transform rectangular Galactocentric to XYZ coordinates (wrt Sun) coordinates INPUT: X, Y, Z - Galactocentric rectangular coordinates Xsun - cylindrical distance to the GC...
[ "def", "galcenrect_to_XYZ", "(", "X", ",", "Y", ",", "Z", ",", "Xsun", "=", "1.", ",", "Zsun", "=", "0.", ",", "_extra_rot", "=", "True", ")", ":", "dgc", "=", "nu", ".", "sqrt", "(", "Xsun", "**", "2.", "+", "Zsun", "**", "2.", ")", "costheta"...
NAME: galcenrect_to_XYZ PURPOSE: transform rectangular Galactocentric to XYZ coordinates (wrt Sun) coordinates INPUT: X, Y, Z - Galactocentric rectangular coordinates Xsun - cylindrical distance to the GC (can be array of same length as X) Zsun - Sun's height abo...
[ "NAME", ":" ]
python
train
glomex/gcdt
gcdt/kumo_core.py
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/kumo_core.py#L123-L139
def call_pre_hook(awsclient, cloudformation): """Invoke the pre_hook BEFORE the config is read. :param awsclient: :param cloudformation: """ # TODO: this is deprecated!! move this to glomex_config_reader # no config available if not hasattr(cloudformation, 'pre_hook'): # hook is not...
[ "def", "call_pre_hook", "(", "awsclient", ",", "cloudformation", ")", ":", "# TODO: this is deprecated!! move this to glomex_config_reader", "# no config available", "if", "not", "hasattr", "(", "cloudformation", ",", "'pre_hook'", ")", ":", "# hook is not present", "return",...
Invoke the pre_hook BEFORE the config is read. :param awsclient: :param cloudformation:
[ "Invoke", "the", "pre_hook", "BEFORE", "the", "config", "is", "read", "." ]
python
train
twosigma/beakerx
beakerx/setupbase.py
https://github.com/twosigma/beakerx/blob/404de61ed627d9daaf6b77eb4859e7cb6f37413f/beakerx/setupbase.py#L400-L432
def wrap_command(cmds, data_dirs, cls, strict=True): """Wrap a setup command Parameters ---------- cmds: list(str) The names of the other commands to run prior to the command. strict: boolean, optional Wether to raise errors when a pre-command fails. """ class WrappedCommand...
[ "def", "wrap_command", "(", "cmds", ",", "data_dirs", ",", "cls", ",", "strict", "=", "True", ")", ":", "class", "WrappedCommand", "(", "cls", ")", ":", "def", "run", "(", "self", ")", ":", "if", "not", "getattr", "(", "self", ",", "'uninstall'", ","...
Wrap a setup command Parameters ---------- cmds: list(str) The names of the other commands to run prior to the command. strict: boolean, optional Wether to raise errors when a pre-command fails.
[ "Wrap", "a", "setup", "command", "Parameters", "----------", "cmds", ":", "list", "(", "str", ")", "The", "names", "of", "the", "other", "commands", "to", "run", "prior", "to", "the", "command", ".", "strict", ":", "boolean", "optional", "Wether", "to", ...
python
train
ejhigson/nestcheck
nestcheck/error_analysis.py
https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L117-L178
def run_bootstrap_values(ns_run, estimator_list, **kwargs): """Uses bootstrap resampling to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for estim...
[ "def", "run_bootstrap_values", "(", "ns_run", ",", "estimator_list", ",", "*", "*", "kwargs", ")", ":", "ninit_sep", "=", "kwargs", ".", "pop", "(", "'ninit_sep'", ",", "False", ")", "flip_skew", "=", "kwargs", ".", "pop", "(", "'flip_skew'", ",", "True", ...
Uses bootstrap resampling to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for estimating sampling errors see 'Sampling errors in nested sampling p...
[ "Uses", "bootstrap", "resampling", "to", "calculate", "an", "estimate", "of", "the", "standard", "deviation", "of", "the", "distribution", "of", "sampling", "errors", "(", "the", "uncertainty", "on", "the", "calculation", ")", "for", "a", "single", "nested", "...
python
train
ciena/afkak
afkak/brokerclient.py
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L149-L194
def makeRequest(self, requestId, request, expectResponse=True): """ Send a request to our broker via our self.proto KafkaProtocol object. Return a deferred which will fire when the reply matching the requestId comes back from the server, or, if expectResponse is False, then retu...
[ "def", "makeRequest", "(", "self", ",", "requestId", ",", "request", ",", "expectResponse", "=", "True", ")", ":", "if", "requestId", "in", "self", ".", "requests", ":", "# Id is duplicate to 'in-flight' request. Reject it, as we", "# won't be able to properly deliver the...
Send a request to our broker via our self.proto KafkaProtocol object. Return a deferred which will fire when the reply matching the requestId comes back from the server, or, if expectResponse is False, then return None instead. If we are not currently connected, then we buffer the reque...
[ "Send", "a", "request", "to", "our", "broker", "via", "our", "self", ".", "proto", "KafkaProtocol", "object", "." ]
python
train
intake/intake
intake/source/utils.py
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L134-L213
def reverse_format(format_string, resolved_string): """ Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template strin...
[ "def", "reverse_format", "(", "format_string", ",", "resolved_string", ")", ":", "from", "string", "import", "Formatter", "from", "datetime", "import", "datetime", "fmt", "=", "Formatter", "(", ")", "args", "=", "{", "}", "# ensure that format_string is in posix for...
Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template string as used with str.format method resolved_string : str ...
[ "Reverse", "the", "string", "method", "format", "." ]
python
train
acutesoftware/AIKIF
aikif/toolbox/network_tools.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/network_tools.py#L48-L65
def download_file_no_logon(url, filename): """ download a file from a public website with no logon required output = open(filename,'wb') output.write(request.urlopen(url).read()) output.close() """ import urllib.request #url = "http://www.google.com/" request = urllib.reques...
[ "def", "download_file_no_logon", "(", "url", ",", "filename", ")", ":", "import", "urllib", ".", "request", "#url = \"http://www.google.com/\"", "request", "=", "urllib", ".", "request", ".", "Request", "(", "url", ")", "try", ":", "response", "=", "urllib", "...
download a file from a public website with no logon required output = open(filename,'wb') output.write(request.urlopen(url).read()) output.close()
[ "download", "a", "file", "from", "a", "public", "website", "with", "no", "logon", "required", "output", "=", "open", "(", "filename", "wb", ")", "output", ".", "write", "(", "request", ".", "urlopen", "(", "url", ")", ".", "read", "()", ")", "output", ...
python
train
merll/docker-map
dockermap/map/config/host_volume.py
https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/config/host_volume.py#L11-L36
def get_host_path(root, path, instance=None): """ Generates the host path for a container volume. If the given path is a dictionary, uses the entry of the instance name. :param root: Root path to prepend, if ``path`` does not already describe an absolute path. :type root: unicode | str | AbstractLa...
[ "def", "get_host_path", "(", "root", ",", "path", ",", "instance", "=", "None", ")", ":", "r_val", "=", "resolve_value", "(", "path", ")", "if", "isinstance", "(", "r_val", ",", "dict", ")", ":", "r_instance", "=", "instance", "or", "'default'", "r_path"...
Generates the host path for a container volume. If the given path is a dictionary, uses the entry of the instance name. :param root: Root path to prepend, if ``path`` does not already describe an absolute path. :type root: unicode | str | AbstractLazyObject :param path: Path string or dictionary of per...
[ "Generates", "the", "host", "path", "for", "a", "container", "volume", ".", "If", "the", "given", "path", "is", "a", "dictionary", "uses", "the", "entry", "of", "the", "instance", "name", "." ]
python
train
COALAIP/pycoalaip
coalaip/model_validators.py
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L13-L18
def use_model_attr(attr): """Use the validator set on a separate attribute on the class.""" def use_model_validator(instance, attribute, value): getattr(instance, attr)(instance, attribute, value) return use_model_validator
[ "def", "use_model_attr", "(", "attr", ")", ":", "def", "use_model_validator", "(", "instance", ",", "attribute", ",", "value", ")", ":", "getattr", "(", "instance", ",", "attr", ")", "(", "instance", ",", "attribute", ",", "value", ")", "return", "use_mode...
Use the validator set on a separate attribute on the class.
[ "Use", "the", "validator", "set", "on", "a", "separate", "attribute", "on", "the", "class", "." ]
python
train
google/dotty
efilter/parsers/dottysql/parser.py
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/dottysql/parser.py#L699-L714
def list(self): """Parse a list (tuple) which can contain any combination of types.""" start = self.tokens.matched.start if self.tokens.accept(common_grammar.rbracket): return ast.Tuple(start=start, end=self.tokens.matched.end, source=self.original) ...
[ "def", "list", "(", "self", ")", ":", "start", "=", "self", ".", "tokens", ".", "matched", ".", "start", "if", "self", ".", "tokens", ".", "accept", "(", "common_grammar", ".", "rbracket", ")", ":", "return", "ast", ".", "Tuple", "(", "start", "=", ...
Parse a list (tuple) which can contain any combination of types.
[ "Parse", "a", "list", "(", "tuple", ")", "which", "can", "contain", "any", "combination", "of", "types", "." ]
python
train
thombashi/allpairspy
examples/example2.1.py
https://github.com/thombashi/allpairspy/blob/9dd256d7ccdc1348c5807d4a814294d9c5192293/examples/example2.1.py#L13-L39
def is_valid_combination(row): """ This is a filtering function. Filtering functions should return True if combination is valid and False otherwise. Test row that is passed here can be incomplete. To prevent search for unnecessary items filtering function is executed with found subset of data t...
[ "def", "is_valid_combination", "(", "row", ")", ":", "n", "=", "len", "(", "row", ")", "if", "n", ">", "1", ":", "# Brand Y does not support Windows 98", "if", "\"98\"", "==", "row", "[", "1", "]", "and", "\"Brand Y\"", "==", "row", "[", "0", "]", ":",...
This is a filtering function. Filtering functions should return True if combination is valid and False otherwise. Test row that is passed here can be incomplete. To prevent search for unnecessary items filtering function is executed with found subset of data to validate it.
[ "This", "is", "a", "filtering", "function", ".", "Filtering", "functions", "should", "return", "True", "if", "combination", "is", "valid", "and", "False", "otherwise", "." ]
python
train
peeringdb/peeringdb-py
peeringdb/config.py
https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L148-L175
def prompt_config(sch, defaults=None, path=None): """ Utility function to recursively prompt for config values Arguments: - defaults<dict>: default values used for empty inputs - path<str>: path to prepend to config keys (eg. "path.keyname") """ out = {} for name, attr in sch.at...
[ "def", "prompt_config", "(", "sch", ",", "defaults", "=", "None", ",", "path", "=", "None", ")", ":", "out", "=", "{", "}", "for", "name", ",", "attr", "in", "sch", ".", "attributes", "(", ")", ":", "fullpath", "=", "name", "if", "path", ":", "fu...
Utility function to recursively prompt for config values Arguments: - defaults<dict>: default values used for empty inputs - path<str>: path to prepend to config keys (eg. "path.keyname")
[ "Utility", "function", "to", "recursively", "prompt", "for", "config", "values" ]
python
train
EventTeam/beliefs
src/beliefs/cells/dicts.py
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L132-L140
def is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """ if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__di...
[ "def", "is_contradictory", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "DictCell", ")", ":", "raise", "Exception", "(", "\"Incomparable\"", ")", "for", "key", ",", "val", "in", "self", ":", "if", "key", "in", "oth...
Returns True if the two DictCells are unmergeable.
[ "Returns", "True", "if", "the", "two", "DictCells", "are", "unmergeable", "." ]
python
train
NetEaseGame/ATX
atx/ext/report/__init__.py
https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L169-L183
def info(self, text, screenshot=None): """ Args: - text(str): description - screenshot: Bool or PIL.Image object """ step = { 'time': '%.1f' % (time.time()-self.start_time,), 'action': 'info', 'description': text, 's...
[ "def", "info", "(", "self", ",", "text", ",", "screenshot", "=", "None", ")", ":", "step", "=", "{", "'time'", ":", "'%.1f'", "%", "(", "time", ".", "time", "(", ")", "-", "self", ".", "start_time", ",", ")", ",", "'action'", ":", "'info'", ",", ...
Args: - text(str): description - screenshot: Bool or PIL.Image object
[ "Args", ":", "-", "text", "(", "str", ")", ":", "description", "-", "screenshot", ":", "Bool", "or", "PIL", ".", "Image", "object" ]
python
train
onnx/onnxmltools
onnxmltools/convert/xgboost/common.py
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/xgboost/common.py#L5-L16
def get_xgb_params(xgb_node): """ Retrieves parameters of a model. """ if hasattr(xgb_node, 'kwargs'): # XGBoost >= 0.7 params = xgb_node.get_xgb_params() else: # XGBoost < 0.7 params = xgb_node.__dict__ return params
[ "def", "get_xgb_params", "(", "xgb_node", ")", ":", "if", "hasattr", "(", "xgb_node", ",", "'kwargs'", ")", ":", "# XGBoost >= 0.7", "params", "=", "xgb_node", ".", "get_xgb_params", "(", ")", "else", ":", "# XGBoost < 0.7", "params", "=", "xgb_node", ".", "...
Retrieves parameters of a model.
[ "Retrieves", "parameters", "of", "a", "model", "." ]
python
train
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L572-L635
def update_flapping(self, notif_period, hosts, services): """Compute the sample list (self.flapping_changes) and determine whether the host/service is flapping or not :param notif_period: notification period object for this host/service :type notif_period: alignak.object.timeperiod.Time...
[ "def", "update_flapping", "(", "self", ",", "notif_period", ",", "hosts", ",", "services", ")", ":", "flap_history", "=", "self", ".", "__class__", ".", "flap_history", "# We compute the flapping change in %", "res", "=", "0.0", "i", "=", "0", "for", "has_change...
Compute the sample list (self.flapping_changes) and determine whether the host/service is flapping or not :param notif_period: notification period object for this host/service :type notif_period: alignak.object.timeperiod.Timeperiod :param hosts: Hosts objects, used to create notificati...
[ "Compute", "the", "sample", "list", "(", "self", ".", "flapping_changes", ")", "and", "determine", "whether", "the", "host", "/", "service", "is", "flapping", "or", "not" ]
python
train
jxtech/wechatpy
wechatpy/enterprise/client/api/menu.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/enterprise/client/api/menu.py#L14-L28
def create(self, agent_id, menu_data): """ 创建菜单 https://work.weixin.qq.com/api/doc#90000/90135/90231 :param agent_id: 应用id """ return self._post( 'menu/create', params={ 'agentid': agent_id }, data=menu_dat...
[ "def", "create", "(", "self", ",", "agent_id", ",", "menu_data", ")", ":", "return", "self", ".", "_post", "(", "'menu/create'", ",", "params", "=", "{", "'agentid'", ":", "agent_id", "}", ",", "data", "=", "menu_data", ")" ]
创建菜单 https://work.weixin.qq.com/api/doc#90000/90135/90231 :param agent_id: 应用id
[ "创建菜单" ]
python
train
PMBio/limix-backup
limix/deprecated/core.py
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/core.py#L11922-L11934
def optdeltaAllY(UY, UX, S, ldeltagrid): """ optdeltaAllY(MatrixXd const & UY, MatrixXd const & UX, MatrixXd const & S, MatrixXd const & ldeltagrid) Parameters ---------- UY: MatrixXd const & UX: MatrixXd const & S: MatrixXd const & ldeltagrid: MatrixXd const & """ return _core...
[ "def", "optdeltaAllY", "(", "UY", ",", "UX", ",", "S", ",", "ldeltagrid", ")", ":", "return", "_core", ".", "optdeltaAllY", "(", "UY", ",", "UX", ",", "S", ",", "ldeltagrid", ")" ]
optdeltaAllY(MatrixXd const & UY, MatrixXd const & UX, MatrixXd const & S, MatrixXd const & ldeltagrid) Parameters ---------- UY: MatrixXd const & UX: MatrixXd const & S: MatrixXd const & ldeltagrid: MatrixXd const &
[ "optdeltaAllY", "(", "MatrixXd", "const", "&", "UY", "MatrixXd", "const", "&", "UX", "MatrixXd", "const", "&", "S", "MatrixXd", "const", "&", "ldeltagrid", ")" ]
python
train
foremast/foremast
src/foremast/awslambda/api_gateway_event/api_gateway_event.py
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/api_gateway_event/api_gateway_event.py#L212-L225
def generate_uris(self): """Generate several lambda uris.""" lambda_arn = "arn:aws:execute-api:{0}:{1}:{2}/*/{3}/{4}".format(self.region, self.account_id, self.api_id, self.trigger_settings['method'], ...
[ "def", "generate_uris", "(", "self", ")", ":", "lambda_arn", "=", "\"arn:aws:execute-api:{0}:{1}:{2}/*/{3}/{4}\"", ".", "format", "(", "self", ".", "region", ",", "self", ".", "account_id", ",", "self", ".", "api_id", ",", "self", ".", "trigger_settings", "[", ...
Generate several lambda uris.
[ "Generate", "several", "lambda", "uris", "." ]
python
train