repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
wummel/linkchecker
linkcheck/checker/itmsservicesurl.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/itmsservicesurl.py#L28-L32
def check_syntax(self): """Only logs that this URL is unknown.""" super(ItmsServicesUrl, self).check_syntax() if u"url=" not in self.urlparts[3]: self.set_result(_("Missing required url parameter"), valid=False)
[ "def", "check_syntax", "(", "self", ")", ":", "super", "(", "ItmsServicesUrl", ",", "self", ")", ".", "check_syntax", "(", ")", "if", "u\"url=\"", "not", "in", "self", ".", "urlparts", "[", "3", "]", ":", "self", ".", "set_result", "(", "_", "(", "\"...
Only logs that this URL is unknown.
[ "Only", "logs", "that", "this", "URL", "is", "unknown", "." ]
python
train
48.6
arne-cl/discoursegraphs
src/discoursegraphs/discoursegraph.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/discoursegraph.py#L905-L920
def get_node_annotation_layers(docgraph): """ WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating nodes in the given graph """ all_layers = set() for node_id, node_a...
[ "def", "get_node_annotation_layers", "(", "docgraph", ")", ":", "all_layers", "=", "set", "(", ")", "for", "node_id", ",", "node_attribs", "in", "docgraph", ".", "nodes_iter", "(", "data", "=", "True", ")", ":", "for", "layer", "in", "node_attribs", "[", "...
WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating nodes in the given graph
[ "WARNING", ":", "this", "is", "higly", "inefficient!", "Fix", "this", "via", "Issue", "#36", "." ]
python
train
27.9375
frictionlessdata/tableschema-sql-py
tableschema_sql/storage.py
https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/storage.py#L162-L178
def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Get table and fallbacks table = self.__get_table(bucket) schema = tableschema.Schema(self.describe(bucket)) # Open and close transaction with self.__connection.begin(...
[ "def", "iter", "(", "self", ",", "bucket", ")", ":", "# Get table and fallbacks", "table", "=", "self", ".", "__get_table", "(", "bucket", ")", "schema", "=", "tableschema", ".", "Schema", "(", "self", ".", "describe", "(", "bucket", ")", ")", "# Open and ...
https://github.com/frictionlessdata/tableschema-sql-py#storage
[ "https", ":", "//", "github", ".", "com", "/", "frictionlessdata", "/", "tableschema", "-", "sql", "-", "py#storage" ]
python
train
40.058824
Nic30/hwt
hwt/synthesizer/rtlLevel/optimalizator.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/rtlLevel/optimalizator.py#L14-L63
def removeUnconnectedSignals(netlist): """ If signal is not driving anything remove it """ toDelete = set() toSearch = netlist.signals while toSearch: _toSearch = set() for sig in toSearch: if not sig.endpoints: try: if sig._inte...
[ "def", "removeUnconnectedSignals", "(", "netlist", ")", ":", "toDelete", "=", "set", "(", ")", "toSearch", "=", "netlist", ".", "signals", "while", "toSearch", ":", "_toSearch", "=", "set", "(", ")", "for", "sig", "in", "toSearch", ":", "if", "not", "sig...
If signal is not driving anything remove it
[ "If", "signal", "is", "not", "driving", "anything", "remove", "it" ]
python
test
31.86
pyGrowler/Growler
growler/http/response.py
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L228-L247
def send_file(self, filename, status=200): """ Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK) """ ...
[ "def", "send_file", "(", "self", ",", "filename", ",", "status", "=", "200", ")", ":", "if", "isinstance", "(", "filename", ",", "Path", ")", "and", "sys", ".", "version_info", ">=", "(", "3", ",", "5", ")", ":", "self", ".", "message", "=", "filen...
Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK)
[ "Reads", "in", "the", "file", "filename", "and", "sends", "bytes", "to", "client" ]
python
train
31.4
paylogic/pip-accel
pip_accel/config.py
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/config.py#L267-L270
def python_executable(self): """The absolute pathname of the Python executable (a string).""" return self.get(property_name='python_executable', default=sys.executable or os.path.join(self.install_prefix, 'bin', 'python'))
[ "def", "python_executable", "(", "self", ")", ":", "return", "self", ".", "get", "(", "property_name", "=", "'python_executable'", ",", "default", "=", "sys", ".", "executable", "or", "os", ".", "path", ".", "join", "(", "self", ".", "install_prefix", ",",...
The absolute pathname of the Python executable (a string).
[ "The", "absolute", "pathname", "of", "the", "Python", "executable", "(", "a", "string", ")", "." ]
python
train
64.75
ZEDGR/pychal
challonge/api.py
https://github.com/ZEDGR/pychal/blob/3600fa9e0557a2a14eb1ad0c0711d28dad3693d7/challonge/api.py#L94-L97
def fetch_and_parse(method, uri, params_prefix=None, **params): """Fetch the given uri and return python dictionary with parsed data-types.""" response = fetch(method, uri, params_prefix, **params) return _parse(json.loads(response.text))
[ "def", "fetch_and_parse", "(", "method", ",", "uri", ",", "params_prefix", "=", "None", ",", "*", "*", "params", ")", ":", "response", "=", "fetch", "(", "method", ",", "uri", ",", "params_prefix", ",", "*", "*", "params", ")", "return", "_parse", "(",...
Fetch the given uri and return python dictionary with parsed data-types.
[ "Fetch", "the", "given", "uri", "and", "return", "python", "dictionary", "with", "parsed", "data", "-", "types", "." ]
python
train
61.75
python-diamond/Diamond
src/collectors/cpu/cpu.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/cpu/cpu.py#L50-L62
def get_default_config(self): """ Returns the default collector settings """ config = super(CPUCollector, self).get_default_config() config.update({ 'path': 'cpu', 'percore': 'True', 'xenfix': None, 'simple': 'False', ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "CPUCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'cpu'", ",", "'percore'", ":", "'True'", ",", "'xen...
Returns the default collector settings
[ "Returns", "the", "default", "collector", "settings" ]
python
train
28.384615
pri22296/beautifultable
beautifultable/rows.py
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/rows.py#L9-L63
def _get_row_within_width(self, row): """Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed...
[ "def", "_get_row_within_width", "(", "self", ",", "row", ")", ":", "table", "=", "self", ".", "_table", "lpw", ",", "rpw", "=", "table", ".", "left_padding_widths", ",", "table", ".", "right_padding_widths", "wep", "=", "table", ".", "width_exceed_policy", "...
Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed according to width exceed policy.
[ "Process", "a", "row", "so", "that", "it", "is", "clamped", "by", "column_width", "." ]
python
train
36.745455
saltstack/salt
salt/utils/openstack/neutron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/neutron.py#L422-L428
def update_subnet(self, subnet, name=None): ''' Updates a subnet ''' subnet_id = self._find_subnet_id(subnet) return self.network_conn.update_subnet( subnet=subnet_id, body={'subnet': {'name': name}})
[ "def", "update_subnet", "(", "self", ",", "subnet", ",", "name", "=", "None", ")", ":", "subnet_id", "=", "self", ".", "_find_subnet_id", "(", "subnet", ")", "return", "self", ".", "network_conn", ".", "update_subnet", "(", "subnet", "=", "subnet_id", ",",...
Updates a subnet
[ "Updates", "a", "subnet" ]
python
train
35.142857
pymacaron/pymacaron
pymacaron/api.py
https://github.com/pymacaron/pymacaron/blob/af244f203f8216108b39d374d46bf8e1813f13d5/pymacaron/api.py#L27-L35
def do_version(): """Return version details of the running server api""" v = ApiPool.ping.model.Version( name=ApiPool().current_server_name, version=ApiPool().current_server_api.get_version(), container=get_container_version(), ) log.info("/version: " + pprint.pformat(v)) ret...
[ "def", "do_version", "(", ")", ":", "v", "=", "ApiPool", ".", "ping", ".", "model", ".", "Version", "(", "name", "=", "ApiPool", "(", ")", ".", "current_server_name", ",", "version", "=", "ApiPool", "(", ")", ".", "current_server_api", ".", "get_version"...
Return version details of the running server api
[ "Return", "version", "details", "of", "the", "running", "server", "api" ]
python
train
35.222222
huntrar/scrape
scrape/utils.py
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L309-L316
def parse_html(infile, xpath): """Filter HTML using XPath.""" if not isinstance(infile, lh.HtmlElement): infile = lh.fromstring(infile) infile = infile.xpath(xpath) if not infile: raise ValueError('XPath {0} returned no results.'.format(xpath)) return infile
[ "def", "parse_html", "(", "infile", ",", "xpath", ")", ":", "if", "not", "isinstance", "(", "infile", ",", "lh", ".", "HtmlElement", ")", ":", "infile", "=", "lh", ".", "fromstring", "(", "infile", ")", "infile", "=", "infile", ".", "xpath", "(", "xp...
Filter HTML using XPath.
[ "Filter", "HTML", "using", "XPath", "." ]
python
train
35.875
fermiPy/fermipy
fermipy/roi_model.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/roi_model.py#L1031-L1046
def create_from_xmlfile(cls, xmlfile, extdir=None): """Create a Source object from an XML file. Parameters ---------- xmlfile : str Path to XML file. extdir : str Path to the extended source archive. """ root = ElementTree.ElementTree(fil...
[ "def", "create_from_xmlfile", "(", "cls", ",", "xmlfile", ",", "extdir", "=", "None", ")", ":", "root", "=", "ElementTree", ".", "ElementTree", "(", "file", "=", "xmlfile", ")", ".", "getroot", "(", ")", "srcs", "=", "root", ".", "findall", "(", "'sour...
Create a Source object from an XML file. Parameters ---------- xmlfile : str Path to XML file. extdir : str Path to the extended source archive.
[ "Create", "a", "Source", "object", "from", "an", "XML", "file", "." ]
python
train
31.125
10gen/mongo-orchestration
mongo_orchestration/sharded_clusters.py
https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L540-L545
def router_del(self, cluster_id, router_id): """remove router from the ShardedCluster""" cluster = self._storage[cluster_id] result = cluster.router_remove(router_id) self._storage[cluster_id] = cluster return result
[ "def", "router_del", "(", "self", ",", "cluster_id", ",", "router_id", ")", ":", "cluster", "=", "self", ".", "_storage", "[", "cluster_id", "]", "result", "=", "cluster", ".", "router_remove", "(", "router_id", ")", "self", ".", "_storage", "[", "cluster_...
remove router from the ShardedCluster
[ "remove", "router", "from", "the", "ShardedCluster" ]
python
train
41.833333
tensorflow/tensor2tensor
tensor2tensor/utils/t2t_model.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L63-L87
def _flatten_dict(original_dict): """Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict ha...
[ "def", "_flatten_dict", "(", "original_dict", ")", ":", "flat_dict", "=", "{", "}", "for", "key", ",", "value", "in", "original_dict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "for", "name", ",", "tensor", ...
Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict have their keys as prefixes in the ...
[ "Flatten", "dict", "of", "dicts", "into", "a", "single", "dict", "with", "appropriate", "prefixes", "." ]
python
train
32.76
mitsei/dlkit
dlkit/json_/repository/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L4510-L4533
def assign_composition_to_repository(self, composition_id, repository_id): """Adds an existing ``Composition`` to a ``Repository``. arg: composition_id (osid.id.Id): the ``Id`` of the ``Composition`` arg: repository_id (osid.id.Id): the ``Id`` of the ``Repo...
[ "def", "assign_composition_to_repository", "(", "self", ",", "composition_id", ",", "repository_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinAssignmentSession.assign_resource_to_bin", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'REPOSI...
Adds an existing ``Composition`` to a ``Repository``. arg: composition_id (osid.id.Id): the ``Id`` of the ``Composition`` arg: repository_id (osid.id.Id): the ``Id`` of the ``Repository`` raise: AlreadyExists - ``composition_id`` already assigned to ...
[ "Adds", "an", "existing", "Composition", "to", "a", "Repository", "." ]
python
train
50.25
DiamondLightSource/python-workflows
workflows/services/common_service.py
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/common_service.py#L170-L183
def start_transport(self): """If a transport object has been defined then connect it now.""" if self.transport: if self.transport.connect(): self.log.debug("Service successfully connected to transport layer") else: raise RuntimeError("Service could...
[ "def", "start_transport", "(", "self", ")", ":", "if", "self", ".", "transport", ":", "if", "self", ".", "transport", ".", "connect", "(", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Service successfully connected to transport layer\"", ")", "else", ...
If a transport object has been defined then connect it now.
[ "If", "a", "transport", "object", "has", "been", "defined", "then", "connect", "it", "now", "." ]
python
train
49.214286
Dallinger/Dallinger
dallinger/models.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1136-L1142
def flatten(self, lst): """Turn a list of lists into a list.""" if lst == []: return lst if isinstance(lst[0], list): return self.flatten(lst[0]) + self.flatten(lst[1:]) return lst[:1] + self.flatten(lst[1:])
[ "def", "flatten", "(", "self", ",", "lst", ")", ":", "if", "lst", "==", "[", "]", ":", "return", "lst", "if", "isinstance", "(", "lst", "[", "0", "]", ",", "list", ")", ":", "return", "self", ".", "flatten", "(", "lst", "[", "0", "]", ")", "+...
Turn a list of lists into a list.
[ "Turn", "a", "list", "of", "lists", "into", "a", "list", "." ]
python
train
36.857143
ten10solutions/Geist
geist/vision.py
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L450-L485
def find_threshold_near_density(img, density, low=0, high=255): """Find a threshold where the fraction of pixels above the threshold is closest to density where density is (count of pixels above threshold / count of pixels). The highest threshold closest to the desired density will be returned. ...
[ "def", "find_threshold_near_density", "(", "img", ",", "density", ",", "low", "=", "0", ",", "high", "=", "255", ")", ":", "size", "=", "numpy", ".", "size", "(", "img", ")", "densities", "=", "[", "]", "last_t", "=", "None", "while", "True", ":", ...
Find a threshold where the fraction of pixels above the threshold is closest to density where density is (count of pixels above threshold / count of pixels). The highest threshold closest to the desired density will be returned. Use low and high to exclude undesirable thresholds. :param i...
[ "Find", "a", "threshold", "where", "the", "fraction", "of", "pixels", "above", "the", "threshold", "is", "closest", "to", "density", "where", "density", "is", "(", "count", "of", "pixels", "above", "threshold", "/", "count", "of", "pixels", ")", ".", "The"...
python
train
32.027778
nickmckay/LiPD-utilities
Python/lipd/timeseries.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/timeseries.py#L372-L388
def _extract_columns(d, tmp_tso, pc): """ Extract data from one paleoData column :param dict d: Column dictionary :param dict tmp_tso: TSO dictionary with only root items :return dict: Finished TSO """ logger_ts.info("enter extract_columns") for k, v in d.items(): if isinstance(v...
[ "def", "_extract_columns", "(", "d", ",", "tmp_tso", ",", "pc", ")", ":", "logger_ts", ".", "info", "(", "\"enter extract_columns\"", ")", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ...
Extract data from one paleoData column :param dict d: Column dictionary :param dict tmp_tso: TSO dictionary with only root items :return dict: Finished TSO
[ "Extract", "data", "from", "one", "paleoData", "column", ":", "param", "dict", "d", ":", "Column", "dictionary", ":", "param", "dict", "tmp_tso", ":", "TSO", "dictionary", "with", "only", "root", "items", ":", "return", "dict", ":", "Finished", "TSO" ]
python
train
35.176471
jxtech/wechatpy
wechatpy/client/api/material.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/material.py#L245-L255
def delete_comment(self, msg_data_id, index, user_comment_id): """ 删除评论 """ return self._post( 'comment/delete', data={ 'msg_data_id': msg_data_id, 'index': index, 'user_comment_id': user_comment_id, })
[ "def", "delete_comment", "(", "self", ",", "msg_data_id", ",", "index", ",", "user_comment_id", ")", ":", "return", "self", ".", "_post", "(", "'comment/delete'", ",", "data", "=", "{", "'msg_data_id'", ":", "msg_data_id", ",", "'index'", ":", "index", ",", ...
删除评论
[ "删除评论" ]
python
train
28
ktdreyer/txkoji
txkoji/task.py
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L328-L340
def params(self): """ Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params. """ if isinstance(self.request, list): return unmu...
[ "def", "params", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "request", ",", "list", ")", ":", "return", "unmunchify", "(", "self", ".", "request", ")", "(", "params", ",", "_", ")", "=", "xmlrpc", ".", "loads", "(", "self", ".", ...
Return a list of parameters in this task's request. If self.request is already a list, simply return it. If self.request is a raw XML-RPC string, parse it and return the params.
[ "Return", "a", "list", "of", "parameters", "in", "this", "task", "s", "request", "." ]
python
train
30.692308
klmitch/bark
bark/format.py
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L421-L444
def convert(self, request, response, data): """ Performs the desired formatting. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
[ "def", "convert", "(", "self", ",", "request", ",", "response", ",", "data", ")", ":", "result", "=", "[", "]", "for", "conv", ",", "datum", "in", "zip", "(", "self", ".", "conversions", ",", "data", ")", ":", "# Only include conversion if it's allowed", ...
Performs the desired formatting. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The data dictionary list returned by the prepa...
[ "Performs", "the", "desired", "formatting", "." ]
python
train
34.416667
PmagPy/PmagPy
pmagpy/validate_upload2.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/validate_upload2.py#L78-L247
def read_upload(up_file, data_model=None): """ take a file that should be ready for upload using the data model, check that all required columns are full, and that all numeric data is in fact numeric. print out warnings for any validation problems return True if there were no problems, otherwise...
[ "def", "read_upload", "(", "up_file", ",", "data_model", "=", "None", ")", ":", "print", "(", "\"-I- Running validation for your upload file\"", ")", "## Read file", "f", "=", "open", "(", "up_file", ")", "lines", "=", "f", ".", "readlines", "(", ")", "f", "...
take a file that should be ready for upload using the data model, check that all required columns are full, and that all numeric data is in fact numeric. print out warnings for any validation problems return True if there were no problems, otherwise return False
[ "take", "a", "file", "that", "should", "be", "ready", "for", "upload", "using", "the", "data", "model", "check", "that", "all", "required", "columns", "are", "full", "and", "that", "all", "numeric", "data", "is", "in", "fact", "numeric", ".", "print", "o...
python
train
46.276471
sbusard/wagoner
wagoner/tree.py
https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/tree.py#L33-L70
def from_table(cls, table, length, prefix=0, flatten=False): """ Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :...
[ "def", "from_table", "(", "cls", ",", "table", ",", "length", ",", "prefix", "=", "0", ",", "flatten", "=", "False", ")", ":", "# Build the expanded tree with necessary suffix and length", "tree", "=", "defaultdict", "(", "dict", ")", "# The tree", "pending", "=...
Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :param length: the length of words generated by the extracted tree; ...
[ "Extract", "from", "the", "given", "table", "a", "tree", "for", "word", "length", "taking", "only", "prefixes", "of", "prefix", "length", "(", "if", "greater", "than", "0", ")", "into", "account", "to", "compute", "successors", ".", ":", "param", "table", ...
python
train
48.394737
mitsei/dlkit
dlkit/handcar/repository/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/objects.py#L1149-L1169
def set_principal_credit_string(self, credit_string=None): """Sets the principal credit string. :param credit_string: the new credit string :type credit_string: ``string`` :raise: ``InvalidArgument`` -- ``credit_string`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()...
[ "def", "set_principal_credit_string", "(", "self", ",", "credit_string", "=", "None", ")", ":", "if", "credit_string", "is", "None", ":", "raise", "NullArgument", "(", ")", "metadata", "=", "Metadata", "(", "*", "*", "settings", ".", "METADATA", "[", "'princ...
Sets the principal credit string. :param credit_string: the new credit string :type credit_string: ``string`` :raise: ``InvalidArgument`` -- ``credit_string`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true`` :raise: ``NullArgument`` -- ``credit_string`` i...
[ "Sets", "the", "principal", "credit", "string", "." ]
python
train
41.190476
Azure/azure-sdk-for-python
azure-eventgrid/azure/eventgrid/event_grid_client.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-eventgrid/azure/eventgrid/event_grid_client.py#L67-L116
def publish_events( self, topic_hostname, events, custom_headers=None, raw=False, **operation_config): """Publishes a batch of events to an Azure Event Grid topic. :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net :type topic_hostn...
[ "def", "publish_events", "(", "self", ",", "topic_hostname", ",", "events", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "operation_config", ")", ":", "# Construct URL", "url", "=", "self", ".", "publish_events", ".", "metadat...
Publishes a batch of events to an Azure Event Grid topic. :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net :type topic_hostname: str :param events: An array of events to be published to Event Grid. :type events: list[~azure.eventgrid....
[ "Publishes", "a", "batch", "of", "events", "to", "an", "Azure", "Event", "Grid", "topic", "." ]
python
test
43.32
lemieuxl/pyGenClean
pyGenClean/Misc/compare_gold_standard.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/Misc/compare_gold_standard.py#L516-L625
def findFlippedSNPs(goldFrqFile1, sourceAlleles, outPrefix): """Find flipped SNPs and flip them in the data1.""" goldAlleles = {} with open(goldFrqFile1, "r") as inputFile: headerIndex = None for i, line in enumerate(inputFile): row = createRowFromPlinkSpacedOutput(line) ...
[ "def", "findFlippedSNPs", "(", "goldFrqFile1", ",", "sourceAlleles", ",", "outPrefix", ")", ":", "goldAlleles", "=", "{", "}", "with", "open", "(", "goldFrqFile1", ",", "\"r\"", ")", "as", "inputFile", ":", "headerIndex", "=", "None", "for", "i", ",", "lin...
Find flipped SNPs and flip them in the data1.
[ "Find", "flipped", "SNPs", "and", "flip", "them", "in", "the", "data1", "." ]
python
train
39.309091
hubo1016/vlcp
vlcp/utils/http.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/http.py#L263-L270
def nl2br(self, text): """ Replace \'\n\' with \'<br/>\\n\' """ if isinstance(text, bytes): return text.replace(b'\n', b'<br/>\n') else: return text.replace('\n', '<br/>\n')
[ "def", "nl2br", "(", "self", ",", "text", ")", ":", "if", "isinstance", "(", "text", ",", "bytes", ")", ":", "return", "text", ".", "replace", "(", "b'\\n'", ",", "b'<br/>\\n'", ")", "else", ":", "return", "text", ".", "replace", "(", "'\\n'", ",", ...
Replace \'\n\' with \'<br/>\\n\'
[ "Replace", "\\", "\\", "n", "\\", "with", "\\", "<br", "/", ">", "\\\\", "n", "\\" ]
python
train
28.75
enkore/i3pystatus
i3pystatus/pulseaudio/__init__.py
https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/pulseaudio/__init__.py#L141-L148
def update_cb(self, context, t, idx, userdata): """A sink property changed, calls request_update""" if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER: pa_operation_unref( pa_context_get_server_info(context, self._server_info_cb, None)) self....
[ "def", "update_cb", "(", "self", ",", "context", ",", "t", ",", "idx", ",", "userdata", ")", ":", "if", "t", "&", "PA_SUBSCRIPTION_EVENT_FACILITY_MASK", "==", "PA_SUBSCRIPTION_EVENT_SERVER", ":", "pa_operation_unref", "(", "pa_context_get_server_info", "(", "context...
A sink property changed, calls request_update
[ "A", "sink", "property", "changed", "calls", "request_update" ]
python
train
42
childsish/lhc-python
lhc/misc/performance_measures.py
https://github.com/childsish/lhc-python/blob/0a669f46a40a39f24d28665e8b5b606dc7e86beb/lhc/misc/performance_measures.py#L64-L79
def mcc(tp, tn, fp, fn): """ Matthew's Correlation Coefficient [-1, 1] 0 = you're just guessing :param int tp: number of true positives :param int tn: number of true negatives :param int fp: number of false positives :param int fn: number of false negatives :rtype: float """ ...
[ "def", "mcc", "(", "tp", ",", "tn", ",", "fp", ",", "fn", ")", ":", "if", "tp", "+", "fp", "==", "0", "or", "tp", "+", "fn", "==", "0", "or", "tn", "+", "fp", "==", "0", "or", "tn", "+", "fn", "==", "0", ":", "den", "=", "1.0", "else", ...
Matthew's Correlation Coefficient [-1, 1] 0 = you're just guessing :param int tp: number of true positives :param int tn: number of true negatives :param int fp: number of false positives :param int fn: number of false negatives :rtype: float
[ "Matthew", "s", "Correlation", "Coefficient", "[", "-", "1", "1", "]", "0", "=", "you", "re", "just", "guessing", ":", "param", "int", "tp", ":", "number", "of", "true", "positives", ":", "param", "int", "tn", ":", "number", "of", "true", "negatives", ...
python
train
31.75
swevm/scaleio-py
scaleiopy/im.py
https://github.com/swevm/scaleio-py/blob/d043a0137cb925987fd5c895a3210968ce1d9028/scaleiopy/im.py#L275-L299
def set_abort_pending(self, newstate): """ Method to set Abort state if something goes wrong during provisioning Method also used to finish provisioning process when all is completed Method: POST """ self.logger.debug("set_abort_pending(" + "{})".format(newstate)) ...
[ "def", "set_abort_pending", "(", "self", ",", "newstate", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"set_abort_pending(\"", "+", "\"{})\"", ".", "format", "(", "newstate", ")", ")", "# NOT TO BE USED", "#default_minimal_cluster_config = '{\"installationId\...
Method to set Abort state if something goes wrong during provisioning Method also used to finish provisioning process when all is completed Method: POST
[ "Method", "to", "set", "Abort", "state", "if", "something", "goes", "wrong", "during", "provisioning", "Method", "also", "used", "to", "finish", "provisioning", "process", "when", "all", "is", "completed", "Method", ":", "POST" ]
python
train
148.12
twilio/twilio-python
twilio/rest/api/v2010/account/conference/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/conference/__init__.py#L351-L364
def recordings(self): """ Access the recordings :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList """ if self._recordings is None: self._recordings = RecordingLi...
[ "def", "recordings", "(", "self", ")", ":", "if", "self", ".", "_recordings", "is", "None", ":", "self", ".", "_recordings", "=", "RecordingList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ...
Access the recordings :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList
[ "Access", "the", "recordings" ]
python
train
35.714286
jazzband/django-widget-tweaks
widget_tweaks/templatetags/widget_tweaks.py
https://github.com/jazzband/django-widget-tweaks/blob/f50ee92410d68e81528a7643a10544e7331af8fb/widget_tweaks/templatetags/widget_tweaks.py#L97-L105
def field_type(field): """ Template filter that returns field class name (in lower case). E.g. if field is CharField then {{ field|field_type }} will return 'charfield'. """ if hasattr(field, 'field') and field.field: return field.field.__class__.__name__.lower() return ''
[ "def", "field_type", "(", "field", ")", ":", "if", "hasattr", "(", "field", ",", "'field'", ")", "and", "field", ".", "field", ":", "return", "field", ".", "field", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", "return", "''" ]
Template filter that returns field class name (in lower case). E.g. if field is CharField then {{ field|field_type }} will return 'charfield'.
[ "Template", "filter", "that", "returns", "field", "class", "name", "(", "in", "lower", "case", ")", ".", "E", ".", "g", ".", "if", "field", "is", "CharField", "then", "{{", "field|field_type", "}}", "will", "return", "charfield", "." ]
python
train
33.444444
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/directory.py
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L4139-L4161
def remove(self): """ remove this object from Ariane server :return: """ LOGGER.debug("Environment.remove") if self.id is None: return None else: params = { 'id': self.id } args = {'http_operation': '...
[ "def", "remove", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Environment.remove\"", ")", "if", "self", ".", "id", "is", "None", ":", "return", "None", "else", ":", "params", "=", "{", "'id'", ":", "self", ".", "id", "}", "args", "=", "{"...
remove this object from Ariane server :return:
[ "remove", "this", "object", "from", "Ariane", "server", ":", "return", ":" ]
python
train
35.652174
watson-developer-cloud/python-sdk
ibm_watson/assistant_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v1.py#L534-L593
def create_intent(self, workspace_id, intent, description=None, examples=None, **kwargs): """ Create intent. Create a new intent. This operation is limited to 2000 requests per ...
[ "def", "create_intent", "(", "self", ",", "workspace_id", ",", "intent", ",", "description", "=", "None", ",", "examples", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "workspace_id", "is", "None", ":", "raise", "ValueError", "(", "'workspace_id m...
Create intent. Create a new intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The name of the intent. This string must conform to the ...
[ "Create", "intent", "." ]
python
train
36.766667
nickmilon/Hellas
Hellas/Athens.py
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Athens.py#L83-L88
def dms2dd(degrees, minutes, seconds, direction): """convert degrees, minutes, seconds to dd :param string direction: one of N S W E """ dd = (degrees + minutes/60.0) + (seconds/3600.0) # 60.0 fraction for python 2+ compatibility return dd * -1 if direction == 'S' or direction == 'W' else ...
[ "def", "dms2dd", "(", "degrees", ",", "minutes", ",", "seconds", ",", "direction", ")", ":", "dd", "=", "(", "degrees", "+", "minutes", "/", "60.0", ")", "+", "(", "seconds", "/", "3600.0", ")", "# 60.0 fraction for python 2+ compatibility", "return", "dd", ...
convert degrees, minutes, seconds to dd :param string direction: one of N S W E
[ "convert", "degrees", "minutes", "seconds", "to", "dd", ":", "param", "string", "direction", ":", "one", "of", "N", "S", "W", "E" ]
python
train
52.833333
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/directory.py
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L2461-L2495
def add_team(self, team, sync=True): """ add a team to this OS instance. :param team: the team to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the team object on list to be added on next save(). :return: ...
[ "def", "add_team", "(", "self", ",", "team", ",", "sync", "=", "True", ")", ":", "LOGGER", ".", "debug", "(", "\"OSInstance.add_team\"", ")", "if", "not", "sync", ":", "self", ".", "team_2_add", ".", "append", "(", "team", ")", "else", ":", "if", "te...
add a team to this OS instance. :param team: the team to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the team object on list to be added on next save(). :return:
[ "add", "a", "team", "to", "this", "OS", "instance", ".", ":", "param", "team", ":", "the", "team", "to", "add", "on", "this", "OS", "instance", ":", "param", "sync", ":", "If", "sync", "=", "True", "(", "default", ")", "synchronize", "with", "Ariane"...
python
train
43.942857
erdewit/ib_insync
ib_insync/util.py
https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/util.py#L52-L69
def tree(obj): """ Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON. """ from .objects import Object if isinstance(obj, (bool, int, float, str, bytes)): return obj elif isinstance(obj, (datetime.date, datetime.time)): return obj...
[ "def", "tree", "(", "obj", ")", ":", "from", ".", "objects", "import", "Object", "if", "isinstance", "(", "obj", ",", "(", "bool", ",", "int", ",", "float", ",", "str", ",", "bytes", ")", ")", ":", "return", "obj", "elif", "isinstance", "(", "obj",...
Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON.
[ "Convert", "object", "to", "a", "tree", "of", "lists", "dicts", "and", "simple", "values", ".", "The", "result", "can", "be", "serialized", "to", "JSON", "." ]
python
train
34.444444
djaodjin/djaodjin-deployutils
deployutils/apps/django/mockup/views.py
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/mockup/views.py#L51-L65
def validate_redirect_url(next_url): """ Returns the next_url path if next_url matches allowed hosts. """ if not next_url: return None parts = urlparse(next_url) if parts.netloc: domain, _ = split_domain_port(parts.netloc) allowed_hosts...
[ "def", "validate_redirect_url", "(", "next_url", ")", ":", "if", "not", "next_url", ":", "return", "None", "parts", "=", "urlparse", "(", "next_url", ")", "if", "parts", ".", "netloc", ":", "domain", ",", "_", "=", "split_domain_port", "(", "parts", ".", ...
Returns the next_url path if next_url matches allowed hosts.
[ "Returns", "the", "next_url", "path", "if", "next_url", "matches", "allowed", "hosts", "." ]
python
train
39.533333
closeio/tasktiger
tasktiger/worker.py
https://github.com/closeio/tasktiger/blob/59f893152d6eb4b7f1f62fc4b35aeeca7f26c07a/tasktiger/worker.py#L177-L220
def _wait_for_new_tasks(self, timeout=0, batch_timeout=0): """ Check activity channel and wait as necessary. This method is also used to slow down the main processing loop to reduce the effects of rapidly sending Redis commands. This method will exit for any of these conditions...
[ "def", "_wait_for_new_tasks", "(", "self", ",", "timeout", "=", "0", ",", "batch_timeout", "=", "0", ")", ":", "new_queue_found", "=", "False", "start_time", "=", "batch_exit", "=", "time", ".", "time", "(", ")", "while", "True", ":", "# Check to see if batc...
Check activity channel and wait as necessary. This method is also used to slow down the main processing loop to reduce the effects of rapidly sending Redis commands. This method will exit for any of these conditions: 1. _did_work is True, suggests there could be more work pending ...
[ "Check", "activity", "channel", "and", "wait", "as", "necessary", "." ]
python
train
45.568182
dw/mitogen
ansible_mitogen/connection.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/connection.py#L860-L869
def spawn_isolated_child(self): """ Fork or launch a new child off the target context. :returns: mitogen.core.Context of the new child. """ return self.get_chain(use_fork=True).call( ansible_mitogen.target.spawn_isolated_child )
[ "def", "spawn_isolated_child", "(", "self", ")", ":", "return", "self", ".", "get_chain", "(", "use_fork", "=", "True", ")", ".", "call", "(", "ansible_mitogen", ".", "target", ".", "spawn_isolated_child", ")" ]
Fork or launch a new child off the target context. :returns: mitogen.core.Context of the new child.
[ "Fork", "or", "launch", "a", "new", "child", "off", "the", "target", "context", "." ]
python
train
29.2
SheffieldML/GPy
GPy/inference/latent_function_inference/laplace.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/inference/latent_function_inference/laplace.py#L233-L306
def mode_computations(self, f_hat, Ki_f, K, Y, likelihood, kern, Y_metadata): """ At the mode, compute the hessian and effective covariance matrix. returns: logZ : approximation to the marginal likelihood woodbury_inv : variable required for calculating the approximation to the...
[ "def", "mode_computations", "(", "self", ",", "f_hat", ",", "Ki_f", ",", "K", ",", "Y", ",", "likelihood", ",", "kern", ",", "Y_metadata", ")", ":", "#At this point get the hessian matrix (or vector as W is diagonal)", "W", "=", "-", "likelihood", ".", "d2logpdf_d...
At the mode, compute the hessian and effective covariance matrix. returns: logZ : approximation to the marginal likelihood woodbury_inv : variable required for calculating the approximation to the covariance matrix dL_dthetaL : array of derivatives (1 x num_kernel_params) ...
[ "At", "the", "mode", "compute", "the", "hessian", "and", "effective", "covariance", "matrix", "." ]
python
train
44.094595
PonteIneptique/collatinus-python
pycollatinus/parser.py
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/parser.py#L104-L113
def lisFichierLexique(self, filepath): """ Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str """ orig = int(filepath.endswith("ext.la")) lignes = lignesFichier(filepath) for ligne in lignes: ...
[ "def", "lisFichierLexique", "(", "self", ",", "filepath", ")", ":", "orig", "=", "int", "(", "filepath", ".", "endswith", "(", "\"ext.la\"", ")", ")", "lignes", "=", "lignesFichier", "(", "filepath", ")", "for", "ligne", "in", "lignes", ":", "self", ".",...
Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str
[ "Lecture", "des", "lemmes", "et", "enregistrement", "de", "leurs", "radicaux" ]
python
train
35.1
ethereum/eth-abi
eth_abi/registry.py
https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L354-L361
def register_encoder(self, lookup: Lookup, encoder: Encoder, label: str=None) -> None: """ Registers the given ``encoder`` under the given ``lookup``. A unique string label may be optionally provided that can be used to refer to the registration by name. For more information about argu...
[ "def", "register_encoder", "(", "self", ",", "lookup", ":", "Lookup", ",", "encoder", ":", "Encoder", ",", "label", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "_register_coder", "(", "self", ".", "_encoders", ",", "lookup", ",", "enc...
Registers the given ``encoder`` under the given ``lookup``. A unique string label may be optionally provided that can be used to refer to the registration by name. For more information about arguments, refer to :any:`register`.
[ "Registers", "the", "given", "encoder", "under", "the", "given", "lookup", ".", "A", "unique", "string", "label", "may", "be", "optionally", "provided", "that", "can", "be", "used", "to", "refer", "to", "the", "registration", "by", "name", ".", "For", "mor...
python
train
55
spdx/tools-python
spdx/parsers/rdf.py
https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L83-L91
def value_error(self, key, bad_value): """Reports a value error using ERROR_MESSAGES dict. key - key to use for ERROR_MESSAGES. bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES. """ msg = ERROR_MESSAGES[key].format(bad_value) s...
[ "def", "value_error", "(", "self", ",", "key", ",", "bad_value", ")", ":", "msg", "=", "ERROR_MESSAGES", "[", "key", "]", ".", "format", "(", "bad_value", ")", "self", ".", "logger", ".", "log", "(", "msg", ")", "self", ".", "error", "=", "True" ]
Reports a value error using ERROR_MESSAGES dict. key - key to use for ERROR_MESSAGES. bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES.
[ "Reports", "a", "value", "error", "using", "ERROR_MESSAGES", "dict", ".", "key", "-", "key", "to", "use", "for", "ERROR_MESSAGES", ".", "bad_value", "-", "is", "passed", "to", "format", "which", "is", "called", "on", "what", "key", "maps", "to", "in", "E...
python
valid
39.666667
jobovy/galpy
galpy/potential/TwoPowerSphericalPotential.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/TwoPowerSphericalPotential.py#L205-L222
def _mass(self,R,z=0.,t=0.): """ NAME: _mass PURPOSE: evaluate the mass within R for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height t - time OUTPUT: the mass enclosed HISTOR...
[ "def", "_mass", "(", "self", ",", "R", ",", "z", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "z", "is", "None", ":", "r", "=", "R", "else", ":", "r", "=", "numpy", ".", "sqrt", "(", "R", "**", "2.", "+", "z", "**", "2.", ")", "retur...
NAME: _mass PURPOSE: evaluate the mass within R for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height t - time OUTPUT: the mass enclosed HISTORY: 2014-04-01 - Written - Erkal (IoA)
[ "NAME", ":", "_mass", "PURPOSE", ":", "evaluate", "the", "mass", "within", "R", "for", "this", "potential", "INPUT", ":", "R", "-", "Galactocentric", "cylindrical", "radius", "z", "-", "vertical", "height", "t", "-", "time", "OUTPUT", ":", "the", "mass", ...
python
train
31.444444
pycontribs/jira
jira/client.py
https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L3591-L3603
def remove_user_from_group(self, username, groupname): """Remove a user from a group. :param username: The user to remove from the group. :param groupname: The group that the user will be removed from. """ url = self._options['server'] + '/rest/api/latest/group/user' x =...
[ "def", "remove_user_from_group", "(", "self", ",", "username", ",", "groupname", ")", ":", "url", "=", "self", ".", "_options", "[", "'server'", "]", "+", "'/rest/api/latest/group/user'", "x", "=", "{", "'groupname'", ":", "groupname", ",", "'username'", ":", ...
Remove a user from a group. :param username: The user to remove from the group. :param groupname: The group that the user will be removed from.
[ "Remove", "a", "user", "from", "a", "group", "." ]
python
train
33.384615
Alignak-monitoring/alignak
alignak/external_command.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L3677-L3705
def schedule_servicegroup_host_downtime(self, servicegroup, start_time, end_time, fixed, trigger_id, duration, author, comment): """Schedule a host downtime for each host of services in a servicegroup Format of the line that triggers function call:: S...
[ "def", "schedule_servicegroup_host_downtime", "(", "self", ",", "servicegroup", ",", "start_time", ",", "end_time", ",", "fixed", ",", "trigger_id", ",", "duration", ",", "author", ",", "comment", ")", ":", "for", "host", "in", "[", "s", ".", "host", "for", ...
Schedule a host downtime for each host of services in a servicegroup Format of the line that triggers function call:: SCHEDULE_SERVICEGROUP_HOST_DOWNTIME;<servicegroup_name>;<start_time>;<end_time>;<fixed>; <trigger_id>;<duration>;<author>;<comment> :param servicegroup: servicegroup to...
[ "Schedule", "a", "host", "downtime", "for", "each", "host", "of", "services", "in", "a", "servicegroup", "Format", "of", "the", "line", "that", "triggers", "function", "call", "::" ]
python
train
45.551724
GoogleCloudPlatform/datastore-ndb-python
demo/task_list.py
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/demo/task_list.py#L61-L74
def mark_done(task_id): """Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist. """ task = Task.get_by_id(task_id) if task is None: raise ValueError('Task with id %d does not exist' % task_id) task.done = True t...
[ "def", "mark_done", "(", "task_id", ")", ":", "task", "=", "Task", ".", "get_by_id", "(", "task_id", ")", "if", "task", "is", "None", ":", "raise", "ValueError", "(", "'Task with id %d does not exist'", "%", "task_id", ")", "task", ".", "done", "=", "True"...
Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist.
[ "Marks", "a", "task", "as", "done", "." ]
python
train
22.571429
pandas-dev/pandas
pandas/core/arrays/datetimelike.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1141-L1177
def _time_shift(self, periods, freq=None): """ Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int ...
[ "def", "_time_shift", "(", "self", ",", "periods", ",", "freq", "=", "None", ")", ":", "if", "freq", "is", "not", "None", "and", "freq", "!=", "self", ".", "freq", ":", "if", "isinstance", "(", "freq", ",", "str", ")", ":", "freq", "=", "frequencie...
Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int Number of periods to shift by. freq : pandas.DateOf...
[ "Shift", "each", "value", "by", "periods", "." ]
python
train
34
kubernetes-client/python
kubernetes/client/apis/rbac_authorization_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/rbac_authorization_v1_api.py#L2062-L2088
def list_role_binding_for_all_namespaces(self, **kwargs): """ list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(...
[ "def", "list_role_binding_for_all_namespaces", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "list_role_binding_for_al...
list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bo...
[ "list", "or", "watch", "objects", "of", "kind", "RoleBinding", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "...
python
train
169.222222
dropbox/pygerduty
pygerduty/events.py
https://github.com/dropbox/pygerduty/blob/11b28bfb66306aa7fc2b95ab9df65eb97ea831cf/pygerduty/events.py#L57-L65
def resolve_incident(self, incident_key, description=None, details=None): """ Causes the referenced incident to enter resolved state. Send a resolve event when the problem that caused the initial trigger has been fixed. """ return self.create_event(descr...
[ "def", "resolve_incident", "(", "self", ",", "incident_key", ",", "description", "=", "None", ",", "details", "=", "None", ")", ":", "return", "self", ".", "create_event", "(", "description", ",", "\"resolve\"", ",", "details", ",", "incident_key", ")" ]
Causes the referenced incident to enter resolved state. Send a resolve event when the problem that caused the initial trigger has been fixed.
[ "Causes", "the", "referenced", "incident", "to", "enter", "resolved", "state", ".", "Send", "a", "resolve", "event", "when", "the", "problem", "that", "caused", "the", "initial", "trigger", "has", "been", "fixed", "." ]
python
train
42.888889
kensho-technologies/graphql-compiler
graphql_compiler/compiler/workarounds/orientdb_query_execution.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/workarounds/orientdb_query_execution.py#L208-L216
def _assert_type_bounds_are_not_conflicting(current_type_bound, previous_type_bound, location, match_query): """Ensure that the two bounds either are an exact match, or one of them is None.""" if all((current_type_bound is not None, previous_type_bound is ...
[ "def", "_assert_type_bounds_are_not_conflicting", "(", "current_type_bound", ",", "previous_type_bound", ",", "location", ",", "match_query", ")", ":", "if", "all", "(", "(", "current_type_bound", "is", "not", "None", ",", "previous_type_bound", "is", "not", "None", ...
Ensure that the two bounds either are an exact match, or one of them is None.
[ "Ensure", "that", "the", "two", "bounds", "either", "are", "an", "exact", "match", "or", "one", "of", "them", "is", "None", "." ]
python
train
64.888889
LonamiWebs/Telethon
telethon/tl/custom/chatgetter.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/chatgetter.py#L97-L105
def is_group(self): """True if the message was sent on a group or megagroup.""" if self._broadcast is None and self.chat: self._broadcast = getattr(self.chat, 'broadcast', None) return ( isinstance(self._chat_peer, (types.PeerChat, types.PeerChannel)) and not...
[ "def", "is_group", "(", "self", ")", ":", "if", "self", ".", "_broadcast", "is", "None", "and", "self", ".", "chat", ":", "self", ".", "_broadcast", "=", "getattr", "(", "self", ".", "chat", ",", "'broadcast'", ",", "None", ")", "return", "(", "isins...
True if the message was sent on a group or megagroup.
[ "True", "if", "the", "message", "was", "sent", "on", "a", "group", "or", "megagroup", "." ]
python
train
37.555556
idlesign/django-sitetree
sitetree/admin.py
https://github.com/idlesign/django-sitetree/blob/61de4608e6e415247c75fe8691027d7c4ed0d1e7/sitetree/admin.py#L232-L262
def item_move(self, request, tree_id, item_id, direction): """Moves item up or down by swapping 'sort_order' field values of neighboring items.""" current_item = MODEL_TREE_ITEM_CLASS._default_manager.get(pk=item_id) if direction == 'up': sort_order = 'sort_order' else: ...
[ "def", "item_move", "(", "self", ",", "request", ",", "tree_id", ",", "item_id", ",", "direction", ")", ":", "current_item", "=", "MODEL_TREE_ITEM_CLASS", ".", "_default_manager", ".", "get", "(", "pk", "=", "item_id", ")", "if", "direction", "==", "'up'", ...
Moves item up or down by swapping 'sort_order' field values of neighboring items.
[ "Moves", "item", "up", "or", "down", "by", "swapping", "sort_order", "field", "values", "of", "neighboring", "items", "." ]
python
test
34.677419
vmware/pyvmomi
pyVmomi/Differ.py
https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVmomi/Differ.py#L94-L111
def DiffDoArrays(self, oldObj, newObj, isElementLinks): """Diff two DataObject arrays""" if len(oldObj) != len(newObj): __Log__.debug('DiffDoArrays: Array lengths do not match %d != %d' % (len(oldObj), len(newObj))) return False for i, j in zip(oldObj, newObj): i...
[ "def", "DiffDoArrays", "(", "self", ",", "oldObj", ",", "newObj", ",", "isElementLinks", ")", ":", "if", "len", "(", "oldObj", ")", "!=", "len", "(", "newObj", ")", ":", "__Log__", ".", "debug", "(", "'DiffDoArrays: Array lengths do not match %d != %d'", "%", ...
Diff two DataObject arrays
[ "Diff", "two", "DataObject", "arrays" ]
python
train
39.611111
kislyuk/aegea
aegea/packages/github3/github.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/github.py#L1158-L1221
def search_issues(self, query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None): """Find issues by state and keyword The query can contain any combination of the following supported qualifers: - ``type`` With this qualifier you can res...
[ "def", "search_issues", "(", "self", ",", "query", ",", "sort", "=", "None", ",", "order", "=", "None", ",", "per_page", "=", "None", ",", "text_match", "=", "False", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "params", "=", ...
Find issues by state and keyword The query can contain any combination of the following supported qualifers: - ``type`` With this qualifier you can restrict the search to issues or pull request only. - ``in`` Qualifies which fields are searched. With this qualifier you ...
[ "Find", "issues", "by", "state", "and", "keyword" ]
python
train
46.40625
napalm-automation/napalm-junos
napalm_junos/junos.py
https://github.com/napalm-automation/napalm-junos/blob/78c0d161daf2abf26af5835b773f6db57c46efff/napalm_junos/junos.py#L1574-L1601
def get_probes_results(self): """Return the results of the RPM probes.""" probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) probes_results_table.get() probes_results_items = probes_results_table.items() for probe_result i...
[ "def", "get_probes_results", "(", "self", ")", ":", "probes_results", "=", "{", "}", "probes_results_table", "=", "junos_views", ".", "junos_rpm_probes_results_table", "(", "self", ".", "device", ")", "probes_results_table", ".", "get", "(", ")", "probes_results_ite...
Return the results of the RPM probes.
[ "Return", "the", "results", "of", "the", "RPM", "probes", "." ]
python
train
44.964286
chaimleib/intervaltree
intervaltree/node.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L109-L117
def compute_depth(self): """ Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree. """ left_depth = self.left_node.compute_depth() if self.left_node ...
[ "def", "compute_depth", "(", "self", ")", ":", "left_depth", "=", "self", ".", "left_node", ".", "compute_depth", "(", ")", "if", "self", ".", "left_node", "else", "0", "right_depth", "=", "self", ".", "right_node", ".", "compute_depth", "(", ")", "if", ...
Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree.
[ "Recursively", "computes", "true", "depth", "of", "the", "subtree", ".", "Should", "only", "be", "needed", "for", "debugging", ".", "Unless", "something", "is", "wrong", "the", "depth", "field", "should", "reflect", "the", "correct", "depth", "of", "the", "s...
python
train
49.555556
odlgroup/odl
odl/tomo/geometry/parallel.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/geometry/parallel.py#L1471-L1587
def parallel_beam_geometry(space, num_angles=None, det_shape=None): r"""Create default parallel beam geometry from ``space``. This is intended for simple test cases where users do not need the full flexibility of the geometries, but simply want a geometry that works. This default geometry gives a full...
[ "def", "parallel_beam_geometry", "(", "space", ",", "num_angles", "=", "None", ",", "det_shape", "=", "None", ")", ":", "# Find maximum distance from rotation axis", "corners", "=", "space", ".", "domain", ".", "corners", "(", ")", "[", ":", ",", ":", "2", "...
r"""Create default parallel beam geometry from ``space``. This is intended for simple test cases where users do not need the full flexibility of the geometries, but simply want a geometry that works. This default geometry gives a fully sampled sinogram according to the Nyquist criterion, which in gene...
[ "r", "Create", "default", "parallel", "beam", "geometry", "from", "space", "." ]
python
train
33.222222
SpheMakh/Stimela
stimela/__init__.py
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/__init__.py#L194-L203
def info(cabdir, header=False): """ prints out help information about a cab """ # First check if cab exists pfile = "{}/parameters.json".format(cabdir) if not os.path.exists(pfile): raise RuntimeError("Cab could not be found at : {}".format(cabdir)) # Get cab info cab_definition = cab.C...
[ "def", "info", "(", "cabdir", ",", "header", "=", "False", ")", ":", "# First check if cab exists", "pfile", "=", "\"{}/parameters.json\"", ".", "format", "(", "cabdir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "pfile", ")", ":", "raise", ...
prints out help information about a cab
[ "prints", "out", "help", "information", "about", "a", "cab" ]
python
train
38
meejah/txtorcon
txtorcon/controller.py
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/controller.py#L1330-L1349
def processEnded(self, status): """ :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API """ self.cleanup() if status.value.exitCode is None: if self._did_timeout: err = RuntimeError("Timeout waiting for Tor launch.") els...
[ "def", "processEnded", "(", "self", ",", "status", ")", ":", "self", ".", "cleanup", "(", ")", "if", "status", ".", "value", ".", "exitCode", "is", "None", ":", "if", "self", ".", "_did_timeout", ":", "err", "=", "RuntimeError", "(", "\"Timeout waiting f...
:api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API
[ ":", "api", ":", "twisted", ".", "internet", ".", "protocol", ".", "ProcessProtocol", "<ProcessProtocol", ">", "API" ]
python
train
34.7
senseobservationsystems/commonsense-python-lib
senseapi.py
https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L1704-L1723
def DomainsGet(self, parameters = None, domain_id = -1): """ This method returns the domains of the current user. The list also contains the domains to which the users has not yet been accepted. @param parameters (dictonary) - Dictionary containing the para...
[ "def", "DomainsGet", "(", "self", ",", "parameters", "=", "None", ",", "domain_id", "=", "-", "1", ")", ":", "url", "=", "''", "if", "parameters", "is", "None", "and", "domain_id", "<>", "-", "1", ":", "url", "=", "'/domains/{0}.json'", ".", "format", ...
This method returns the domains of the current user. The list also contains the domains to which the users has not yet been accepted. @param parameters (dictonary) - Dictionary containing the parameters of the request. @return (...
[ "This", "method", "returns", "the", "domains", "of", "the", "current", "user", ".", "The", "list", "also", "contains", "the", "domains", "to", "which", "the", "users", "has", "not", "yet", "been", "accepted", "." ]
python
train
41.45
datastore/datastore
datastore/core/basic.py
https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L398-L403
def contains(self, key): '''Returns whether the object named by `key` exists. First checks ``cache_datastore``. ''' return self.cache_datastore.contains(key) \ or self.child_datastore.contains(key)
[ "def", "contains", "(", "self", ",", "key", ")", ":", "return", "self", ".", "cache_datastore", ".", "contains", "(", "key", ")", "or", "self", ".", "child_datastore", ".", "contains", "(", "key", ")" ]
Returns whether the object named by `key` exists. First checks ``cache_datastore``.
[ "Returns", "whether", "the", "object", "named", "by", "key", "exists", ".", "First", "checks", "cache_datastore", "." ]
python
train
36.5
Microsoft/nni
tools/nni_cmd/nnictl_utils.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L364-L387
def experiment_list(args): '''get the information of all experiments''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: print('There is no experiment running...') exit(1) update_experiment() experiment_id_list = ...
[ "def", "experiment_list", "(", "args", ")", ":", "experiment_config", "=", "Experiments", "(", ")", "experiment_dict", "=", "experiment_config", ".", "get_all_experiments", "(", ")", "if", "not", "experiment_dict", ":", "print", "(", "'There is no experiment running.....
get the information of all experiments
[ "get", "the", "information", "of", "all", "experiments" ]
python
train
47.791667
uktrade/directory-validators
directory_validators/company.py
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L45-L57
def keywords_special_characters(keywords): """ Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError """ invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n' if any(char in invalid_chars for char in keywords...
[ "def", "keywords_special_characters", "(", "keywords", ")", ":", "invalid_chars", "=", "'!\\\"#$%&\\'()*+-./:;<=>?@[\\\\]^_{|}~\\t\\n'", "if", "any", "(", "char", "in", "invalid_chars", "for", "char", "in", "keywords", ")", ":", "raise", "ValidationError", "(", "MESSA...
Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError
[ "Confirms", "that", "the", "keywords", "don", "t", "contain", "special", "characters" ]
python
train
28.538462
KE-works/pykechain
pykechain/models/scope.py
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L56-L62
def team(self): """Team to which the scope is assigned.""" team_dict = self._json_data.get('team') if team_dict and team_dict.get('id'): return self._client.team(id=team_dict.get('id')) else: return None
[ "def", "team", "(", "self", ")", ":", "team_dict", "=", "self", ".", "_json_data", ".", "get", "(", "'team'", ")", "if", "team_dict", "and", "team_dict", ".", "get", "(", "'id'", ")", ":", "return", "self", ".", "_client", ".", "team", "(", "id", "...
Team to which the scope is assigned.
[ "Team", "to", "which", "the", "scope", "is", "assigned", "." ]
python
train
36.142857
saltstack/salt
salt/scripts.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L442-L451
def salt_run(): ''' Execute a salt convenience routine. ''' import salt.cli.run if '' in sys.path: sys.path.remove('') client = salt.cli.run.SaltRun() _install_signal_handlers(client) client.run()
[ "def", "salt_run", "(", ")", ":", "import", "salt", ".", "cli", ".", "run", "if", "''", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "remove", "(", "''", ")", "client", "=", "salt", ".", "cli", ".", "run", ".", "SaltRun", "(", ")", ...
Execute a salt convenience routine.
[ "Execute", "a", "salt", "convenience", "routine", "." ]
python
train
22.7
LLNL/scraper
scraper/doecode/__init__.py
https://github.com/LLNL/scraper/blob/881a316e4c04dfa5a9cf491b7c7f9f997a7c56ea/scraper/doecode/__init__.py#L41-L54
def process(filename=None, url=None, key=None): """ Yeilds DOE CODE records based on provided input sources param: filename (str): Path to a DOE CODE .json file url (str): URL for a DOE CODE server json file key (str): API Key for connecting to DOE CODE server """ if filena...
[ "def", "process", "(", "filename", "=", "None", ",", "url", "=", "None", ",", "key", "=", "None", ")", ":", "if", "filename", "is", "not", "None", ":", "yield", "from", "process_json", "(", "filename", ")", "elif", "url", "and", "key", ":", "yield", ...
Yeilds DOE CODE records based on provided input sources param: filename (str): Path to a DOE CODE .json file url (str): URL for a DOE CODE server json file key (str): API Key for connecting to DOE CODE server
[ "Yeilds", "DOE", "CODE", "records", "based", "on", "provided", "input", "sources" ]
python
test
30.5
bspaans/python-mingus
mingus/midi/midi_track.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L77-L88
def play_NoteContainer(self, notecontainer): """Convert a mingus.containers.NoteContainer to the equivalent MIDI events and add it to the track_data. Note.channel and Note.velocity can be set as well. """ if len(notecontainer) <= 1: [self.play_Note(x) for x in noteco...
[ "def", "play_NoteContainer", "(", "self", ",", "notecontainer", ")", ":", "if", "len", "(", "notecontainer", ")", "<=", "1", ":", "[", "self", ".", "play_Note", "(", "x", ")", "for", "x", "in", "notecontainer", "]", "else", ":", "self", ".", "play_Note...
Convert a mingus.containers.NoteContainer to the equivalent MIDI events and add it to the track_data. Note.channel and Note.velocity can be set as well.
[ "Convert", "a", "mingus", ".", "containers", ".", "NoteContainer", "to", "the", "equivalent", "MIDI", "events", "and", "add", "it", "to", "the", "track_data", "." ]
python
train
39.083333
saltstack/salt
salt/cloud/clouds/ec2.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L2178-L2304
def query_instance(vm_=None, call=None): ''' Query an instance upon creation from the EC2 API ''' if call == 'function': # Technically this function may be called other ways too, but it # definitely cannot be called with --function. raise SaltCloudSystemExit( 'The que...
[ "def", "query_instance", "(", "vm_", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "# Technically this function may be called other ways too, but it", "# definitely cannot be called with --function.", "raise", "SaltCloudSystemExit", ...
Query an instance upon creation from the EC2 API
[ "Query", "an", "instance", "upon", "creation", "from", "the", "EC2", "API" ]
python
train
34.488189
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cvf.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cvf.py#L36-L49
def generate(env): """Add Builders and construction variables for compaq visual fortran to an Environment.""" fortran.generate(env) env['FORTRAN'] = 'f90' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows...
[ "def", "generate", "(", "env", ")", ":", "fortran", ".", "generate", "(", "env", ")", "env", "[", "'FORTRAN'", "]", "=", "'f90'", "env", "[", "'FORTRANCOM'", "]", "=", "'$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:$...
Add Builders and construction variables for compaq visual fortran to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "compaq", "visual", "fortran", "to", "an", "Environment", "." ]
python
train
68.857143
NASA-AMMOS/AIT-Core
ait/core/bsc.py
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L350-L377
def _should_rotate_log(self, handler): ''' Determine if a log file rotation is necessary ''' if handler['rotate_log']: rotate_time_index = handler.get('rotate_log_index', 'day') try: rotate_time_index = self._decode_time_rotation_index(rotate_time_index) ...
[ "def", "_should_rotate_log", "(", "self", ",", "handler", ")", ":", "if", "handler", "[", "'rotate_log'", "]", ":", "rotate_time_index", "=", "handler", ".", "get", "(", "'rotate_log_index'", ",", "'day'", ")", "try", ":", "rotate_time_index", "=", "self", "...
Determine if a log file rotation is necessary
[ "Determine", "if", "a", "log", "file", "rotation", "is", "necessary" ]
python
train
40.678571
decryptus/sonicprobe
sonicprobe/validator/country.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/validator/country.py#L277-L287
def validate(value): """ checks if given value is a valid country codes @param string value @return bool """ if not helpers.has_len(value): return False return COUNTRIES.has_key(str(value).lower())
[ "def", "validate", "(", "value", ")", ":", "if", "not", "helpers", ".", "has_len", "(", "value", ")", ":", "return", "False", "return", "COUNTRIES", ".", "has_key", "(", "str", "(", "value", ")", ".", "lower", "(", ")", ")" ]
checks if given value is a valid country codes @param string value @return bool
[ "checks", "if", "given", "value", "is", "a", "valid", "country", "codes" ]
python
train
23.363636
spencerahill/aospy
aospy/utils/vertcoord.py
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L92-L94
def pfull_from_ps(bk, pk, ps, pfull_coord): """Compute pressure at full levels from surface pressure.""" return to_pfull_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
[ "def", "pfull_from_ps", "(", "bk", ",", "pk", ",", "ps", ",", "pfull_coord", ")", ":", "return", "to_pfull_from_phalf", "(", "phalf_from_ps", "(", "bk", ",", "pk", ",", "ps", ")", ",", "pfull_coord", ")" ]
Compute pressure at full levels from surface pressure.
[ "Compute", "pressure", "at", "full", "levels", "from", "surface", "pressure", "." ]
python
train
59
gestaolivre/brazil-types
brazil_types/types.py
https://github.com/gestaolivre/brazil-types/blob/13db32c17d66d85166a2459f6b3d6fcff2c2b954/brazil_types/types.py#L290-L314
def validate(cls, cpf): u""" Válida o CPF. >>> CPF.validate(58119443659) True >>> CPF.validate(58119443650) False >>> CPF.validate('58119443659') True >>> CPF.validate('581.194.436-59') True """ if cpf is None: ...
[ "def", "validate", "(", "cls", ",", "cpf", ")", ":", "if", "cpf", "is", "None", ":", "return", "False", "cpf", "=", "CPF", ".", "clean", "(", "cpf", ")", "def", "mod11", "(", "value", ")", ":", "return", "(", "value", "%", "11", ")", "%", "10",...
u""" Válida o CPF. >>> CPF.validate(58119443659) True >>> CPF.validate(58119443650) False >>> CPF.validate('58119443659') True >>> CPF.validate('581.194.436-59') True
[ "u", "Válida", "o", "CPF", "." ]
python
train
23.92
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1374-L1390
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh, flip bottleneck_noise many bits.""" x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck") d0 = tf.stop_gradient(2.0 * tf.to_floa...
[ "def", "tanh_discrete_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "bottleneck_noise", ",", "discretize_warmup_steps", ",", "mode", ")", ":", "x", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "bottleneck_bits", ",", "name", "=", "\"tanh_discre...
Simple discretization through tanh, flip bottleneck_noise many bits.
[ "Simple", "discretization", "through", "tanh", "flip", "bottleneck_noise", "many", "bits", "." ]
python
train
51
Diaoul/subliminal
subliminal/extensions.py
https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/extensions.py#L70-L86
def unregister(self, entry_point): """Unregister a provider :param str entry_point: provider to unregister (entry point syntax). """ if entry_point not in self.registered_extensions: raise ValueError('Extension not registered') ep = EntryPoint.parse(entry_point) ...
[ "def", "unregister", "(", "self", ",", "entry_point", ")", ":", "if", "entry_point", "not", "in", "self", ".", "registered_extensions", ":", "raise", "ValueError", "(", "'Extension not registered'", ")", "ep", "=", "EntryPoint", ".", "parse", "(", "entry_point",...
Unregister a provider :param str entry_point: provider to unregister (entry point syntax).
[ "Unregister", "a", "provider" ]
python
train
35.411765
cpburnz/python-path-specification
pathspec/util.py
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L139-L156
def match_file(patterns, file): """ Matches the file to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :data:`True` if *file* matched; ...
[ "def", "match_file", "(", "patterns", ",", "file", ")", ":", "matched", "=", "False", "for", "pattern", "in", "patterns", ":", "if", "pattern", ".", "include", "is", "not", "None", ":", "if", "file", "in", "pattern", ".", "match", "(", "(", "file", "...
Matches the file to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :data:`True` if *file* matched; otherwise, :data:`False`.
[ "Matches", "the", "file", "to", "the", "patterns", "." ]
python
train
27.444444
CodyKochmann/generators
generators/average.py
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/average.py#L14-L21
def average(): """ generator that holds a rolling average """ count = 0 total = total() i=0 while 1: i = yield ((total.send(i)*1.0)/count if count else 0) count += 1
[ "def", "average", "(", ")", ":", "count", "=", "0", "total", "=", "total", "(", ")", "i", "=", "0", "while", "1", ":", "i", "=", "yield", "(", "(", "total", ".", "send", "(", "i", ")", "*", "1.0", ")", "/", "count", "if", "count", "else", "...
generator that holds a rolling average
[ "generator", "that", "holds", "a", "rolling", "average" ]
python
train
24.25
mamrhein/specification
specification/_extd_ast_expr.py
https://github.com/mamrhein/specification/blob/a4c09a0d286cda7a04e8a189f12e23edd97f64ea/specification/_extd_ast_expr.py#L404-L410
def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of `node` as keyword arg.""" arg = node.arg if arg is None: return f"**{self.visit(node.value)}" else: return f"{arg}={self.visit(node.value)}"
[ "def", "visit_keyword", "(", "self", ",", "node", ":", "AST", ",", "dfltChaining", ":", "bool", "=", "True", ")", "->", "str", ":", "arg", "=", "node", ".", "arg", "if", "arg", "is", "None", ":", "return", "f\"**{self.visit(node.value)}\"", "else", ":", ...
Return representation of `node` as keyword arg.
[ "Return", "representation", "of", "node", "as", "keyword", "arg", "." ]
python
train
41.142857
bpsmith/tia
tia/bbg/bbg_com.py
https://github.com/bpsmith/tia/blob/a7043b6383e557aeea8fc7112bbffd6e36a230e9/tia/bbg/bbg_com.py#L430-L438
def response_as_single(self, copy=0): """ convert the response map to a single data frame with Multi-Index columns """ arr = [] for sid, frame in self.response.iteritems(): if copy: frame = frame.copy() 'security' not in frame and frame.insert(0, 'security...
[ "def", "response_as_single", "(", "self", ",", "copy", "=", "0", ")", ":", "arr", "=", "[", "]", "for", "sid", ",", "frame", "in", "self", ".", "response", ".", "iteritems", "(", ")", ":", "if", "copy", ":", "frame", "=", "frame", ".", "copy", "(...
convert the response map to a single data frame with Multi-Index columns
[ "convert", "the", "response", "map", "to", "a", "single", "data", "frame", "with", "Multi", "-", "Index", "columns" ]
python
train
48
SectorLabs/django-postgres-extra
psqlextra/expressions.py
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/expressions.py#L104-L112
def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), self.target, self.hstore_key, self.output_field )
[ "def", "relabeled_clone", "(", "self", ",", "relabels", ")", ":", "return", "self", ".", "__class__", "(", "relabels", ".", "get", "(", "self", ".", "alias", ",", "self", ".", "alias", ")", ",", "self", ".", "target", ",", "self", ".", "hstore_key", ...
Gets a re-labeled clone of this expression.
[ "Gets", "a", "re", "-", "labeled", "clone", "of", "this", "expression", "." ]
python
test
29.111111
metachris/RPIO
source/RPIO/_RPIO.py
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L114-L217
def add_interrupt_callback(self, gpio_id, callback, edge='both', pull_up_down=_GPIO.PUD_OFF, threaded_callback=False, debounce_timeout_ms=None): """ Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='...
[ "def", "add_interrupt_callback", "(", "self", ",", "gpio_id", ",", "callback", ",", "edge", "=", "'both'", ",", "pull_up_down", "=", "_GPIO", ".", "PUD_OFF", ",", "threaded_callback", "=", "False", ",", "debounce_timeout_ms", "=", "None", ")", ":", "gpio_id", ...
Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `threaded_callback` is True, the callback will be started insid...
[ "Add", "a", "callback", "to", "be", "executed", "when", "the", "value", "on", "gpio_id", "changes", "to", "the", "edge", "specified", "via", "the", "edge", "parameter", "(", "default", "=", "both", ")", "." ]
python
train
44.548077
chrismattmann/tika-python
tika/tika.py
https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L253-L282
def parseAndSave(option, urlOrPaths, outDir=None, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar, responseMimeType='application/json', metaExtension='_meta.json', services={'meta': '/meta', 'text': '/tika', 'all': '/rmeta'}): ''' Parse the objects a...
[ "def", "parseAndSave", "(", "option", ",", "urlOrPaths", ",", "outDir", "=", "None", ",", "serverEndpoint", "=", "ServerEndpoint", ",", "verbose", "=", "Verbose", ",", "tikaServerJar", "=", "TikaServerJar", ",", "responseMimeType", "=", "'application/json'", ",", ...
Parse the objects and write extracted metadata and/or text in JSON format to matching filename with an extension of '_meta.json'. :param option: :param urlOrPaths: :param outDir: :param serverEndpoint: :param verbose: :param tikaServerJar: :param responseMimeType: :param metaExtensio...
[ "Parse", "the", "objects", "and", "write", "extracted", "metadata", "and", "/", "or", "text", "in", "JSON", "format", "to", "matching", "filename", "with", "an", "extension", "of", "_meta", ".", "json", ".", ":", "param", "option", ":", ":", "param", "ur...
python
train
39.9
aarongarrett/inspyred
inspyred/ec/replacers.py
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/replacers.py#L194-L214
def comma_replacement(random, population, parents, offspring, args): """Performs "comma" replacement. This function performs "comma" replacement, which means that the entire existing population is replaced by the best population-many elements from the offspring. This function makes the assumpti...
[ "def", "comma_replacement", "(", "random", ",", "population", ",", "parents", ",", "offspring", ",", "args", ")", ":", "offspring", ".", "sort", "(", "reverse", "=", "True", ")", "survivors", "=", "offspring", "[", ":", "len", "(", "population", ")", "]"...
Performs "comma" replacement. This function performs "comma" replacement, which means that the entire existing population is replaced by the best population-many elements from the offspring. This function makes the assumption that the size of the offspring is at least as large as the original ...
[ "Performs", "comma", "replacement", ".", "This", "function", "performs", "comma", "replacement", "which", "means", "that", "the", "entire", "existing", "population", "is", "replaced", "by", "the", "best", "population", "-", "many", "elements", "from", "the", "of...
python
train
39.809524
androguard/androguard
androguard/core/analysis/analysis.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/analysis/analysis.py#L439-L461
def show(self): """ Prints the content of this method to stdout. This will print the method signature and the decompiled code. """ args, ret = self.method.get_descriptor()[1:].split(")") if self.code: # We patch the descriptor here and add the registers, if c...
[ "def", "show", "(", "self", ")", ":", "args", ",", "ret", "=", "self", ".", "method", ".", "get_descriptor", "(", ")", "[", "1", ":", "]", ".", "split", "(", "\")\"", ")", "if", "self", ".", "code", ":", "# We patch the descriptor here and add the regist...
Prints the content of this method to stdout. This will print the method signature and the decompiled code.
[ "Prints", "the", "content", "of", "this", "method", "to", "stdout", "." ]
python
train
37.391304
saltstack/salt
salt/modules/win_iis.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L822-L930
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0): ''' Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Arg...
[ "def", "create_cert_binding", "(", "name", ",", "site", ",", "hostheader", "=", "''", ",", "ipaddress", "=", "'*'", ",", "port", "=", "443", ",", "sslflags", "=", "0", ")", ":", "name", "=", "six", ".", "text_type", "(", "name", ")", ".", "upper", ...
Assign a certificate to an IIS Web Binding. .. versionadded:: 2016.11.0 .. note:: The web binding that the certificate is being assigned to must already exist. Args: name (str): The thumbprint of the certificate. site (str): The IIS site name. hostheader (str): Th...
[ "Assign", "a", "certificate", "to", "an", "IIS", "Web", "Binding", "." ]
python
train
34.266055
jwkvam/plotlywrapper
plotlywrapper.py
https://github.com/jwkvam/plotlywrapper/blob/762b42912e824fecb1212c186900f2ebdd0ab12b/plotlywrapper.py#L31-L55
def _detect_notebook() -> bool: """Detect if code is running in a Jupyter Notebook. This isn't 100% correct but seems good enough Returns ------- bool True if it detects this is a notebook, otherwise False. """ try: from IPython import get_ipython from ipykernel im...
[ "def", "_detect_notebook", "(", ")", "->", "bool", ":", "try", ":", "from", "IPython", "import", "get_ipython", "from", "ipykernel", "import", "zmqshell", "except", "ImportError", ":", "return", "False", "kernel", "=", "get_ipython", "(", ")", "try", ":", "f...
Detect if code is running in a Jupyter Notebook. This isn't 100% correct but seems good enough Returns ------- bool True if it detects this is a notebook, otherwise False.
[ "Detect", "if", "code", "is", "running", "in", "a", "Jupyter", "Notebook", "." ]
python
train
26.04
aws/aws-encryption-sdk-python
src/aws_encryption_sdk/internal/crypto/authentication.py
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/crypto/authentication.py#L74-L83
def from_key_bytes(cls, algorithm, key_bytes): """Builds a `Signer` from an algorithm suite and a raw signing key. :param algorithm: Algorithm on which to base signer :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes key_bytes: Raw signing key :rtype: aws_en...
[ "def", "from_key_bytes", "(", "cls", ",", "algorithm", ",", "key_bytes", ")", ":", "key", "=", "serialization", ".", "load_der_private_key", "(", "data", "=", "key_bytes", ",", "password", "=", "None", ",", "backend", "=", "default_backend", "(", ")", ")", ...
Builds a `Signer` from an algorithm suite and a raw signing key. :param algorithm: Algorithm on which to base signer :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes key_bytes: Raw signing key :rtype: aws_encryption_sdk.internal.crypto.Signer
[ "Builds", "a", "Signer", "from", "an", "algorithm", "suite", "and", "a", "raw", "signing", "key", "." ]
python
train
50
peepall/FancyLogger
FancyLogger/__init__.py
https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/__init__.py#L387-L396
def error(self, text): """ Posts an error message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their ...
[ "def", "error", "(", "self", ",", "text", ")", ":", "self", ".", "queue", ".", "put", "(", "dill", ".", "dumps", "(", "LogMessageCommand", "(", "text", "=", "text", ",", "level", "=", "logging", ".", "ERROR", ")", ")", ")" ]
Posts an error message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right tim...
[ "Posts", "an", "error", "message", "adding", "a", "timestamp", "and", "logging", "level", "to", "it", "for", "both", "file", "and", "console", "handlers", ".", "Logger", "uses", "a", "redraw", "rate", "because", "of", "console", "flickering", ".", "That", ...
python
train
71.5
zetaops/pyoko
pyoko/db/adapter/db_riak.py
https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/db/adapter/db_riak.py#L412-L470
def save_model(self, model, meta_data=None, index_fields=None): """ model (instance): Model instance. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for indexing keys in ri...
[ "def", "save_model", "(", "self", ",", "model", ",", "meta_data", "=", "None", ",", "index_fields", "=", "None", ")", ":", "# if model:", "# self._model = model", "if", "settings", ".", "DEBUG", ":", "t1", "=", "time", ".", "time", "(", ")", "clean_val...
model (instance): Model instance. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for indexing keys in riak (with 'bin' or 'int'). [('lorem','bin'),('dolar','int')] :ret...
[ "model", "(", "instance", ")", ":", "Model", "instance", ".", "meta", "(", "dict", ")", ":", "JSON", "serializable", "meta", "data", "for", "logging", "of", "save", "operation", ".", "{", "lorem", ":", "ipsum", "dolar", ":", "5", "}", "index_fields", "...
python
train
35.881356
HewlettPackard/python-hpOneView
hpOneView/resources/servers/server_profiles.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/server_profiles.py#L82-L106
def update(self, data=None, timeout=-1, force=''): """Updates server profile template. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops wa...
[ "def", "update", "(", "self", ",", "data", "=", "None", ",", "timeout", "=", "-", "1", ",", "force", "=", "''", ")", ":", "uri", "=", "self", ".", "data", "[", "'uri'", "]", "resource", "=", "deepcopy", "(", "self", ".", "data", ")", "resource", ...
Updates server profile template. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. force: Force the update ...
[ "Updates", "server", "profile", "template", "." ]
python
train
34.52
loli/medpy
doc/numpydoc/numpydoc/plot_directive.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/plot_directive.py#L416-L436
def split_code_at_show(text): """ Split code at plt.show() """ parts = [] is_doctest = contains_doctest(text) part = [] for line in text.split("\n"): if (not is_doctest and line.strip() == 'plt.show()') or \ (is_doctest and line.strip() == '>>> plt.show()'): ...
[ "def", "split_code_at_show", "(", "text", ")", ":", "parts", "=", "[", "]", "is_doctest", "=", "contains_doctest", "(", "text", ")", "part", "=", "[", "]", "for", "line", "in", "text", ".", "split", "(", "\"\\n\"", ")", ":", "if", "(", "not", "is_doc...
Split code at plt.show()
[ "Split", "code", "at", "plt", ".", "show", "()" ]
python
train
24.619048
lvieirajr/mongorest
mongorest/collection.py
https://github.com/lvieirajr/mongorest/blob/00f4487ded33254434bc51ff09d48c7a936bd465/mongorest/collection.py#L316-L321
def update_many(cls, filter, update, upsert=False): """ Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered """ return cls.collection.update_many(filter, update, upsert).raw_result
[ "def", "update_many", "(", "cls", ",", "filter", ",", "update", ",", "upsert", "=", "False", ")", ":", "return", "cls", ".", "collection", ".", "update_many", "(", "filter", ",", "update", ",", "upsert", ")", ".", "raw_result" ]
Updates all documents that pass the filter with the update value Will upsert a new document if upsert=True and no document is filtered
[ "Updates", "all", "documents", "that", "pass", "the", "filter", "with", "the", "update", "value", "Will", "upsert", "a", "new", "document", "if", "upsert", "=", "True", "and", "no", "document", "is", "filtered" ]
python
train
49.666667
danijar/sets
sets/core/step.py
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/core/step.py#L12-L21
def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ @utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): ...
[ "def", "disk_cache", "(", "cls", ",", "basename", ",", "function", ",", "*", "args", ",", "method", "=", "True", ",", "*", "*", "kwargs", ")", ":", "@", "utility", ".", "disk_cache", "(", "basename", ",", "cls", ".", "directory", "(", ")", ",", "me...
Cache the return value in the correct cache directory. Set 'method' to false for static methods.
[ "Cache", "the", "return", "value", "in", "the", "correct", "cache", "directory", ".", "Set", "method", "to", "false", "for", "static", "methods", "." ]
python
train
39.2
inveniosoftware/invenio-jsonschemas
invenio_jsonschemas/ext.py
https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L79-L90
def get_schema_dir(self, path): """Retrieve the directory containing the given schema. :param path: Schema path, relative to the directory where it was registered. :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema was found in the specified path. ...
[ "def", "get_schema_dir", "(", "self", ",", "path", ")", ":", "if", "path", "not", "in", "self", ".", "schemas", ":", "raise", "JSONSchemaNotFound", "(", "path", ")", "return", "self", ".", "schemas", "[", "path", "]" ]
Retrieve the directory containing the given schema. :param path: Schema path, relative to the directory where it was registered. :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema was found in the specified path. :returns: The schema directory.
[ "Retrieve", "the", "directory", "containing", "the", "given", "schema", "." ]
python
train
39
materialsproject/pymatgen
pymatgen/core/surface.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/surface.py#L386-L393
def center_of_mass(self): """ Calculates the center of mass of the slab """ weights = [s.species.weight for s in self] center_of_mass = np.average(self.frac_coords, weights=weights, axis=0) return center_of_mass
[ "def", "center_of_mass", "(", "self", ")", ":", "weights", "=", "[", "s", ".", "species", ".", "weight", "for", "s", "in", "self", "]", "center_of_mass", "=", "np", ".", "average", "(", "self", ".", "frac_coords", ",", "weights", "=", "weights", ",", ...
Calculates the center of mass of the slab
[ "Calculates", "the", "center", "of", "mass", "of", "the", "slab" ]
python
train
36
shoebot/shoebot
shoebot/sbio/shell.py
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L182-L192
def do_speed(self, speed): """ rewind """ if speed: try: self.bot._speed = float(speed) except Exception as e: self.print_response('%s is not a valid framerate' % speed) return self.print_response('Speed: %s ...
[ "def", "do_speed", "(", "self", ",", "speed", ")", ":", "if", "speed", ":", "try", ":", "self", ".", "bot", ".", "_speed", "=", "float", "(", "speed", ")", "except", "Exception", "as", "e", ":", "self", ".", "print_response", "(", "'%s is not a valid f...
rewind
[ "rewind" ]
python
valid
30.272727