repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
matthieugouel/gibica
gibica/sementic.py
https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/sementic.py#L113-L115
def append_table(self, name, **kwargs): """Create a new table.""" self.stack.append(Table(name, **kwargs))
[ "def", "append_table", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "self", ".", "stack", ".", "append", "(", "Table", "(", "name", ",", "*", "*", "kwargs", ")", ")" ]
Create a new table.
[ "Create", "a", "new", "table", "." ]
python
train
Music-Moo/music2storage
music2storage/service.py
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/service.py#L82-L101
def download(self, url): """ Downloads a MP3 file that is associated with the track at the URL passed. :param str url: URL of the track to be downloaded """ try: track = self.client.get('/resolve', url=url) except HTTPError: log.error(f"{url} is not a Soundcloud URL.") return r = requests.get(self.client.get(track.stream_url, allow_redirects=False).location, stream=True) total_size = int(r.headers['content-length']) chunk_size = 1000000 file_name = track.title + '.mp3' with open(file_name, 'wb') as f: for data in tqdm(r.iter_content(chunk_size), desc=track.title, total=total_size / chunk_size, unit='MB', file=sys.stdout): f.write(data) return file_name
[ "def", "download", "(", "self", ",", "url", ")", ":", "try", ":", "track", "=", "self", ".", "client", ".", "get", "(", "'/resolve'", ",", "url", "=", "url", ")", "except", "HTTPError", ":", "log", ".", "error", "(", "f\"{url} is not a Soundcloud URL.\""...
Downloads a MP3 file that is associated with the track at the URL passed. :param str url: URL of the track to be downloaded
[ "Downloads", "a", "MP3", "file", "that", "is", "associated", "with", "the", "track", "at", "the", "URL", "passed", ".", ":", "param", "str", "url", ":", "URL", "of", "the", "track", "to", "be", "downloaded" ]
python
test
tehmaze/diagram
diagram.py
https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L373-L415
def consume(self, istream, ostream, batch=False): """Read points from istream and output to ostream.""" datapoints = [] # List of 2-tuples if batch: sleep = max(0.01, self.option.sleep) fd = istream.fileno() while True: try: if select.select([fd], [], [], sleep): try: line = istream.readline() if line == '': break datapoints.append(self.consume_line(line)) except ValueError: continue if self.option.sort_by_column: datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1)) if len(datapoints) > 1: datapoints = datapoints[-self.maximum_points:] self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints]) self.render(ostream) time.sleep(sleep) except KeyboardInterrupt: break else: for line in istream: try: datapoints.append(self.consume_line(line)) except ValueError: pass if self.option.sort_by_column: datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1)) self.update([dp[0] for dp in datapoints], [dp[1] for dp in datapoints]) self.render(ostream)
[ "def", "consume", "(", "self", ",", "istream", ",", "ostream", ",", "batch", "=", "False", ")", ":", "datapoints", "=", "[", "]", "# List of 2-tuples", "if", "batch", ":", "sleep", "=", "max", "(", "0.01", ",", "self", ".", "option", ".", "sleep", ")...
Read points from istream and output to ostream.
[ "Read", "points", "from", "istream", "and", "output", "to", "ostream", "." ]
python
valid
Kronuz/pyScss
scss/extension/compass/helpers.py
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/helpers.py#L73-L83
def compact(*args): """Returns a new list after removing any non-true values""" use_comma = True if len(args) == 1 and isinstance(args[0], List): use_comma = args[0].use_comma args = args[0] return List( [arg for arg in args if arg], use_comma=use_comma, )
[ "def", "compact", "(", "*", "args", ")", ":", "use_comma", "=", "True", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "List", ")", ":", "use_comma", "=", "args", "[", "0", "]", ".", "use_comma", ...
Returns a new list after removing any non-true values
[ "Returns", "a", "new", "list", "after", "removing", "any", "non", "-", "true", "values" ]
python
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L1843-L1863
def Emulation_setNavigatorOverrides(self, platform): """ Function path: Emulation.setNavigatorOverrides Domain: Emulation Method name: setNavigatorOverrides WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'platform' (type: string) -> The platform navigator.platform should return. No return value. Description: Overrides value returned by the javascript navigator object. """ assert isinstance(platform, (str,) ), "Argument 'platform' must be of type '['str']'. Received type: '%s'" % type( platform) subdom_funcs = self.synchronous_command('Emulation.setNavigatorOverrides', platform=platform) return subdom_funcs
[ "def", "Emulation_setNavigatorOverrides", "(", "self", ",", "platform", ")", ":", "assert", "isinstance", "(", "platform", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'platform' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "platform", ")",...
Function path: Emulation.setNavigatorOverrides Domain: Emulation Method name: setNavigatorOverrides WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'platform' (type: string) -> The platform navigator.platform should return. No return value. Description: Overrides value returned by the javascript navigator object.
[ "Function", "path", ":", "Emulation", ".", "setNavigatorOverrides", "Domain", ":", "Emulation", "Method", "name", ":", "setNavigatorOverrides", "WARNING", ":", "This", "function", "is", "marked", "Experimental", "!", "Parameters", ":", "Required", "arguments", ":", ...
python
train
rbw/flask-journey
flask_journey/journey.py
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L135-L154
def _register_blueprint(self, app, bp, bundle_path, child_path, description): """Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path :return: Dict with info about the blueprint """ base_path = sanitize_path(self._journey_path + bundle_path + child_path) app.register_blueprint(bp, url_prefix=base_path) return { 'name': bp.name, 'path': child_path, 'import_name': bp.import_name, 'description': description, 'routes': self.get_blueprint_routes(app, base_path) }
[ "def", "_register_blueprint", "(", "self", ",", "app", ",", "bp", ",", "bundle_path", ",", "child_path", ",", "description", ")", ":", "base_path", "=", "sanitize_path", "(", "self", ".", "_journey_path", "+", "bundle_path", "+", "child_path", ")", "app", "....
Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path :return: Dict with info about the blueprint
[ "Register", "and", "return", "info", "about", "the", "registered", "blueprint" ]
python
valid
PyCQA/astroid
astroid/node_classes.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L3780-L3792
def raises_not_implemented(self): """Check if this node raises a :class:`NotImplementedError`. :returns: True if this node raises a :class:`NotImplementedError`, False otherwise. :rtype: bool """ if not self.exc: return False for name in self.exc._get_name_nodes(): if name.name == "NotImplementedError": return True return False
[ "def", "raises_not_implemented", "(", "self", ")", ":", "if", "not", "self", ".", "exc", ":", "return", "False", "for", "name", "in", "self", ".", "exc", ".", "_get_name_nodes", "(", ")", ":", "if", "name", ".", "name", "==", "\"NotImplementedError\"", "...
Check if this node raises a :class:`NotImplementedError`. :returns: True if this node raises a :class:`NotImplementedError`, False otherwise. :rtype: bool
[ "Check", "if", "this", "node", "raises", "a", ":", "class", ":", "NotImplementedError", "." ]
python
train
hyperledger/sawtooth-core
rest_api/sawtooth_rest_api/state_delta_subscription_handler.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/rest_api/sawtooth_rest_api/state_delta_subscription_handler.py#L88-L117
async def subscriptions(self, request): """ Handles requests for new subscription websockets. Args: request (aiohttp.Request): the incoming request Returns: aiohttp.web.WebSocketResponse: the websocket response, when the resulting websocket is closed """ if not self._accepting: return web.Response(status=503) web_sock = web.WebSocketResponse() await web_sock.prepare(request) async for msg in web_sock: if msg.type == aiohttp.WSMsgType.TEXT: await self._handle_message(web_sock, msg.data) elif msg.type == aiohttp.WSMsgType.ERROR: LOGGER.warning( 'Web socket connection closed with exception %s', web_sock.exception()) await web_sock.close() await self._handle_unsubscribe(web_sock) return web_sock
[ "async", "def", "subscriptions", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "_accepting", ":", "return", "web", ".", "Response", "(", "status", "=", "503", ")", "web_sock", "=", "web", ".", "WebSocketResponse", "(", ")", "await", ...
Handles requests for new subscription websockets. Args: request (aiohttp.Request): the incoming request Returns: aiohttp.web.WebSocketResponse: the websocket response, when the resulting websocket is closed
[ "Handles", "requests", "for", "new", "subscription", "websockets", "." ]
python
train
pkgw/pwkit
pwkit/numutil.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/numutil.py#L283-L348
def reduce_data_frame (df, chunk_slicers, avg_cols=(), uavg_cols=(), minmax_cols=(), nchunk_colname='nchunk', uncert_prefix='u', min_points_per_chunk=3): """"Reduce" a DataFrame by collapsing rows in grouped chunks. Returns another DataFrame with similar columns but fewer rows. Arguments: df The input :class:`pandas.DataFrame`. chunk_slicers An iterable that returns values that are used to slice *df* with its :meth:`pandas.DataFrame.iloc` indexer. An example value might be the generator returned from :func:`slice_evenly_with_gaps`. avg_cols An iterable of names of columns that are to be reduced by taking the mean. uavg_cols An iterable of names of columns that are to be reduced by taking a weighted mean. minmax_cols An iterable of names of columns that are to be reduced by reporting minimum and maximum values. nchunk_colname The name of a column to create reporting the number of rows contributing to each chunk. uncert_prefix The column name prefix for locating uncertainty estimates. By default, the uncertainty on the column ``"temp"`` is given in the column ``"utemp"``. min_points_per_chunk Require at least this many rows in each chunk. Smaller chunks are discarded. Returns a new :class:`pandas.DataFrame`. """ subds = [df.iloc[idx] for idx in chunk_slicers] subds = [sd for sd in subds if sd.shape[0] >= min_points_per_chunk] chunked = df.__class__ ({nchunk_colname: np.zeros (len (subds), dtype=np.int)}) # Some future-proofing: allow possibility of different ways of mapping # from a column giving a value to a column giving its uncertainty. uncert_col_name = lambda c: uncert_prefix + c for i, subd in enumerate (subds): label = chunked.index[i] chunked.loc[label,nchunk_colname] = subd.shape[0] for col in avg_cols: chunked.loc[label,col] = subd[col].mean () for col in uavg_cols: ucol = uncert_col_name (col) v, u = weighted_mean (subd[col], subd[ucol]) chunked.loc[label,col] = v chunked.loc[label,ucol] = u for col in minmax_cols: chunked.loc[label, 'min_'+col] = subd[col].min () chunked.loc[label, 'max_'+col] = subd[col].max () return chunked
[ "def", "reduce_data_frame", "(", "df", ",", "chunk_slicers", ",", "avg_cols", "=", "(", ")", ",", "uavg_cols", "=", "(", ")", ",", "minmax_cols", "=", "(", ")", ",", "nchunk_colname", "=", "'nchunk'", ",", "uncert_prefix", "=", "'u'", ",", "min_points_per_...
Reduce" a DataFrame by collapsing rows in grouped chunks. Returns another DataFrame with similar columns but fewer rows. Arguments: df The input :class:`pandas.DataFrame`. chunk_slicers An iterable that returns values that are used to slice *df* with its :meth:`pandas.DataFrame.iloc` indexer. An example value might be the generator returned from :func:`slice_evenly_with_gaps`. avg_cols An iterable of names of columns that are to be reduced by taking the mean. uavg_cols An iterable of names of columns that are to be reduced by taking a weighted mean. minmax_cols An iterable of names of columns that are to be reduced by reporting minimum and maximum values. nchunk_colname The name of a column to create reporting the number of rows contributing to each chunk. uncert_prefix The column name prefix for locating uncertainty estimates. By default, the uncertainty on the column ``"temp"`` is given in the column ``"utemp"``. min_points_per_chunk Require at least this many rows in each chunk. Smaller chunks are discarded. Returns a new :class:`pandas.DataFrame`.
[ "Reduce", "a", "DataFrame", "by", "collapsing", "rows", "in", "grouped", "chunks", ".", "Returns", "another", "DataFrame", "with", "similar", "columns", "but", "fewer", "rows", "." ]
python
train
Dallinger/Dallinger
dallinger/notifications.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/notifications.py#L42-L52
def validate(self): """Could this config be used to send a real email?""" missing = [] for k, v in self._map.items(): attr = getattr(self, k, False) if not attr or attr == CONFIG_PLACEHOLDER: missing.append(v) if missing: return "Missing or invalid config values: {}".format( ", ".join(sorted(missing)) )
[ "def", "validate", "(", "self", ")", ":", "missing", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "_map", ".", "items", "(", ")", ":", "attr", "=", "getattr", "(", "self", ",", "k", ",", "False", ")", "if", "not", "attr", "or", "at...
Could this config be used to send a real email?
[ "Could", "this", "config", "be", "used", "to", "send", "a", "real", "email?" ]
python
train
lk-geimfari/mimesis
mimesis/providers/date.py
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L229-L243
def formatted_datetime(self, fmt: str = '', **kwargs) -> str: """Generate datetime string in human readable format. :param fmt: Custom format (default is format for current locale) :param kwargs: Keyword arguments for :meth:`~Datetime.datetime()` :return: Formatted datetime string. """ dt_obj = self.datetime(**kwargs) if not fmt: date_fmt = self._data['formats'].get('date') time_fmt = self._data['formats'].get('time') fmt = '{} {}'.format(date_fmt, time_fmt) return dt_obj.strftime(fmt)
[ "def", "formatted_datetime", "(", "self", ",", "fmt", ":", "str", "=", "''", ",", "*", "*", "kwargs", ")", "->", "str", ":", "dt_obj", "=", "self", ".", "datetime", "(", "*", "*", "kwargs", ")", "if", "not", "fmt", ":", "date_fmt", "=", "self", "...
Generate datetime string in human readable format. :param fmt: Custom format (default is format for current locale) :param kwargs: Keyword arguments for :meth:`~Datetime.datetime()` :return: Formatted datetime string.
[ "Generate", "datetime", "string", "in", "human", "readable", "format", "." ]
python
train
toastdriven/alligator
alligator/utils.py
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/utils.py#L49-L67
def import_module(module_name): """ Given a dotted Python path, imports & returns the module. If not found, raises ``UnknownModuleError``. Ex:: mod = import_module('random') :param module_name: The dotted Python path :type module_name: string :returns: module """ try: return importlib.import_module(module_name) except ImportError as err: raise UnknownModuleError(str(err))
[ "def", "import_module", "(", "module_name", ")", ":", "try", ":", "return", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", "as", "err", ":", "raise", "UnknownModuleError", "(", "str", "(", "err", ")", ")" ]
Given a dotted Python path, imports & returns the module. If not found, raises ``UnknownModuleError``. Ex:: mod = import_module('random') :param module_name: The dotted Python path :type module_name: string :returns: module
[ "Given", "a", "dotted", "Python", "path", "imports", "&", "returns", "the", "module", "." ]
python
train
tgsmith61591/pmdarima
pmdarima/preprocessing/endog/boxcox.py
https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/preprocessing/endog/boxcox.py#L52-L80
def fit(self, y, exogenous=None): """Fit the transformer Learns the value of ``lmbda``, if not specified in the constructor. If defined in the constructor, is not re-learned. Parameters ---------- y : array-like or None, shape=(n_samples,) The endogenous (time-series) array. exogenous : array-like or None, shape=(n_samples, n_features), optional The exogenous array of additional covariates. Not used for endogenous transformers. Default is None, and non-None values will serve as pass-through arrays. """ lam1 = self.lmbda lam2 = self.lmbda2 if lam2 < 0: raise ValueError("lmbda2 must be a non-negative scalar value") if lam1 is None: y, _ = self._check_y_exog(y, exogenous) _, lam1 = stats.boxcox(y, lmbda=None, alpha=None) self.lam1_ = lam1 self.lam2_ = lam2 return self
[ "def", "fit", "(", "self", ",", "y", ",", "exogenous", "=", "None", ")", ":", "lam1", "=", "self", ".", "lmbda", "lam2", "=", "self", ".", "lmbda2", "if", "lam2", "<", "0", ":", "raise", "ValueError", "(", "\"lmbda2 must be a non-negative scalar value\"", ...
Fit the transformer Learns the value of ``lmbda``, if not specified in the constructor. If defined in the constructor, is not re-learned. Parameters ---------- y : array-like or None, shape=(n_samples,) The endogenous (time-series) array. exogenous : array-like or None, shape=(n_samples, n_features), optional The exogenous array of additional covariates. Not used for endogenous transformers. Default is None, and non-None values will serve as pass-through arrays.
[ "Fit", "the", "transformer" ]
python
train
blockstack/blockstack-core
blockstack/blockstackd.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1498-L1508
def rpc_get_num_names_cumulative( self, **con_info ): """ Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error """ db = get_db_state(self.working_dir) num_names = db.get_num_names(include_expired=True) db.close() return self.success_response( {'count': num_names} )
[ "def", "rpc_get_num_names_cumulative", "(", "self", ",", "*", "*", "con_info", ")", ":", "db", "=", "get_db_state", "(", "self", ".", "working_dir", ")", "num_names", "=", "db", ".", "get_num_names", "(", "include_expired", "=", "True", ")", "db", ".", "cl...
Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error
[ "Get", "the", "number", "of", "names", "that", "have", "ever", "existed", "Return", "{", "status", ":", "True", "count", ":", "count", "}", "on", "success", "Return", "{", "error", ":", "...", "}", "on", "error" ]
python
train
pandas-dev/pandas
pandas/util/_decorators.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/util/_decorators.py#L324-L351
def make_signature(func): """ Returns a tuple containing the paramenter list with defaults and parameter list. Examples -------- >>> def f(a, b, c=2): >>> return a * b * c >>> print(make_signature(f)) (['a', 'b', 'c=2'], ['a', 'b', 'c']) """ spec = inspect.getfullargspec(func) if spec.defaults is None: n_wo_defaults = len(spec.args) defaults = ('',) * n_wo_defaults else: n_wo_defaults = len(spec.args) - len(spec.defaults) defaults = ('',) * n_wo_defaults + tuple(spec.defaults) args = [] for var, default in zip(spec.args, defaults): args.append(var if default == '' else var + '=' + repr(default)) if spec.varargs: args.append('*' + spec.varargs) if spec.varkw: args.append('**' + spec.varkw) return args, spec.args
[ "def", "make_signature", "(", "func", ")", ":", "spec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "if", "spec", ".", "defaults", "is", "None", ":", "n_wo_defaults", "=", "len", "(", "spec", ".", "args", ")", "defaults", "=", "(", "''", ...
Returns a tuple containing the paramenter list with defaults and parameter list. Examples -------- >>> def f(a, b, c=2): >>> return a * b * c >>> print(make_signature(f)) (['a', 'b', 'c=2'], ['a', 'b', 'c'])
[ "Returns", "a", "tuple", "containing", "the", "paramenter", "list", "with", "defaults", "and", "parameter", "list", "." ]
python
train
obriencj/python-javatools
javatools/manifest.py
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L287-L295
def get_data(self, linesep=os.linesep): """ Serialize the section and return it as bytes :return bytes """ stream = BytesIO() self.store(stream, linesep) return stream.getvalue()
[ "def", "get_data", "(", "self", ",", "linesep", "=", "os", ".", "linesep", ")", ":", "stream", "=", "BytesIO", "(", ")", "self", ".", "store", "(", "stream", ",", "linesep", ")", "return", "stream", ".", "getvalue", "(", ")" ]
Serialize the section and return it as bytes :return bytes
[ "Serialize", "the", "section", "and", "return", "it", "as", "bytes", ":", "return", "bytes" ]
python
train
boriel/zxbasic
zxbpp.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L517-L527
def p_ifdef_else_a(p): """ ifdefelsea : if_header NEWLINE program """ global ENABLED if ENABLED: p[0] = [p[2]] + p[3] else: p[0] = [] ENABLED = not ENABLED
[ "def", "p_ifdef_else_a", "(", "p", ")", ":", "global", "ENABLED", "if", "ENABLED", ":", "p", "[", "0", "]", "=", "[", "p", "[", "2", "]", "]", "+", "p", "[", "3", "]", "else", ":", "p", "[", "0", "]", "=", "[", "]", "ENABLED", "=", "not", ...
ifdefelsea : if_header NEWLINE program
[ "ifdefelsea", ":", "if_header", "NEWLINE", "program" ]
python
train
splunk/splunk-sdk-python
examples/analytics/bottle.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L613-L615
def delete(self, path=None, method='DELETE', **options): """ Equals :meth:`route` with a ``DELETE`` method parameter. """ return self.route(path, method, **options)
[ "def", "delete", "(", "self", ",", "path", "=", "None", ",", "method", "=", "'DELETE'", ",", "*", "*", "options", ")", ":", "return", "self", ".", "route", "(", "path", ",", "method", ",", "*", "*", "options", ")" ]
Equals :meth:`route` with a ``DELETE`` method parameter.
[ "Equals", ":", "meth", ":", "route", "with", "a", "DELETE", "method", "parameter", "." ]
python
train
google/grr
grr/server/grr_response_server/databases/mem_cronjobs.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_cronjobs.py#L44-L65
def UpdateCronJob(self, cronjob_id, last_run_status=db.Database.unchanged, last_run_time=db.Database.unchanged, current_run_id=db.Database.unchanged, state=db.Database.unchanged, forced_run_requested=db.Database.unchanged): """Updates run information for an existing cron job.""" job = self.cronjobs.get(cronjob_id) if job is None: raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id) if last_run_status != db.Database.unchanged: job.last_run_status = last_run_status if last_run_time != db.Database.unchanged: job.last_run_time = last_run_time if current_run_id != db.Database.unchanged: job.current_run_id = current_run_id if state != db.Database.unchanged: job.state = state if forced_run_requested != db.Database.unchanged: job.forced_run_requested = forced_run_requested
[ "def", "UpdateCronJob", "(", "self", ",", "cronjob_id", ",", "last_run_status", "=", "db", ".", "Database", ".", "unchanged", ",", "last_run_time", "=", "db", ".", "Database", ".", "unchanged", ",", "current_run_id", "=", "db", ".", "Database", ".", "unchang...
Updates run information for an existing cron job.
[ "Updates", "run", "information", "for", "an", "existing", "cron", "job", "." ]
python
train
KeepSafe/android-resource-remover
android_clean_app.py
https://github.com/KeepSafe/android-resource-remover/blob/f2b4fb5a6822da79c9b166e3250ca6bdc6ee06e8/android_clean_app.py#L87-L105
def run_lint_command(): """ Run lint command in the shell and save results to lint-result.xml """ lint, app_dir, lint_result, ignore_layouts = parse_args() if not lint_result: if not distutils.spawn.find_executable(lint): raise Exception( '`%s` executable could not be found and path to lint result not specified. See --help' % lint) lint_result = os.path.join(app_dir, 'lint-result.xml') call_result = subprocess.call([lint, app_dir, '--xml', lint_result]) if call_result > 0: print('Running the command failed with result %s. Try running it from the console.' ' Arguments for subprocess.call: %s' % (call_result, [lint, app_dir, '--xml', lint_result])) else: if not os.path.isabs(lint_result): lint_result = os.path.join(app_dir, lint_result) lint_result = os.path.abspath(lint_result) return lint_result, app_dir, ignore_layouts
[ "def", "run_lint_command", "(", ")", ":", "lint", ",", "app_dir", ",", "lint_result", ",", "ignore_layouts", "=", "parse_args", "(", ")", "if", "not", "lint_result", ":", "if", "not", "distutils", ".", "spawn", ".", "find_executable", "(", "lint", ")", ":"...
Run lint command in the shell and save results to lint-result.xml
[ "Run", "lint", "command", "in", "the", "shell", "and", "save", "results", "to", "lint", "-", "result", ".", "xml" ]
python
train
noxdafox/vminspect
vminspect/vulnscan.py
https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/vulnscan.py#L68-L99
def scan(self, concurrency=1): """Iterates over the applications installed within the disk and queries the CVE DB to determine whether they are vulnerable. Concurrency controls the amount of concurrent queries against the CVE DB. For each vulnerable application the method yields a namedtuple: VulnApp(name -> application name version -> application version vulnerabilities) -> list of Vulnerabilities Vulnerability(id -> CVE Id summary) -> brief description of the vulnerability """ self.logger.debug("Scanning FS content.") with ThreadPoolExecutor(max_workers=concurrency) as executor: results = executor.map(self.query_vulnerabilities, self.applications()) for report in results: application, vulnerabilities = report vulnerabilities = list(lookup_vulnerabilities(application.version, vulnerabilities)) if vulnerabilities: yield VulnApp(application.name, application.version, vulnerabilities)
[ "def", "scan", "(", "self", ",", "concurrency", "=", "1", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Scanning FS content.\"", ")", "with", "ThreadPoolExecutor", "(", "max_workers", "=", "concurrency", ")", "as", "executor", ":", "results", "=", ...
Iterates over the applications installed within the disk and queries the CVE DB to determine whether they are vulnerable. Concurrency controls the amount of concurrent queries against the CVE DB. For each vulnerable application the method yields a namedtuple: VulnApp(name -> application name version -> application version vulnerabilities) -> list of Vulnerabilities Vulnerability(id -> CVE Id summary) -> brief description of the vulnerability
[ "Iterates", "over", "the", "applications", "installed", "within", "the", "disk", "and", "queries", "the", "CVE", "DB", "to", "determine", "whether", "they", "are", "vulnerable", "." ]
python
train
GNS3/gns3-server
gns3server/compute/builtin/nodes/ethernet_hub.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/ethernet_hub.py#L48-L54
def create(self): """ Creates this hub. """ super().create() log.info('Ethernet hub "{name}" [{id}] has been created'.format(name=self._name, id=self._id))
[ "def", "create", "(", "self", ")", ":", "super", "(", ")", ".", "create", "(", ")", "log", ".", "info", "(", "'Ethernet hub \"{name}\" [{id}] has been created'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ...
Creates this hub.
[ "Creates", "this", "hub", "." ]
python
train
textX/textX
textx/metamodel.py
https://github.com/textX/textX/blob/5796ac38116ad86584392dbecdbf923ede746361/textx/metamodel.py#L222-L235
def _enter_namespace(self, namespace_name): """ A namespace is usually an absolute file name of the grammar. A special namespace '__base__' is used for BASETYPE namespace. """ if namespace_name not in self.namespaces: self.namespaces[namespace_name] = {} # BASETYPE namespace is imported in each namespace # as the first namespace to be searched. self._imported_namespaces[namespace_name] = \ [self.namespaces['__base__']] self._namespace_stack.append(namespace_name)
[ "def", "_enter_namespace", "(", "self", ",", "namespace_name", ")", ":", "if", "namespace_name", "not", "in", "self", ".", "namespaces", ":", "self", ".", "namespaces", "[", "namespace_name", "]", "=", "{", "}", "# BASETYPE namespace is imported in each namespace", ...
A namespace is usually an absolute file name of the grammar. A special namespace '__base__' is used for BASETYPE namespace.
[ "A", "namespace", "is", "usually", "an", "absolute", "file", "name", "of", "the", "grammar", ".", "A", "special", "namespace", "__base__", "is", "used", "for", "BASETYPE", "namespace", "." ]
python
train
noirbizarre/django.js
djangojs/context_serializer.py
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/context_serializer.py#L37-L57
def as_dict(self): ''' Serialize the context as a dictionnary from a given request. ''' data = {} if settings.JS_CONTEXT_ENABLED: for context in RequestContext(self.request): for key, value in six.iteritems(context): if settings.JS_CONTEXT and key not in settings.JS_CONTEXT: continue if settings.JS_CONTEXT_EXCLUDE and key in settings.JS_CONTEXT_EXCLUDE: continue handler_name = 'process_%s' % key if hasattr(self, handler_name): handler = getattr(self, handler_name) data[key] = handler(value, data) elif isinstance(value, SERIALIZABLE_TYPES): data[key] = value if settings.JS_USER_ENABLED: self.handle_user(data) return data
[ "def", "as_dict", "(", "self", ")", ":", "data", "=", "{", "}", "if", "settings", ".", "JS_CONTEXT_ENABLED", ":", "for", "context", "in", "RequestContext", "(", "self", ".", "request", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems"...
Serialize the context as a dictionnary from a given request.
[ "Serialize", "the", "context", "as", "a", "dictionnary", "from", "a", "given", "request", "." ]
python
train
juju/python-libjuju
juju/user.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/user.py#L62-L68
async def grant(self, acl='login'): """Set access level of this user on the controller. :param str acl: Access control ('login', 'add-model', or 'superuser') """ if await self.controller.grant(self.username, acl): self._user_info.access = acl
[ "async", "def", "grant", "(", "self", ",", "acl", "=", "'login'", ")", ":", "if", "await", "self", ".", "controller", ".", "grant", "(", "self", ".", "username", ",", "acl", ")", ":", "self", ".", "_user_info", ".", "access", "=", "acl" ]
Set access level of this user on the controller. :param str acl: Access control ('login', 'add-model', or 'superuser')
[ "Set", "access", "level", "of", "this", "user", "on", "the", "controller", "." ]
python
train
mdsol/rwslib
rwslib/builders/clinicaldata.py
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/clinicaldata.py#L984-L990
def build(self, builder): """ Build XML by appending to builder """ builder.start("SourceID", {}) builder.data(self.source_id) builder.end("SourceID")
[ "def", "build", "(", "self", ",", "builder", ")", ":", "builder", ".", "start", "(", "\"SourceID\"", ",", "{", "}", ")", "builder", ".", "data", "(", "self", ".", "source_id", ")", "builder", ".", "end", "(", "\"SourceID\"", ")" ]
Build XML by appending to builder
[ "Build", "XML", "by", "appending", "to", "builder" ]
python
train
tensorflow/skflow
scripts/docs/docs.py
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L503-L511
def assert_no_leftovers(self): """Generate an error if there are leftover members.""" leftovers = [] for name in self._members.keys(): if name in self._members and name not in self._documented: leftovers.append(name) if leftovers: raise RuntimeError("%s: undocumented members: %s" % (self._title, ", ".join(leftovers)))
[ "def", "assert_no_leftovers", "(", "self", ")", ":", "leftovers", "=", "[", "]", "for", "name", "in", "self", ".", "_members", ".", "keys", "(", ")", ":", "if", "name", "in", "self", ".", "_members", "and", "name", "not", "in", "self", ".", "_documen...
Generate an error if there are leftover members.
[ "Generate", "an", "error", "if", "there", "are", "leftover", "members", "." ]
python
train
GemHQ/round-py
round/wallets.py
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L431-L447
def signatures(self, transaction): """Sign a transaction. Args: transaction (coinop.Transaction) Returns: A list of signature dicts of the form [ {'primary': 'base58signaturestring'}, ... ] """ # TODO: output.metadata['type']['change'] if not self.multi_wallet: raise DecryptionError("This wallet must be unlocked with " "wallet.unlock(passphrase)") return self.multi_wallet.signatures(transaction)
[ "def", "signatures", "(", "self", ",", "transaction", ")", ":", "# TODO: output.metadata['type']['change']", "if", "not", "self", ".", "multi_wallet", ":", "raise", "DecryptionError", "(", "\"This wallet must be unlocked with \"", "\"wallet.unlock(passphrase)\"", ")", "retu...
Sign a transaction. Args: transaction (coinop.Transaction) Returns: A list of signature dicts of the form [ {'primary': 'base58signaturestring'}, ... ]
[ "Sign", "a", "transaction", "." ]
python
train
metagriffin/morph
morph/__init__.py
https://github.com/metagriffin/morph/blob/907f169b0155712c466d3aac29f0907d0f36b443/morph/__init__.py#L147-L175
def unflatten(obj): ''' TODO: add docs ''' if not isdict(obj): raise ValueError( 'only dict-like objects can be unflattened, not %r' % (obj,)) ret = dict() sub = dict() for key, value in obj.items(): if '.' not in key and '[' not in key: ret[key] = value continue if '.' in key and '[' in key: idx = min(key.find('.'), key.find('[')) elif '.' in key: idx = key.find('.') else: idx = key.find('[') prefix = key[:idx] if prefix not in sub: sub[prefix] = dict() sub[prefix][key[idx:]] = value for pfx, values in sub.items(): if pfx in ret: raise ValueError( 'conflicting scalar vs. structure for prefix: %s' % (pfx,)) ret[pfx] = _relunflatten(pfx, values) return ret
[ "def", "unflatten", "(", "obj", ")", ":", "if", "not", "isdict", "(", "obj", ")", ":", "raise", "ValueError", "(", "'only dict-like objects can be unflattened, not %r'", "%", "(", "obj", ",", ")", ")", "ret", "=", "dict", "(", ")", "sub", "=", "dict", "(...
TODO: add docs
[ "TODO", ":", "add", "docs" ]
python
train
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L688-L736
def mount_iso_image(self, image, image_name, ins_file_name): """ Upload an ISO image and associate it to this Partition using the HMC operation 'Mount ISO Image'. When the partition already has an ISO image associated, the newly uploaded image replaces the current one. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: image (:term:`byte string` or file-like object): The content of the ISO image. Images larger than 2GB cannot be specified as a Byte string; they must be specified as a file-like object. File-like objects must have opened the file in binary mode. image_name (:term:`string`): The displayable name of the image. This value must be a valid Linux file name without directories, must not contain blanks, and must end with '.iso' in lower case. This value will be shown in the 'boot-iso-image-name' property of this partition. ins_file_name (:term:`string`): The path name of the INS file within the file system of the ISO image. This value will be shown in the 'boot-iso-ins-file' property of this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ query_parms_str = '?image-name={}&ins-file-name={}'. \ format(quote(image_name, safe=''), quote(ins_file_name, safe='')) self.manager.session.post( self.uri + '/operations/mount-iso-image' + query_parms_str, body=image)
[ "def", "mount_iso_image", "(", "self", ",", "image", ",", "image_name", ",", "ins_file_name", ")", ":", "query_parms_str", "=", "'?image-name={}&ins-file-name={}'", ".", "format", "(", "quote", "(", "image_name", ",", "safe", "=", "''", ")", ",", "quote", "(",...
Upload an ISO image and associate it to this Partition using the HMC operation 'Mount ISO Image'. When the partition already has an ISO image associated, the newly uploaded image replaces the current one. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: image (:term:`byte string` or file-like object): The content of the ISO image. Images larger than 2GB cannot be specified as a Byte string; they must be specified as a file-like object. File-like objects must have opened the file in binary mode. image_name (:term:`string`): The displayable name of the image. This value must be a valid Linux file name without directories, must not contain blanks, and must end with '.iso' in lower case. This value will be shown in the 'boot-iso-image-name' property of this partition. ins_file_name (:term:`string`): The path name of the INS file within the file system of the ISO image. This value will be shown in the 'boot-iso-ins-file' property of this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Upload", "an", "ISO", "image", "and", "associate", "it", "to", "this", "Partition", "using", "the", "HMC", "operation", "Mount", "ISO", "Image", "." ]
python
train
jborean93/smbprotocol
smbprotocol/connection.py
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1364-L1408
def _calculate_credit_charge(self, message): """ Calculates the credit charge for a request based on the command. If connection.supports_multi_credit is not True then the credit charge isn't valid so it returns 0. The credit charge is the number of credits that are required for sending/receiving data over 64 kilobytes, in the existing messages only the Read, Write, Query Directory or IOCTL commands will end in this scenario and each require their own calculation to get the proper value. The generic formula for calculating the credit charge is https://msdn.microsoft.com/en-us/library/dn529312.aspx (max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1 :param message: The message being sent :return: The credit charge to set on the header """ credit_size = 65536 if not self.supports_multi_credit: credit_charge = 0 elif message.COMMAND == Commands.SMB2_READ: max_size = message['length'].get_value() + \ message['read_channel_info_length'].get_value() - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_WRITE: max_size = message['length'].get_value() + \ message['write_channel_info_length'].get_value() - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_IOCTL: max_in_size = len(message['buffer']) max_out_size = message['max_output_response'].get_value() max_size = max(max_in_size, max_out_size) - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_QUERY_DIRECTORY: max_in_size = len(message['buffer']) max_out_size = message['output_buffer_length'].get_value() max_size = max(max_in_size, max_out_size) - 1 credit_charge = math.ceil(max_size / credit_size) else: credit_charge = 1 # python 2 returns a float where we need an integer return int(credit_charge)
[ "def", "_calculate_credit_charge", "(", "self", ",", "message", ")", ":", "credit_size", "=", "65536", "if", "not", "self", ".", "supports_multi_credit", ":", "credit_charge", "=", "0", "elif", "message", ".", "COMMAND", "==", "Commands", ".", "SMB2_READ", ":"...
Calculates the credit charge for a request based on the command. If connection.supports_multi_credit is not True then the credit charge isn't valid so it returns 0. The credit charge is the number of credits that are required for sending/receiving data over 64 kilobytes, in the existing messages only the Read, Write, Query Directory or IOCTL commands will end in this scenario and each require their own calculation to get the proper value. The generic formula for calculating the credit charge is https://msdn.microsoft.com/en-us/library/dn529312.aspx (max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1 :param message: The message being sent :return: The credit charge to set on the header
[ "Calculates", "the", "credit", "charge", "for", "a", "request", "based", "on", "the", "command", ".", "If", "connection", ".", "supports_multi_credit", "is", "not", "True", "then", "the", "credit", "charge", "isn", "t", "valid", "so", "it", "returns", "0", ...
python
train
ethpm/py-ethpm
ethpm/utils/deployments.py
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/deployments.py#L31-L53
def validate_linked_references( link_deps: Tuple[Tuple[int, bytes], ...], bytecode: bytes ) -> None: """ Validates that normalized linked_references (offset, expected_bytes) match the corresponding bytecode. """ offsets, values = zip(*link_deps) for idx, offset in enumerate(offsets): value = values[idx] # https://github.com/python/mypy/issues/4975 offset_value = int(offset) dep_length = len(value) end_of_bytes = offset_value + dep_length # Ignore b/c whitespace around ':' conflict b/w black & flake8 actual_bytes = bytecode[offset_value:end_of_bytes] # noqa: E203 if actual_bytes != values[idx]: raise ValidationError( "Error validating linked reference. " f"Offset: {offset} " f"Value: {values[idx]} " f"Bytecode: {bytecode} ." )
[ "def", "validate_linked_references", "(", "link_deps", ":", "Tuple", "[", "Tuple", "[", "int", ",", "bytes", "]", ",", "...", "]", ",", "bytecode", ":", "bytes", ")", "->", "None", ":", "offsets", ",", "values", "=", "zip", "(", "*", "link_deps", ")", ...
Validates that normalized linked_references (offset, expected_bytes) match the corresponding bytecode.
[ "Validates", "that", "normalized", "linked_references", "(", "offset", "expected_bytes", ")", "match", "the", "corresponding", "bytecode", "." ]
python
train
googlefonts/fontbakery
Lib/fontbakery/profiles/googlefonts.py
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L691-L714
def com_google_fonts_check_usweightclass(font, ttFont, style): """Checking OS/2 usWeightClass.""" from fontbakery.profiles.shared_conditions import is_ttf weight_name, expected_value = expected_os2_weight(style) value = ttFont['OS/2'].usWeightClass if value != expected_value: if is_ttf(ttFont) and \ (weight_name == 'Thin' and value == 100) or \ (weight_name == 'ExtraLight' and value == 200): yield WARN, ("{}:{} is OK on TTFs, but OTF files with those values" " will cause bluring on Windows." " GlyphsApp users must set a Instance Custom Parameter" " for the Thin and ExtraLight styles to 250 and 275," " so that if OTFs are exported then it will not" " blur on Windows.") else: yield FAIL, ("OS/2 usWeightClass expected value for" " '{}' is {} but this font has" " {}.").format(weight_name, expected_value, value) else: yield PASS, "OS/2 usWeightClass value looks good!"
[ "def", "com_google_fonts_check_usweightclass", "(", "font", ",", "ttFont", ",", "style", ")", ":", "from", "fontbakery", ".", "profiles", ".", "shared_conditions", "import", "is_ttf", "weight_name", ",", "expected_value", "=", "expected_os2_weight", "(", "style", ")...
Checking OS/2 usWeightClass.
[ "Checking", "OS", "/", "2", "usWeightClass", "." ]
python
train
python/core-workflow
cherry_picker/cherry_picker/cherry_picker.py
https://github.com/python/core-workflow/blob/b93c76195f6db382cfcefee334380fb4c68d4e21/cherry_picker/cherry_picker/cherry_picker.py#L168-L173
def fetch_upstream(self): """ git fetch <upstream> """ set_state(WORKFLOW_STATES.FETCHING_UPSTREAM) cmd = ["git", "fetch", self.upstream] self.run_cmd(cmd) set_state(WORKFLOW_STATES.FETCHED_UPSTREAM)
[ "def", "fetch_upstream", "(", "self", ")", ":", "set_state", "(", "WORKFLOW_STATES", ".", "FETCHING_UPSTREAM", ")", "cmd", "=", "[", "\"git\"", ",", "\"fetch\"", ",", "self", ".", "upstream", "]", "self", ".", "run_cmd", "(", "cmd", ")", "set_state", "(", ...
git fetch <upstream>
[ "git", "fetch", "<upstream", ">" ]
python
train
quarkslab/arybo
arybo/lib/mba_if.py
https://github.com/quarkslab/arybo/blob/04fad817090b3b9f2328a5e984457aba6024e971/arybo/lib/mba_if.py#L408-L426
def var(self, name): ''' Get an n-bit named symbolic variable Returns: An :class:`MBAVariable` object representing a symbolic variable Example: >>> mba.var('x') Vec([ x0, x1, x2, x3 ]) ''' ret = self.from_vec(self.var_symbols(name)) ret.name = name return ret
[ "def", "var", "(", "self", ",", "name", ")", ":", "ret", "=", "self", ".", "from_vec", "(", "self", ".", "var_symbols", "(", "name", ")", ")", "ret", ".", "name", "=", "name", "return", "ret" ]
Get an n-bit named symbolic variable Returns: An :class:`MBAVariable` object representing a symbolic variable Example: >>> mba.var('x') Vec([ x0, x1, x2, x3 ])
[ "Get", "an", "n", "-", "bit", "named", "symbolic", "variable" ]
python
train
buildbot/buildbot
worker/buildbot_worker/scripts/create_worker.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/worker/buildbot_worker/scripts/create_worker.py#L142-L195
def _makeInfoFiles(basedir, quiet): """ Create info/* files inside basedir. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making info directory or writing info files """ def createFile(path, file, contents): filepath = os.path.join(path, file) if os.path.exists(filepath): return False if not quiet: print("Creating {0}, you need to edit it appropriately.".format( os.path.join("info", file))) try: open(filepath, "wt").write(contents) except IOError as exception: raise CreateWorkerError("could not write {0}: {1}".format( filepath, exception.strerror)) return True path = os.path.join(basedir, "info") if not os.path.exists(path): if not quiet: print("mkdir", path) try: os.mkdir(path) except OSError as exception: raise CreateWorkerError("error creating directory {0}: {1}".format( path, exception.strerror)) # create 'info/admin' file created = createFile(path, "admin", "Your Name Here <admin@youraddress.invalid>\n") # create 'info/host' file created = createFile(path, "host", "Please put a description of this build host here\n") access_uri = os.path.join(path, "access_uri") if not os.path.exists(access_uri): if not quiet: print("Not creating {0} - add it if you wish".format( os.path.join("info", "access_uri"))) if created and not quiet: print("Please edit the files in {0} appropriately.".format(path))
[ "def", "_makeInfoFiles", "(", "basedir", ",", "quiet", ")", ":", "def", "createFile", "(", "path", ",", "file", ",", "contents", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "file", ")", "if", "os", ".", "path", ".",...
Create info/* files inside basedir. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making info directory or writing info files
[ "Create", "info", "/", "*", "files", "inside", "basedir", "." ]
python
train
bachya/pyopenuv
pyopenuv/client.py
https://github.com/bachya/pyopenuv/blob/f7c2f9dd99dd4e3b8b1f9e501ea17ce62a7ace46/pyopenuv/client.py#L69-L76
async def uv_protection_window( self, low: float = 3.5, high: float = 3.5) -> dict: """Get data on when a UV protection window is.""" return await self.request( 'get', 'protection', params={ 'from': str(low), 'to': str(high) })
[ "async", "def", "uv_protection_window", "(", "self", ",", "low", ":", "float", "=", "3.5", ",", "high", ":", "float", "=", "3.5", ")", "->", "dict", ":", "return", "await", "self", ".", "request", "(", "'get'", ",", "'protection'", ",", "params", "=", ...
Get data on when a UV protection window is.
[ "Get", "data", "on", "when", "a", "UV", "protection", "window", "is", "." ]
python
train
ray-project/ray
python/ray/node.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/node.py#L438-L448
def start_monitor(self): """Start the monitor.""" stdout_file, stderr_file = self.new_log_files("monitor") process_info = ray.services.start_monitor( self._redis_address, stdout_file=stdout_file, stderr_file=stderr_file, autoscaling_config=self._ray_params.autoscaling_config, redis_password=self._ray_params.redis_password) assert ray_constants.PROCESS_TYPE_MONITOR not in self.all_processes self.all_processes[ray_constants.PROCESS_TYPE_MONITOR] = [process_info]
[ "def", "start_monitor", "(", "self", ")", ":", "stdout_file", ",", "stderr_file", "=", "self", ".", "new_log_files", "(", "\"monitor\"", ")", "process_info", "=", "ray", ".", "services", ".", "start_monitor", "(", "self", ".", "_redis_address", ",", "stdout_fi...
Start the monitor.
[ "Start", "the", "monitor", "." ]
python
train
dpkp/kafka-python
kafka/client.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/client.py#L142-L177
def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn): """ Attempt to send a broker-agnostic request to one of the available brokers. Keep trying until you succeed. """ hosts = set() for broker in self.brokers.values(): host, port, afi = get_ip_port_afi(broker.host) hosts.add((host, broker.port, afi)) hosts.update(self.hosts) hosts = list(hosts) random.shuffle(hosts) for (host, port, afi) in hosts: try: conn = self._get_conn(host, port, afi) except KafkaConnectionError: log.warning("Skipping unconnected connection: %s:%s (AFI %s)", host, port, afi) continue request = encoder_fn(payloads=payloads) future = conn.send(request) # Block while not future.is_done: for r, f in conn.recv(): f.success(r) if future.failed(): log.error("Request failed: %s", future.exception) continue return decoder_fn(future.value) raise KafkaUnavailableError('All servers failed to process request: %s' % (hosts,))
[ "def", "_send_broker_unaware_request", "(", "self", ",", "payloads", ",", "encoder_fn", ",", "decoder_fn", ")", ":", "hosts", "=", "set", "(", ")", "for", "broker", "in", "self", ".", "brokers", ".", "values", "(", ")", ":", "host", ",", "port", ",", "...
Attempt to send a broker-agnostic request to one of the available brokers. Keep trying until you succeed.
[ "Attempt", "to", "send", "a", "broker", "-", "agnostic", "request", "to", "one", "of", "the", "available", "brokers", ".", "Keep", "trying", "until", "you", "succeed", "." ]
python
train
sprockets/sprockets
sprockets/cli.py
https://github.com/sprockets/sprockets/blob/089dbaf04da54afd95645fce31f4ff9c8bdd8fae/sprockets/cli.py#L161-L187
def _configure_logging(application, verbosity=0, syslog=False): """Configure logging for the application, setting the appropriate verbosity and adding syslog if it's enabled. :param str application: The application module/package name :param int verbosity: 1 == INFO, 2 == DEBUG :param bool syslog: Enable the syslog handler """ # Create a new copy of the logging config that will be modified config = dict(LOGGING) # Increase the logging verbosity if verbosity == 1: config['loggers']['sprockets']['level'] = logging.INFO elif verbosity == 2: config['loggers']['sprockets']['level'] = logging.DEBUG # Add syslog if it's enabled if syslog: config['loggers']['sprockets']['handlers'].append('syslog') # Copy the sprockets logger to the application config['loggers'][application] = dict(config['loggers']['sprockets']) # Configure logging logging_config.dictConfig(config)
[ "def", "_configure_logging", "(", "application", ",", "verbosity", "=", "0", ",", "syslog", "=", "False", ")", ":", "# Create a new copy of the logging config that will be modified", "config", "=", "dict", "(", "LOGGING", ")", "# Increase the logging verbosity", "if", "...
Configure logging for the application, setting the appropriate verbosity and adding syslog if it's enabled. :param str application: The application module/package name :param int verbosity: 1 == INFO, 2 == DEBUG :param bool syslog: Enable the syslog handler
[ "Configure", "logging", "for", "the", "application", "setting", "the", "appropriate", "verbosity", "and", "adding", "syslog", "if", "it", "s", "enabled", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/extended/ext_seq/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/extended/ext_seq/__init__.py#L912-L933
def _set_src_port_any(self, v, load=False): """ Setter method for src_port_any, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/src_port_any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_src_port_any is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_src_port_any() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="src-port-any", rest_name="src-port-any", parent=self, choice=(u'choice-src-port', u'case-src-port-any'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'src-port-any', u'display-when': u'(../dst-port) or (../dst-port-any)'}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='empty', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """src_port_any must be of a type compatible with empty""", 'defined-type': "empty", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="src-port-any", rest_name="src-port-any", parent=self, choice=(u'choice-src-port', u'case-src-port-any'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'src-port-any', u'display-when': u'(../dst-port) or (../dst-port-any)'}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='empty', is_config=True)""", }) self.__src_port_any = t if hasattr(self, '_set'): self._set()
[ "def", "_set_src_port_any", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
Setter method for src_port_any, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/src_port_any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_src_port_any is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_src_port_any() directly.
[ "Setter", "method", "for", "src_port_any", "mapped", "from", "YANG", "variable", "/", "overlay", "/", "access_list", "/", "type", "/", "vxlan", "/", "extended", "/", "ext_seq", "/", "src_port_any", "(", "empty", ")", "If", "this", "variable", "is", "read", ...
python
train
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_kmlread.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_kmlread.py#L318-L344
def readkmz(self, filename): '''reads in a kmz file and returns xml nodes''' #Strip quotation marks if neccessary filename.strip('"') #Open the zip file (as applicable) if filename[-4:] == '.kml': fo = open(filename, "r") fstring = fo.read() fo.close() elif filename[-4:] == '.kmz': zip=ZipFile(filename) for z in zip.filelist: if z.filename[-4:] == '.kml': fstring=zip.read(z) break else: raise Exception("Could not find kml file in %s" % filename) else: raise Exception("Is not a valid kml or kmz file in %s" % filename) #send into the xml parser kmlstring = parseString(fstring) #get all the placenames nodes=kmlstring.getElementsByTagName('Placemark') return nodes
[ "def", "readkmz", "(", "self", ",", "filename", ")", ":", "#Strip quotation marks if neccessary", "filename", ".", "strip", "(", "'\"'", ")", "#Open the zip file (as applicable) ", "if", "filename", "[", "-", "4", ":", "]", "==", "'.kml'", ":", "fo", "=", "...
reads in a kmz file and returns xml nodes
[ "reads", "in", "a", "kmz", "file", "and", "returns", "xml", "nodes" ]
python
train
jonathanj/txspinneret
txspinneret/route.py
https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L31-L50
def Text(name, encoding=None): """ Match a route parameter. `Any` is a synonym for `Text`. :type name: `bytes` :param name: Route parameter name. :type encoding: `bytes` :param encoding: Default encoding to assume if the ``Content-Type`` header is lacking one. :return: ``callable`` suitable for use with `route` or `subroute`. """ def _match(request, value): return name, query.Text( value, encoding=contentEncoding(request.requestHeaders, encoding)) return _match
[ "def", "Text", "(", "name", ",", "encoding", "=", "None", ")", ":", "def", "_match", "(", "request", ",", "value", ")", ":", "return", "name", ",", "query", ".", "Text", "(", "value", ",", "encoding", "=", "contentEncoding", "(", "request", ".", "req...
Match a route parameter. `Any` is a synonym for `Text`. :type name: `bytes` :param name: Route parameter name. :type encoding: `bytes` :param encoding: Default encoding to assume if the ``Content-Type`` header is lacking one. :return: ``callable`` suitable for use with `route` or `subroute`.
[ "Match", "a", "route", "parameter", "." ]
python
valid
CivicSpleen/ambry
ambry/identity.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L328-L331
def as_partition(self, **kwargs): """Return a PartitionName based on this name.""" return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items())))
[ "def", "as_partition", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "PartitionName", "(", "*", "*", "dict", "(", "list", "(", "self", ".", "dict", ".", "items", "(", ")", ")", "+", "list", "(", "kwargs", ".", "items", "(", ")", ")", ...
Return a PartitionName based on this name.
[ "Return", "a", "PartitionName", "based", "on", "this", "name", "." ]
python
train
trailofbits/manticore
manticore/utils/config.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/config.py#L105-L112
def get_description(self, name: str) -> str: """ Return the description, or a help string of variable identified by |name|. """ if name not in self._vars: raise ConfigError(f"{self.name}.{name} not defined.") return self._vars[name].description
[ "def", "get_description", "(", "self", ",", "name", ":", "str", ")", "->", "str", ":", "if", "name", "not", "in", "self", ".", "_vars", ":", "raise", "ConfigError", "(", "f\"{self.name}.{name} not defined.\"", ")", "return", "self", ".", "_vars", "[", "nam...
Return the description, or a help string of variable identified by |name|.
[ "Return", "the", "description", "or", "a", "help", "string", "of", "variable", "identified", "by", "|name|", "." ]
python
valid
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6381-L6521
def plot_divers(self, iabscissa=1, foffset=1e-19): """plot fitness, sigma, axis ratio... :param iabscissa: 0 means vs evaluations, 1 means vs iterations :param foffset: added to f-value :See: `plot()` """ from matplotlib.pyplot import semilogy, hold, grid, \ axis, title, text fontsize = pyplot.rcParams['font.size'] if not hasattr(self, 'f'): self.load() dat = self minfit = min(dat.f[:, 5]) dfit = dat.f[:, 5] - minfit # why not using idx? dfit[dfit < 1e-98] = np.NaN self._enter_plotting() if dat.f.shape[1] > 7: # semilogy(dat.f[:, iabscissa], abs(dat.f[:,[6, 7, 10, 12]])+foffset,'-k') semilogy(dat.f[:, iabscissa], abs(dat.f[:, [6, 7]]) + foffset, '-k') hold(True) # (larger indices): additional fitness data, for example constraints values if dat.f.shape[1] > 8: # dd = abs(dat.f[:,7:]) + 10*foffset # dd = np.where(dat.f[:,7:]==0, np.NaN, dd) # cannot be semilogy(dat.f[:, iabscissa], np.abs(dat.f[:, 8:]) + 10 * foffset, 'y') hold(True) idx = np.where(dat.f[:, 5] > 1e-98)[0] # positive values semilogy(dat.f[idx, iabscissa], dat.f[idx, 5] + foffset, '.b') hold(True) grid(True) semilogy(dat.f[:, iabscissa], abs(dat.f[:, 5]) + foffset, '-b') text(dat.f[-1, iabscissa], abs(dat.f[-1, 5]) + foffset, r'$|f_\mathsf{best}|$', fontsize=fontsize + 2) # negative f-values, dots sgn = np.sign(dat.f[:, 5]) sgn[np.abs(dat.f[:, 5]) < 1e-98] = 0 idx = np.where(sgn < 0)[0] semilogy(dat.f[idx, iabscissa], abs(dat.f[idx, 5]) + foffset, '.m') # , markersize=5 # lines between negative f-values dsgn = np.diff(sgn) start_idx = 1 + np.where((dsgn < 0) * (sgn[1:] < 0))[0] stop_idx = 1 + np.where(dsgn > 0)[0] if sgn[0] < 0: start_idx = np.concatenate(([0], start_idx)) for istart in start_idx: istop = stop_idx[stop_idx > istart] istop = istop[0] if len(istop) else 0 idx = xrange(istart, istop if istop else dat.f.shape[0]) if len(idx) > 1: semilogy(dat.f[idx, iabscissa], abs(dat.f[idx, 5]) + foffset, 'm') # , markersize=5 # lines between positive and negative f-values # TODO: the following might plot values very close to zero if istart > 0: # line to the left of istart semilogy(dat.f[istart-1:istart+1, iabscissa], abs(dat.f[istart-1:istart+1, 5]) + foffset, '--m') if istop: # line to the left of istop semilogy(dat.f[istop-1:istop+1, iabscissa], abs(dat.f[istop-1:istop+1, 5]) + foffset, '--m') # mark the respective first positive values semilogy(dat.f[istop, iabscissa], abs(dat.f[istop, 5]) + foffset, '.b', markersize=7) # mark the respective first negative values semilogy(dat.f[istart, iabscissa], abs(dat.f[istart, 5]) + foffset, '.r', markersize=7) # standard deviations std semilogy(dat.std[:-1, iabscissa], np.vstack([list(map(max, dat.std[:-1, 5:])), list(map(min, dat.std[:-1, 5:]))]).T, '-m', linewidth=2) text(dat.std[-2, iabscissa], max(dat.std[-2, 5:]), 'max std', fontsize=fontsize) text(dat.std[-2, iabscissa], min(dat.std[-2, 5:]), 'min std', fontsize=fontsize) # delta-fitness in cyan idx = isfinite(dfit) if 1 < 3: idx_nan = np.where(idx == False)[0] # gaps if not len(idx_nan): # should never happen semilogy(dat.f[:, iabscissa][idx], dfit[idx], '-c') else: i_start = 0 for i_end in idx_nan: if i_end > i_start: semilogy(dat.f[:, iabscissa][i_start:i_end], dfit[i_start:i_end], '-c') i_start = i_end + 1 if len(dfit) > idx_nan[-1] + 1: semilogy(dat.f[:, iabscissa][idx_nan[-1]+1:], dfit[idx_nan[-1]+1:], '-c') text(dat.f[idx, iabscissa][-1], dfit[idx][-1], r'$f_\mathsf{best} - \min(f)$', fontsize=fontsize + 2) # overall minimum i = np.argmin(dat.f[:, 5]) semilogy(dat.f[i, iabscissa], np.abs(dat.f[i, 5]), 'ro', markersize=9) semilogy(dat.f[i, iabscissa], dfit[idx][np.argmin(dfit[idx])] + 1e-98, 'ro', markersize=9) # semilogy(dat.f[-1, iabscissa]*np.ones(2), dat.f[-1,4]*np.ones(2), 'rd') # AR and sigma semilogy(dat.f[:, iabscissa], dat.f[:, 3], '-r') # AR semilogy(dat.f[:, iabscissa], dat.f[:, 2], '-g') # sigma text(dat.f[-1, iabscissa], dat.f[-1, 3], r'axis ratio', fontsize=fontsize) text(dat.f[-1, iabscissa], dat.f[-1, 2] / 1.5, r'$\sigma$', fontsize=fontsize+3) ax = array(axis()) # ax[1] = max(minxend, ax[1]) axis(ax) text(ax[0] + 0.01, ax[2], # 10**(log10(ax[2])+0.05*(log10(ax[3])-log10(ax[2]))), '.min($f$)=' + repr(minfit)) #'.f_recent=' + repr(dat.f[-1, 5])) # title('abs(f) (blue), f-min(f) (cyan), Sigma (green), Axis Ratio (red)') # title(r'blue:$\mathrm{abs}(f)$, cyan:$f - \min(f)$, green:$\sigma$, red:axis ratio', # fontsize=fontsize - 0.0) title(r'$|f_{\mathrm{best},\mathrm{med},\mathrm{worst}}|$, $f - \min(f)$, $\sigma$, axis ratio') # if __name__ != 'cma': # should be handled by the caller self._xlabel(iabscissa) self._finalize_plotting() return self
[ "def", "plot_divers", "(", "self", ",", "iabscissa", "=", "1", ",", "foffset", "=", "1e-19", ")", ":", "from", "matplotlib", ".", "pyplot", "import", "semilogy", ",", "hold", ",", "grid", ",", "axis", ",", "title", ",", "text", "fontsize", "=", "pyplot...
plot fitness, sigma, axis ratio... :param iabscissa: 0 means vs evaluations, 1 means vs iterations :param foffset: added to f-value :See: `plot()`
[ "plot", "fitness", "sigma", "axis", "ratio", "..." ]
python
train
defunkt/pystache
pystache/loader.py
https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/loader.py#L124-L137
def load_file(self, file_name): """ Find and return the template with the given file name. Arguments: file_name: the file name of the template. """ locator = self._make_locator() path = locator.find_file(file_name, self.search_dirs) return self.read(path)
[ "def", "load_file", "(", "self", ",", "file_name", ")", ":", "locator", "=", "self", ".", "_make_locator", "(", ")", "path", "=", "locator", ".", "find_file", "(", "file_name", ",", "self", ".", "search_dirs", ")", "return", "self", ".", "read", "(", "...
Find and return the template with the given file name. Arguments: file_name: the file name of the template.
[ "Find", "and", "return", "the", "template", "with", "the", "given", "file", "name", "." ]
python
train
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L521-L531
def IsPipe(self): """Determines if the file entry is a pipe. Returns: bool: True if the file entry is a pipe. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_PIPE
[ "def", "IsPipe", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type", ...
Determines if the file entry is a pipe. Returns: bool: True if the file entry is a pipe.
[ "Determines", "if", "the", "file", "entry", "is", "a", "pipe", "." ]
python
train
tradenity/python-sdk
tradenity/resources/option_set.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/option_set.py#L302-L322
def create_option_set(cls, option_set, **kwargs): """Create OptionSet Create a new OptionSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_option_set(option_set, async=True) >>> result = thread.get() :param async bool :param OptionSet option_set: Attributes of optionSet to create (required) :return: OptionSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_option_set_with_http_info(option_set, **kwargs) else: (data) = cls._create_option_set_with_http_info(option_set, **kwargs) return data
[ "def", "create_option_set", "(", "cls", ",", "option_set", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_create_option_set_with_ht...
Create OptionSet Create a new OptionSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_option_set(option_set, async=True) >>> result = thread.get() :param async bool :param OptionSet option_set: Attributes of optionSet to create (required) :return: OptionSet If the method is called asynchronously, returns the request thread.
[ "Create", "OptionSet" ]
python
train
pvlib/pvlib-python
pvlib/pvsystem.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L409-L439
def sapm(self, effective_irradiance, temp_cell, **kwargs): """ Use the :py:func:`sapm` function, the input parameters, and ``self.module_parameters`` to calculate Voc, Isc, Ix, Ixx, Vmp/Imp. Parameters ---------- poa_direct : Series The direct irradiance incident upon the module (W/m^2). poa_diffuse : Series The diffuse irradiance incident on module. temp_cell : Series The cell temperature (degrees C). airmass_absolute : Series Absolute airmass. aoi : Series Angle of incidence (degrees). kwargs See pvsystem.sapm for details Returns ------- See pvsystem.sapm for details """ return sapm(effective_irradiance, temp_cell, self.module_parameters)
[ "def", "sapm", "(", "self", ",", "effective_irradiance", ",", "temp_cell", ",", "*", "*", "kwargs", ")", ":", "return", "sapm", "(", "effective_irradiance", ",", "temp_cell", ",", "self", ".", "module_parameters", ")" ]
Use the :py:func:`sapm` function, the input parameters, and ``self.module_parameters`` to calculate Voc, Isc, Ix, Ixx, Vmp/Imp. Parameters ---------- poa_direct : Series The direct irradiance incident upon the module (W/m^2). poa_diffuse : Series The diffuse irradiance incident on module. temp_cell : Series The cell temperature (degrees C). airmass_absolute : Series Absolute airmass. aoi : Series Angle of incidence (degrees). kwargs See pvsystem.sapm for details Returns ------- See pvsystem.sapm for details
[ "Use", "the", ":", "py", ":", "func", ":", "sapm", "function", "the", "input", "parameters", "and", "self", ".", "module_parameters", "to", "calculate", "Voc", "Isc", "Ix", "Ixx", "Vmp", "/", "Imp", "." ]
python
train
videntity/django-djmongo
djmongo/decorators.py
https://github.com/videntity/django-djmongo/blob/7534e0981a2bc12634cf3f1ed03353623dc57565/djmongo/decorators.py#L120-L178
def check_read_httpauth_access(func): """ Call after login decorator. """ def wrapper(request, *args, **kwargs): database_name = kwargs.get('database_name', "") collection_name = kwargs.get('collection_name', "") if not database_name or not collection_name: return HttpResponse(unauthorized_json_response(), content_type="application/json") try: # Check to see if we have a matching record in DB access. dac = HTTPAuthReadAPI.objects.get( database_name=database_name, collection_name=collection_name) except HTTPAuthReadAPI.DoesNotExist: return HttpResponse(unauthorized_json_response(), content_type="application/json") dac_groups = dac.groups.all() user_groups = request.user.groups.all() # allowedgroups in_group = False group = None for dg in dac_groups: if dg in user_groups: in_group = True group = dg if not in_group: message = "NOT-IN-GROUP: You do not have access to this collection. Please see your system administrator." body = {"code": 400, "message": message, "errors": [message, ]} return HttpResponse(json.dumps(body, indent=4, ), content_type="application/json") # If search keys have been limitied... if dac.search_keys: search_key_list = shlex.split(dac.search_keys) keys = [] for k in request.GET.keys(): if k not in search_key_list: message = "Search key %s is not allowed." % (k) body = {"code": 400, "message": k, "errors": [message, ]} return HttpResponse(json.dumps(body, indent=4, ), content_type="application/json") return func(request, *args, **kwargs) return update_wrapper(wrapper, func)
[ "def", "check_read_httpauth_access", "(", "func", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "database_name", "=", "kwargs", ".", "get", "(", "'database_name'", ",", "\"\"", ")", "collection_name", "=",...
Call after login decorator.
[ "Call", "after", "login", "decorator", "." ]
python
train
inveniosoftware/invenio-stats
invenio_stats/ext.py
https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/ext.py#L189-L192
def publish(self, event_type, events): """Publish events.""" assert event_type in self.events current_queues.queues['stats-{}'.format(event_type)].publish(events)
[ "def", "publish", "(", "self", ",", "event_type", ",", "events", ")", ":", "assert", "event_type", "in", "self", ".", "events", "current_queues", ".", "queues", "[", "'stats-{}'", ".", "format", "(", "event_type", ")", "]", ".", "publish", "(", "events", ...
Publish events.
[ "Publish", "events", "." ]
python
valid
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py#L497-L511
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_tx_ls_rjt(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output") fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list") fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id") fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id') fcoe_intf_tx_ls_rjt = ET.SubElement(fcoe_intf_list, "fcoe-intf-tx-ls-rjt") fcoe_intf_tx_ls_rjt.text = kwargs.pop('fcoe_intf_tx_ls_rjt') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_tx_ls_rjt", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcoe_get_interface", "=", "ET", ".", "Element", "(", "\"fcoe_get_interface\"", ")", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
mdsol/rwslib
rwslib/builders/core.py
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/core.py#L78-L82
def getroot(self): """Build XML object, return the root""" builder = ET.TreeBuilder() self.build(builder) return builder.close()
[ "def", "getroot", "(", "self", ")", ":", "builder", "=", "ET", ".", "TreeBuilder", "(", ")", "self", ".", "build", "(", "builder", ")", "return", "builder", ".", "close", "(", ")" ]
Build XML object, return the root
[ "Build", "XML", "object", "return", "the", "root" ]
python
train
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L93-L97
def get_records(self, sequence_id, gt=None, gte=None, lt=None, lte=None, limit=None, query_ascending=True, results_ascending=True): """ Returns records for a sequence. """
[ "def", "get_records", "(", "self", ",", "sequence_id", ",", "gt", "=", "None", ",", "gte", "=", "None", ",", "lt", "=", "None", ",", "lte", "=", "None", ",", "limit", "=", "None", ",", "query_ascending", "=", "True", ",", "results_ascending", "=", "T...
Returns records for a sequence.
[ "Returns", "records", "for", "a", "sequence", "." ]
python
train
hickeroar/simplebayes
simplebayes/category.py
https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/category.py#L40-L53
def train_token(self, word, count): """ Trains a particular token (increases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int """ if word not in self.tokens: self.tokens[word] = 0 self.tokens[word] += count self.tally += count
[ "def", "train_token", "(", "self", ",", "word", ",", "count", ")", ":", "if", "word", "not", "in", "self", ".", "tokens", ":", "self", ".", "tokens", "[", "word", "]", "=", "0", "self", ".", "tokens", "[", "word", "]", "+=", "count", "self", ".",...
Trains a particular token (increases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int
[ "Trains", "a", "particular", "token", "(", "increases", "the", "weight", "/", "count", "of", "it", ")" ]
python
train
manolomartinez/greg
greg/classes.py
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L146-L158
def retrieve_download_path(self): """ Retrieves the download path (looks first into config_filename_global then into the [DEFAULT], then the [feed], section of config_filename_user. The latest takes preeminence) """ section = self.name if self.config.has_section( self.name) else self.config.default_section download_path = self.config.get( section, 'Download directory', fallback='~/Podcasts') subdirectory = self.config.get( section, 'Create subdirectories', fallback='no') return [os.path.expanduser(download_path), subdirectory]
[ "def", "retrieve_download_path", "(", "self", ")", ":", "section", "=", "self", ".", "name", "if", "self", ".", "config", ".", "has_section", "(", "self", ".", "name", ")", "else", "self", ".", "config", ".", "default_section", "download_path", "=", "self"...
Retrieves the download path (looks first into config_filename_global then into the [DEFAULT], then the [feed], section of config_filename_user. The latest takes preeminence)
[ "Retrieves", "the", "download", "path", "(", "looks", "first", "into", "config_filename_global", "then", "into", "the", "[", "DEFAULT", "]", "then", "the", "[", "feed", "]", "section", "of", "config_filename_user", ".", "The", "latest", "takes", "preeminence", ...
python
train
apache/incubator-mxnet
example/ctc/multiproc_data.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L59-L88
def _proc_loop(proc_id, alive, queue, fn): """Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue queue for passing data back fn: function function object that returns a sample to be pushed into the queue """ print("proc {} started".format(proc_id)) try: while alive.value: data = fn() put_success = False while alive.value and not put_success: try: queue.put(data, timeout=0.5) put_success = True except QFullExcept: # print("Queue Full") pass except KeyboardInterrupt: print("W: interrupt received, stopping process {} ...".format(proc_id)) print("Closing process {}".format(proc_id)) queue.close()
[ "def", "_proc_loop", "(", "proc_id", ",", "alive", ",", "queue", ",", "fn", ")", ":", "print", "(", "\"proc {} started\"", ".", "format", "(", "proc_id", ")", ")", "try", ":", "while", "alive", ".", "value", ":", "data", "=", "fn", "(", ")", "put_suc...
Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue queue for passing data back fn: function function object that returns a sample to be pushed into the queue
[ "Thread", "loop", "for", "generating", "data" ]
python
train
blink1073/oct2py
oct2py/core.py
https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L523-L593
def _feval(self, func_name, func_args=(), dname='', nout=0, timeout=None, stream_handler=None, store_as='', plot_dir=None): """Run the given function with the given args. """ engine = self._engine if engine is None: raise Oct2PyError('Session is closed') # Set up our mat file paths. out_file = osp.join(self.temp_dir, 'writer.mat') out_file = out_file.replace(osp.sep, '/') in_file = osp.join(self.temp_dir, 'reader.mat') in_file = in_file.replace(osp.sep, '/') func_args = list(func_args) ref_indices = [] for (i, value) in enumerate(func_args): if isinstance(value, OctavePtr): ref_indices.append(i + 1) func_args[i] = value.address ref_indices = np.array(ref_indices) # Save the request data to the output file. req = dict(func_name=func_name, func_args=tuple(func_args), dname=dname or '', nout=nout, store_as=store_as or '', ref_indices=ref_indices) write_file(req, out_file, oned_as=self._oned_as, convert_to_float=self.convert_to_float) # Set up the engine and evaluate the `_pyeval()` function. engine.stream_handler = stream_handler or self.logger.info if timeout is None: timeout = self.timeout try: engine.eval('_pyeval("%s", "%s");' % (out_file, in_file), timeout=timeout) except KeyboardInterrupt as e: stream_handler(engine.repl.interrupt()) raise except TIMEOUT: stream_handler(engine.repl.interrupt()) raise Oct2PyError('Timed out, interrupting') except EOF: stream_handler(engine.repl.child.before) self.restart() raise Oct2PyError('Session died, restarting') # Read in the output. resp = read_file(in_file, self) if resp['err']: msg = self._parse_error(resp['err']) raise Oct2PyError(msg) result = resp['result'].ravel().tolist() if isinstance(result, list) and len(result) == 1: result = result[0] # Check for sentinel value. if (isinstance(result, Cell) and result.size == 1 and isinstance(result[0], string_types) and result[0] == '__no_value__'): result = None if plot_dir: self._engine.make_figures(plot_dir) return result
[ "def", "_feval", "(", "self", ",", "func_name", ",", "func_args", "=", "(", ")", ",", "dname", "=", "''", ",", "nout", "=", "0", ",", "timeout", "=", "None", ",", "stream_handler", "=", "None", ",", "store_as", "=", "''", ",", "plot_dir", "=", "Non...
Run the given function with the given args.
[ "Run", "the", "given", "function", "with", "the", "given", "args", "." ]
python
valid
great-expectations/great_expectations
great_expectations/dataset/pandas_dataset.py
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/pandas_dataset.py#L199-L252
def multicolumn_map_expectation(cls, func): """ The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns. """ if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column_list, mostly=None, ignore_row_if="all_values_are_missing", result_format=None, *args, **kwargs): if result_format is None: result_format = self.default_expectation_args["result_format"] test_df = self[column_list] if ignore_row_if == "all_values_are_missing": boolean_mapped_skip_values = test_df.isnull().all(axis=1) elif ignore_row_if == "any_value_is_missing": boolean_mapped_skip_values = test_df.isnull().any(axis=1) elif ignore_row_if == "never": boolean_mapped_skip_values = pd.Series([False] * len(test_df)) else: raise ValueError( "Unknown value of ignore_row_if: %s", (ignore_row_if,)) boolean_mapped_success_values = func( self, test_df[boolean_mapped_skip_values == False], *args, **kwargs) success_count = boolean_mapped_success_values.sum() nonnull_count = (~boolean_mapped_skip_values).sum() element_count = len(test_df) unexpected_list = test_df[(boolean_mapped_skip_values == False) & (boolean_mapped_success_values == False)] unexpected_index_list = list(unexpected_list.index) success, percent_success = self._calc_map_expectation_success( success_count, nonnull_count, mostly) return_obj = self._format_map_output( result_format, success, element_count, nonnull_count, len(unexpected_list), unexpected_list.to_dict(orient='records'), unexpected_index_list ) return return_obj inner_wrapper.__name__ = func.__name__ inner_wrapper.__doc__ = func.__doc__ return inner_wrapper
[ "def", "multicolumn_map_expectation", "(", "cls", ",", "func", ")", ":", "if", "PY3", ":", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "[", "0", "]", "[", "1", ":", "]", "else", ":", "argspec", "=", "inspect", ".", "getargspec",...
The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns.
[ "The", "multicolumn_map_expectation", "decorator", "handles", "boilerplate", "issues", "surrounding", "the", "common", "pattern", "of", "evaluating", "truthiness", "of", "some", "condition", "on", "a", "per", "row", "basis", "across", "a", "set", "of", "columns", ...
python
train
williballenthin/python-evtx
Evtx/Nodes.py
https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Nodes.py#L980-L991
def template(self): ''' parse the template referenced by this root node. note, this template structure is not guaranteed to be located within the root node's boundaries. Returns: TemplateNode: the template. ''' instance = self.template_instance() offset = self._chunk.offset() + instance.template_offset() node = TemplateNode(self._buf, offset, self._chunk, instance) return node
[ "def", "template", "(", "self", ")", ":", "instance", "=", "self", ".", "template_instance", "(", ")", "offset", "=", "self", ".", "_chunk", ".", "offset", "(", ")", "+", "instance", ".", "template_offset", "(", ")", "node", "=", "TemplateNode", "(", "...
parse the template referenced by this root node. note, this template structure is not guaranteed to be located within the root node's boundaries. Returns: TemplateNode: the template.
[ "parse", "the", "template", "referenced", "by", "this", "root", "node", ".", "note", "this", "template", "structure", "is", "not", "guaranteed", "to", "be", "located", "within", "the", "root", "node", "s", "boundaries", "." ]
python
train
mozilla/python-zeppelin
zeppelin/converters/markdown.py
https://github.com/mozilla/python-zeppelin/blob/76ce6b7608ef6cf7b807bd5d850a58ea6a59ef07/zeppelin/converters/markdown.py#L237-L239
def write_image_to_disk(self, msg, result, fh): """Decode message to PNG and write to disk.""" cairosvg.svg2png(bytestring=msg.encode('utf-8'), write_to=fh)
[ "def", "write_image_to_disk", "(", "self", ",", "msg", ",", "result", ",", "fh", ")", ":", "cairosvg", ".", "svg2png", "(", "bytestring", "=", "msg", ".", "encode", "(", "'utf-8'", ")", ",", "write_to", "=", "fh", ")" ]
Decode message to PNG and write to disk.
[ "Decode", "message", "to", "PNG", "and", "write", "to", "disk", "." ]
python
train
zeldamods/aamp
aamp/parameters.py
https://github.com/zeldamods/aamp/blob/90d722d33357af5af9809a3fc83b9ceaecf943c1/aamp/parameters.py#L40-L42
def set_param(self, name: str, v) -> None: """Add or update an existing parameter.""" self.params[zlib.crc32(name.encode())] = v
[ "def", "set_param", "(", "self", ",", "name", ":", "str", ",", "v", ")", "->", "None", ":", "self", ".", "params", "[", "zlib", ".", "crc32", "(", "name", ".", "encode", "(", ")", ")", "]", "=", "v" ]
Add or update an existing parameter.
[ "Add", "or", "update", "an", "existing", "parameter", "." ]
python
train
saltstack/salt
salt/modules/supervisord.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L312-L335
def status_raw(name=None, user=None, conf_file=None, bin_env=None): ''' Display the raw output of status user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status_raw ''' ret = __salt__['cmd.run_all']( _ctl_cmd('status', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
[ "def", "status_raw", "(", "name", "=", "None", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "_ctl_cmd", "(", "'status'", ",", "name", ",", "con...
Display the raw output of status user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status_raw
[ "Display", "the", "raw", "output", "of", "status" ]
python
train
zeroSteiner/smoke-zephyr
smoke_zephyr/utilities.py
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L533-L564
def open_uri(uri): """ Open a URI in a platform intelligent way. On Windows this will use 'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open depending on which is available. If no suitable application can be found to open the URI, a RuntimeError will be raised. .. versionadded:: 1.3.0 :param str uri: The URI to open. """ close_fds = True startupinfo = None proc_args = [] if sys.platform.startswith('win'): proc_args.append(which('cmd.exe')) proc_args.append('/c') proc_args.append('start') uri = uri.replace('&', '^&') close_fds = False startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE elif which('gvfs-open'): proc_args.append(which('gvfs-open')) elif which('xdg-open'): proc_args.append(which('xdg-open')) else: raise RuntimeError('could not find suitable application to open uri') proc_args.append(uri) proc_h = subprocess.Popen(proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=close_fds, startupinfo=startupinfo) return proc_h.wait() == 0
[ "def", "open_uri", "(", "uri", ")", ":", "close_fds", "=", "True", "startupinfo", "=", "None", "proc_args", "=", "[", "]", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "proc_args", ".", "append", "(", "which", "(", "'cmd.exe...
Open a URI in a platform intelligent way. On Windows this will use 'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open depending on which is available. If no suitable application can be found to open the URI, a RuntimeError will be raised. .. versionadded:: 1.3.0 :param str uri: The URI to open.
[ "Open", "a", "URI", "in", "a", "platform", "intelligent", "way", ".", "On", "Windows", "this", "will", "use", "cmd", ".", "exe", "/", "c", "start", "and", "on", "Linux", "this", "will", "use", "gvfs", "-", "open", "or", "xdg", "-", "open", "depending...
python
train
edx/opaque-keys
opaque_keys/edx/block_types.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/block_types.py#L40-L56
def _from_string(cls, serialized): """ Return an instance of `cls` parsed from its `serialized` form. Args: cls: The :class:`OpaqueKey` subclass. serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed. Raises: InvalidKeyError: Should be raised if `serialized` is not a valid serialized key understood by `cls`. """ if ':' not in serialized: raise InvalidKeyError( "BlockTypeKeyV1 keys must contain ':' separating the block family from the block_type.", serialized) family, __, block_type = serialized.partition(':') return cls(family, block_type)
[ "def", "_from_string", "(", "cls", ",", "serialized", ")", ":", "if", "':'", "not", "in", "serialized", ":", "raise", "InvalidKeyError", "(", "\"BlockTypeKeyV1 keys must contain ':' separating the block family from the block_type.\"", ",", "serialized", ")", "family", ","...
Return an instance of `cls` parsed from its `serialized` form. Args: cls: The :class:`OpaqueKey` subclass. serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed. Raises: InvalidKeyError: Should be raised if `serialized` is not a valid serialized key understood by `cls`.
[ "Return", "an", "instance", "of", "cls", "parsed", "from", "its", "serialized", "form", "." ]
python
train
prompt-toolkit/pymux
pymux/arrangement.py
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L275-L305
def remove_pane(self, pane): """ Remove pane from this Window. """ assert isinstance(pane, Pane) if pane in self.panes: # When this pane was focused, switch to previous active or next in order. if pane == self.active_pane: if self.previous_active_pane: self.active_pane = self.previous_active_pane else: self.focus_next() # Remove from the parent. When the parent becomes empty, remove the # parent itself recursively. p = self._get_parent(pane) p.remove(pane) while len(p) == 0 and p != self.root: p2 = self._get_parent(p) p2.remove(p) p = p2 # When the parent has only one item left, collapse into its parent. while len(p) == 1 and p != self.root: p2 = self._get_parent(p) p2.weights[p[0]] = p2.weights[p] # Keep dimensions. i = p2.index(p) p2[i] = p[0] p = p2
[ "def", "remove_pane", "(", "self", ",", "pane", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "if", "pane", "in", "self", ".", "panes", ":", "# When this pane was focused, switch to previous active or next in order.", "if", "pane", "==", "self",...
Remove pane from this Window.
[ "Remove", "pane", "from", "this", "Window", "." ]
python
train
nchopin/particles
book/mle/malikpitt_interpolation.py
https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/book/mle/malikpitt_interpolation.py#L16-L24
def avg_n_nplusone(x): """ returns x[0]/2, (x[0]+x[1])/2, ... (x[-2]+x[-1])/2, x[-1]/2 """ y = np.zeros(1 + x.shape[0]) hx = 0.5 * x y[:-1] = hx y[1:] += hx return y
[ "def", "avg_n_nplusone", "(", "x", ")", ":", "y", "=", "np", ".", "zeros", "(", "1", "+", "x", ".", "shape", "[", "0", "]", ")", "hx", "=", "0.5", "*", "x", "y", "[", ":", "-", "1", "]", "=", "hx", "y", "[", "1", ":", "]", "+=", "hx", ...
returns x[0]/2, (x[0]+x[1])/2, ... (x[-2]+x[-1])/2, x[-1]/2
[ "returns", "x", "[", "0", "]", "/", "2", "(", "x", "[", "0", "]", "+", "x", "[", "1", "]", ")", "/", "2", "...", "(", "x", "[", "-", "2", "]", "+", "x", "[", "-", "1", "]", ")", "/", "2", "x", "[", "-", "1", "]", "/", "2" ]
python
train
summanlp/textrank
summa/preprocessing/snowball.py
https://github.com/summanlp/textrank/blob/6844bbe8c4b2b468020ae0dfd6574a743f9ad442/summa/preprocessing/snowball.py#L659-L1032
def stem(self, word): """ Stem an English word and return the stemmed form. :param word: The word that is stemmed. :type word: str or unicode :return: The stemmed form. :rtype: unicode """ word = word.lower() if len(word) <= 2: return word elif word in self.__special_words: return self.__special_words[word] # Map the different apostrophe characters to a single consistent one word = (word.replace("\u2019", "\x27") .replace("\u2018", "\x27") .replace("\u201B", "\x27")) if word.startswith("\x27"): word = word[1:] if word.startswith("y"): word = "".join(("Y", word[1:])) for i in range(1, len(word)): if word[i-1] in self.__vowels and word[i] == "y": word = "".join((word[:i], "Y", word[i+1:])) step1a_vowel_found = False step1b_vowel_found = False r1 = "" r2 = "" if word.startswith(("gener", "commun", "arsen")): if word.startswith(("gener", "arsen")): r1 = word[5:] else: r1 = word[6:] for i in range(1, len(r1)): if r1[i] not in self.__vowels and r1[i-1] in self.__vowels: r2 = r1[i+1:] break else: r1, r2 = self._r1r2_standard(word, self.__vowels) # STEP 0 for suffix in self.__step0_suffixes: if word.endswith(suffix): word = word[:-len(suffix)] r1 = r1[:-len(suffix)] r2 = r2[:-len(suffix)] break # STEP 1a for suffix in self.__step1a_suffixes: if word.endswith(suffix): if suffix == "sses": word = word[:-2] r1 = r1[:-2] r2 = r2[:-2] elif suffix in ("ied", "ies"): if len(word[:-len(suffix)]) > 1: word = word[:-2] r1 = r1[:-2] r2 = r2[:-2] else: word = word[:-1] r1 = r1[:-1] r2 = r2[:-1] elif suffix == "s": for letter in word[:-2]: if letter in self.__vowels: step1a_vowel_found = True break if step1a_vowel_found: word = word[:-1] r1 = r1[:-1] r2 = r2[:-1] break # STEP 1b for suffix in self.__step1b_suffixes: if word.endswith(suffix): if suffix in ("eed", "eedly"): if r1.endswith(suffix): word = "".join((word[:-len(suffix)], "ee")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ee")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ee")) else: r2 = "" else: for letter in word[:-len(suffix)]: if letter in self.__vowels: step1b_vowel_found = True break if step1b_vowel_found: word = word[:-len(suffix)] r1 = r1[:-len(suffix)] r2 = r2[:-len(suffix)] if word.endswith(("at", "bl", "iz")): word = "".join((word, "e")) r1 = "".join((r1, "e")) if len(word) > 5 or len(r1) >=3: r2 = "".join((r2, "e")) elif word.endswith(self.__double_consonants): word = word[:-1] r1 = r1[:-1] r2 = r2[:-1] elif ((r1 == "" and len(word) >= 3 and word[-1] not in self.__vowels and word[-1] not in "wxY" and word[-2] in self.__vowels and word[-3] not in self.__vowels) or (r1 == "" and len(word) == 2 and word[0] in self.__vowels and word[1] not in self.__vowels)): word = "".join((word, "e")) if len(r1) > 0: r1 = "".join((r1, "e")) if len(r2) > 0: r2 = "".join((r2, "e")) break # STEP 1c if len(word) > 2 and word[-1] in "yY" and word[-2] not in self.__vowels: word = "".join((word[:-1], "i")) if len(r1) >= 1: r1 = "".join((r1[:-1], "i")) else: r1 = "" if len(r2) >= 1: r2 = "".join((r2[:-1], "i")) else: r2 = "" # STEP 2 for suffix in self.__step2_suffixes: if word.endswith(suffix): if r1.endswith(suffix): if suffix == "tional": word = word[:-2] r1 = r1[:-2] r2 = r2[:-2] elif suffix in ("enci", "anci", "abli"): word = "".join((word[:-1], "e")) if len(r1) >= 1: r1 = "".join((r1[:-1], "e")) else: r1 = "" if len(r2) >= 1: r2 = "".join((r2[:-1], "e")) else: r2 = "" elif suffix == "entli": word = word[:-2] r1 = r1[:-2] r2 = r2[:-2] elif suffix in ("izer", "ization"): word = "".join((word[:-len(suffix)], "ize")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ize")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ize")) else: r2 = "" elif suffix in ("ational", "ation", "ator"): word = "".join((word[:-len(suffix)], "ate")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ate")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ate")) else: r2 = "e" elif suffix in ("alism", "aliti", "alli"): word = "".join((word[:-len(suffix)], "al")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "al")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "al")) else: r2 = "" elif suffix == "fulness": word = word[:-4] r1 = r1[:-4] r2 = r2[:-4] elif suffix in ("ousli", "ousness"): word = "".join((word[:-len(suffix)], "ous")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ous")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ous")) else: r2 = "" elif suffix in ("iveness", "iviti"): word = "".join((word[:-len(suffix)], "ive")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ive")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ive")) else: r2 = "e" elif suffix in ("biliti", "bli"): word = "".join((word[:-len(suffix)], "ble")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ble")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ble")) else: r2 = "" elif suffix == "ogi" and word[-4] == "l": word = word[:-1] r1 = r1[:-1] r2 = r2[:-1] elif suffix in ("fulli", "lessli"): word = word[:-2] r1 = r1[:-2] r2 = r2[:-2] elif suffix == "li" and word[-3] in self.__li_ending: word = word[:-2] r1 = r1[:-2] r2 = r2[:-2] break # STEP 3 for suffix in self.__step3_suffixes: if word.endswith(suffix): if r1.endswith(suffix): if suffix == "tional": word = word[:-2] r1 = r1[:-2] r2 = r2[:-2] elif suffix == "ational": word = "".join((word[:-len(suffix)], "ate")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ate")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ate")) else: r2 = "" elif suffix == "alize": word = word[:-3] r1 = r1[:-3] r2 = r2[:-3] elif suffix in ("icate", "iciti", "ical"): word = "".join((word[:-len(suffix)], "ic")) if len(r1) >= len(suffix): r1 = "".join((r1[:-len(suffix)], "ic")) else: r1 = "" if len(r2) >= len(suffix): r2 = "".join((r2[:-len(suffix)], "ic")) else: r2 = "" elif suffix in ("ful", "ness"): word = word[:-len(suffix)] r1 = r1[:-len(suffix)] r2 = r2[:-len(suffix)] elif suffix == "ative" and r2.endswith(suffix): word = word[:-5] r1 = r1[:-5] r2 = r2[:-5] break # STEP 4 for suffix in self.__step4_suffixes: if word.endswith(suffix): if r2.endswith(suffix): if suffix == "ion": if word[-4] in "st": word = word[:-3] r1 = r1[:-3] r2 = r2[:-3] else: word = word[:-len(suffix)] r1 = r1[:-len(suffix)] r2 = r2[:-len(suffix)] break # STEP 5 if r2.endswith("l") and word[-2] == "l": word = word[:-1] elif r2.endswith("e"): word = word[:-1] elif r1.endswith("e"): if len(word) >= 4 and (word[-2] in self.__vowels or word[-2] in "wxY" or word[-3] not in self.__vowels or word[-4] in self.__vowels): word = word[:-1] word = word.replace("Y", "y") return word
[ "def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "lower", "(", ")", "if", "len", "(", "word", ")", "<=", "2", ":", "return", "word", "elif", "word", "in", "self", ".", "__special_words", ":", "return", "self", ".", "__...
Stem an English word and return the stemmed form. :param word: The word that is stemmed. :type word: str or unicode :return: The stemmed form. :rtype: unicode
[ "Stem", "an", "English", "word", "and", "return", "the", "stemmed", "form", "." ]
python
train
grundic/yagocd
yagocd/client.py
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L131-L139
def agents(self): """ Property for accessing :class:`AgentManager` instance, which is used to manage agents. :rtype: yagocd.resources.agent.AgentManager """ if self._agent_manager is None: self._agent_manager = AgentManager(session=self._session) return self._agent_manager
[ "def", "agents", "(", "self", ")", ":", "if", "self", ".", "_agent_manager", "is", "None", ":", "self", ".", "_agent_manager", "=", "AgentManager", "(", "session", "=", "self", ".", "_session", ")", "return", "self", ".", "_agent_manager" ]
Property for accessing :class:`AgentManager` instance, which is used to manage agents. :rtype: yagocd.resources.agent.AgentManager
[ "Property", "for", "accessing", ":", "class", ":", "AgentManager", "instance", "which", "is", "used", "to", "manage", "agents", "." ]
python
train
fedora-infra/fedmsg
fedmsg/meta/base.py
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/meta/base.py#L146-L154
def handle_msg(self, msg, **config): """ If we can handle the given message, return the remainder of the topic. Returns None if we can't handle the message. """ match = self.__prefix__.match(msg['topic']) if match: return match.groups()[-1] or ""
[ "def", "handle_msg", "(", "self", ",", "msg", ",", "*", "*", "config", ")", ":", "match", "=", "self", ".", "__prefix__", ".", "match", "(", "msg", "[", "'topic'", "]", ")", "if", "match", ":", "return", "match", ".", "groups", "(", ")", "[", "-"...
If we can handle the given message, return the remainder of the topic. Returns None if we can't handle the message.
[ "If", "we", "can", "handle", "the", "given", "message", "return", "the", "remainder", "of", "the", "topic", "." ]
python
train
ayust/kitnirc
kitnirc/client.py
https://github.com/ayust/kitnirc/blob/cf19fe39219da75f053e1a3976bf21331b6fefea/kitnirc/client.py#L409-L429
def join(self, target, key=None): """Attempt to join a channel. The optional second argument is the channel key, if needed. """ chantypes = self.server.features.get("CHANTYPES", "#") if not target or target[0] not in chantypes: # Among other things, this prevents accidentally sending the # "JOIN 0" command which actually removes you from all channels _log.warning("Refusing to join channel that does not start " "with one of '%s': %s", chantypes, target) return False if self.server.in_channel(target): _log.warning("Ignoring request to join channel '%s' because we " "are already in that channel.", target) return False _log.info("Joining channel %s ...", target) self.send("JOIN", target, *([key] if key else [])) return True
[ "def", "join", "(", "self", ",", "target", ",", "key", "=", "None", ")", ":", "chantypes", "=", "self", ".", "server", ".", "features", ".", "get", "(", "\"CHANTYPES\"", ",", "\"#\"", ")", "if", "not", "target", "or", "target", "[", "0", "]", "not"...
Attempt to join a channel. The optional second argument is the channel key, if needed.
[ "Attempt", "to", "join", "a", "channel", "." ]
python
train
datacats/datacats
datacats/environment.py
https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/environment.py#L94-L100
def save(self): """ Save environment settings into environment directory, overwriting any existing configuration and discarding site config """ task.save_new_environment(self.name, self.datadir, self.target, self.ckan_version, self.deploy_target, self.always_prod)
[ "def", "save", "(", "self", ")", ":", "task", ".", "save_new_environment", "(", "self", ".", "name", ",", "self", ".", "datadir", ",", "self", ".", "target", ",", "self", ".", "ckan_version", ",", "self", ".", "deploy_target", ",", "self", ".", "always...
Save environment settings into environment directory, overwriting any existing configuration and discarding site config
[ "Save", "environment", "settings", "into", "environment", "directory", "overwriting", "any", "existing", "configuration", "and", "discarding", "site", "config" ]
python
train
pasztorpisti/json-cfg
src/jsoncfg/text_encoding.py
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/text_encoding.py#L23-L40
def decode_utf_text_buffer(buf, default_encoding='UTF-8', use_utf8_strings=True): """ :param buf: Binary file contents with optional BOM prefix. :param default_encoding: The encoding to be used if the buffer doesn't have a BOM prefix. :param use_utf8_strings: Used only in case of python2: You can choose utf-8 str in-memory string representation in case of python. If use_utf8_strings is False or you are using python3 then the text buffer is automatically loaded as a unicode object. :return: A unicode object. In case of python2 it can optionally be an str object containing utf-8 encoded text. """ buf, encoding = detect_encoding_and_remove_bom(buf, default_encoding) if python2 and use_utf8_strings: if are_encoding_names_equivalent(encoding, 'UTF-8'): return buf return buf.decode(encoding).encode('UTF-8') return buf.decode(encoding)
[ "def", "decode_utf_text_buffer", "(", "buf", ",", "default_encoding", "=", "'UTF-8'", ",", "use_utf8_strings", "=", "True", ")", ":", "buf", ",", "encoding", "=", "detect_encoding_and_remove_bom", "(", "buf", ",", "default_encoding", ")", "if", "python2", "and", ...
:param buf: Binary file contents with optional BOM prefix. :param default_encoding: The encoding to be used if the buffer doesn't have a BOM prefix. :param use_utf8_strings: Used only in case of python2: You can choose utf-8 str in-memory string representation in case of python. If use_utf8_strings is False or you are using python3 then the text buffer is automatically loaded as a unicode object. :return: A unicode object. In case of python2 it can optionally be an str object containing utf-8 encoded text.
[ ":", "param", "buf", ":", "Binary", "file", "contents", "with", "optional", "BOM", "prefix", ".", ":", "param", "default_encoding", ":", "The", "encoding", "to", "be", "used", "if", "the", "buffer", "doesn", "t", "have", "a", "BOM", "prefix", ".", ":", ...
python
train
HPAC/matchpy
matchpy/expressions/expressions.py
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L426-L482
def new( name: str, arity: Arity, class_name: str=None, *, associative: bool=False, commutative: bool=False, one_identity: bool=False, infix: bool=False ) -> Type['Operation']: """Utility method to create a new operation type. Example: >>> Times = Operation.new('*', Arity.polyadic, 'Times', associative=True, commutative=True, one_identity=True) >>> Times Times['*', Arity(min_count=2, fixed_size=False), associative, commutative, one_identity] >>> str(Times(Symbol('a'), Symbol('b'))) '*(a, b)' Args: name: Name or symbol for the operator. Will be used as name for the new class if `class_name` is not specified. arity: The arity of the operator as explained in the documentation of `Operation`. class_name: Name for the new operation class to be used instead of name. This argument is required if `name` is not a valid python identifier. Keyword Args: associative: See :attr:`~Operation.associative`. commutative: See :attr:`~Operation.commutative`. one_identity: See :attr:`~Operation.one_identity`. infix: See :attr:`~Operation.infix`. Raises: ValueError: if the class name of the operation is not a valid class identifier. """ class_name = class_name or name if not class_name.isidentifier() or keyword.iskeyword(class_name): raise ValueError("Invalid identifier for new operator class.") return type( class_name, (Operation, ), { 'name': name, 'arity': arity, 'associative': associative, 'commutative': commutative, 'one_identity': one_identity, 'infix': infix } )
[ "def", "new", "(", "name", ":", "str", ",", "arity", ":", "Arity", ",", "class_name", ":", "str", "=", "None", ",", "*", ",", "associative", ":", "bool", "=", "False", ",", "commutative", ":", "bool", "=", "False", ",", "one_identity", ":", "bool", ...
Utility method to create a new operation type. Example: >>> Times = Operation.new('*', Arity.polyadic, 'Times', associative=True, commutative=True, one_identity=True) >>> Times Times['*', Arity(min_count=2, fixed_size=False), associative, commutative, one_identity] >>> str(Times(Symbol('a'), Symbol('b'))) '*(a, b)' Args: name: Name or symbol for the operator. Will be used as name for the new class if `class_name` is not specified. arity: The arity of the operator as explained in the documentation of `Operation`. class_name: Name for the new operation class to be used instead of name. This argument is required if `name` is not a valid python identifier. Keyword Args: associative: See :attr:`~Operation.associative`. commutative: See :attr:`~Operation.commutative`. one_identity: See :attr:`~Operation.one_identity`. infix: See :attr:`~Operation.infix`. Raises: ValueError: if the class name of the operation is not a valid class identifier.
[ "Utility", "method", "to", "create", "a", "new", "operation", "type", "." ]
python
train
mcieslik-mctp/papy
src/papy/util/func.py
https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L510-L520
def pickle_dumps(inbox): """ Serializes the first element of the input using the pickle protocol using the fastes binary protocol. """ # http://bugs.python.org/issue4074 gc.disable() str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL) gc.enable() return str_
[ "def", "pickle_dumps", "(", "inbox", ")", ":", "# http://bugs.python.org/issue4074", "gc", ".", "disable", "(", ")", "str_", "=", "cPickle", ".", "dumps", "(", "inbox", "[", "0", "]", ",", "cPickle", ".", "HIGHEST_PROTOCOL", ")", "gc", ".", "enable", "(", ...
Serializes the first element of the input using the pickle protocol using the fastes binary protocol.
[ "Serializes", "the", "first", "element", "of", "the", "input", "using", "the", "pickle", "protocol", "using", "the", "fastes", "binary", "protocol", "." ]
python
train
ownport/scrapy-dblite
dblite/__init__.py
https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L54-L58
def _regexp(expr, item): ''' REGEXP function for Sqlite ''' reg = re.compile(expr) return reg.search(item) is not None
[ "def", "_regexp", "(", "expr", ",", "item", ")", ":", "reg", "=", "re", ".", "compile", "(", "expr", ")", "return", "reg", ".", "search", "(", "item", ")", "is", "not", "None" ]
REGEXP function for Sqlite
[ "REGEXP", "function", "for", "Sqlite" ]
python
train
Gorialis/jishaku
jishaku/cog.py
https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L347-L359
async def jsk_sudo(self, ctx: commands.Context, *, command_string: str): """ Run a command bypassing all checks and cooldowns. This also bypasses permission checks so this has a high possibility of making a command raise. """ alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string) if alt_ctx.command is None: return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found') return await alt_ctx.command.reinvoke(alt_ctx)
[ "async", "def", "jsk_sudo", "(", "self", ",", "ctx", ":", "commands", ".", "Context", ",", "*", ",", "command_string", ":", "str", ")", ":", "alt_ctx", "=", "await", "copy_context_with", "(", "ctx", ",", "content", "=", "ctx", ".", "prefix", "+", "comm...
Run a command bypassing all checks and cooldowns. This also bypasses permission checks so this has a high possibility of making a command raise.
[ "Run", "a", "command", "bypassing", "all", "checks", "and", "cooldowns", "." ]
python
train
pybel/pybel
src/pybel/struct/mutation/induction/annotations.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/annotations.py#L40-L53
def get_subgraph_by_annotation_value(graph, annotation, values): """Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values: str or iter[str] :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph """ if isinstance(values, str): values = {values} return get_subgraph_by_annotations(graph, {annotation: values})
[ "def", "get_subgraph_by_annotation_value", "(", "graph", ",", "annotation", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "str", ")", ":", "values", "=", "{", "values", "}", "return", "get_subgraph_by_annotations", "(", "graph", ",", "{", ...
Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values: str or iter[str] :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph
[ "Induce", "a", "sub", "-", "graph", "over", "all", "edges", "whose", "annotations", "match", "the", "given", "key", "and", "value", "." ]
python
train
serkanyersen/underscore.py
src/underscore.py
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L245-L248
def filter(self, func): """ Return all the elements that pass a truth test. """ return self._wrap(list(filter(func, self.obj)))
[ "def", "filter", "(", "self", ",", "func", ")", ":", "return", "self", ".", "_wrap", "(", "list", "(", "filter", "(", "func", ",", "self", ".", "obj", ")", ")", ")" ]
Return all the elements that pass a truth test.
[ "Return", "all", "the", "elements", "that", "pass", "a", "truth", "test", "." ]
python
train
dbcli/cli_helpers
cli_helpers/config.py
https://github.com/dbcli/cli_helpers/blob/3ebd891ac0c02bad061182dbcb54a47fb21980ae/cli_helpers/config.py#L77-L101
def read_default_config(self): """Read the default config file. :raises DefaultConfigValidationError: There was a validation error with the *default* file. """ if self.validate: self.default_config = ConfigObj(configspec=self.default_file, list_values=False, _inspec=True, encoding='utf8') valid = self.default_config.validate(Validator(), copy=True, preserve_errors=True) if valid is not True: for name, section in valid.items(): if section is True: continue for key, value in section.items(): if isinstance(value, ValidateError): raise DefaultConfigValidationError( 'section [{}], key "{}": {}'.format( name, key, value)) elif self.default_file: self.default_config, _ = self.read_config_file(self.default_file) self.update(self.default_config)
[ "def", "read_default_config", "(", "self", ")", ":", "if", "self", ".", "validate", ":", "self", ".", "default_config", "=", "ConfigObj", "(", "configspec", "=", "self", ".", "default_file", ",", "list_values", "=", "False", ",", "_inspec", "=", "True", ",...
Read the default config file. :raises DefaultConfigValidationError: There was a validation error with the *default* file.
[ "Read", "the", "default", "config", "file", "." ]
python
test
marl/jams
jams/schema.py
https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L50-L75
def namespace(ns_key): '''Construct a validation schema for a given namespace. Parameters ---------- ns_key : str Namespace key identifier (eg, 'beat' or 'segment_tut') Returns ------- schema : dict JSON schema of `namespace` ''' if ns_key not in __NAMESPACE__: raise NamespaceError('Unknown namespace: {:s}'.format(ns_key)) sch = copy.deepcopy(JAMS_SCHEMA['definitions']['SparseObservation']) for key in ['value', 'confidence']: try: sch['properties'][key] = __NAMESPACE__[ns_key][key] except KeyError: pass return sch
[ "def", "namespace", "(", "ns_key", ")", ":", "if", "ns_key", "not", "in", "__NAMESPACE__", ":", "raise", "NamespaceError", "(", "'Unknown namespace: {:s}'", ".", "format", "(", "ns_key", ")", ")", "sch", "=", "copy", ".", "deepcopy", "(", "JAMS_SCHEMA", "[",...
Construct a validation schema for a given namespace. Parameters ---------- ns_key : str Namespace key identifier (eg, 'beat' or 'segment_tut') Returns ------- schema : dict JSON schema of `namespace`
[ "Construct", "a", "validation", "schema", "for", "a", "given", "namespace", "." ]
python
valid
ryanvarley/ExoData
exodata/assumptions.py
https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/assumptions.py#L82-L92
def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
[ "def", "planetRadiusType", "(", "radius", ")", ":", "if", "radius", "is", "np", ".", "nan", ":", "return", "None", "for", "radiusLimit", ",", "radiusType", "in", "planetAssumptions", "[", "'radiusType'", "]", ":", "if", "radius", "<", "radiusLimit", ":", "...
Returns the planet radiustype given the mass and using planetAssumptions['radiusType']
[ "Returns", "the", "planet", "radiustype", "given", "the", "mass", "and", "using", "planetAssumptions", "[", "radiusType", "]" ]
python
train
MacHu-GWU/crawl_zillow-project
crawl_zillow/helpers.py
https://github.com/MacHu-GWU/crawl_zillow-project/blob/c6d7ca8e4c80e7e7e963496433ef73df1413c16e/crawl_zillow/helpers.py#L5-L16
def int_filter(text): """Extract integer from text. **中文文档** 摘除文本内的整数。 """ res = list() for char in text: if char.isdigit(): res.append(char) return int("".join(res))
[ "def", "int_filter", "(", "text", ")", ":", "res", "=", "list", "(", ")", "for", "char", "in", "text", ":", "if", "char", ".", "isdigit", "(", ")", ":", "res", ".", "append", "(", "char", ")", "return", "int", "(", "\"\"", ".", "join", "(", "re...
Extract integer from text. **中文文档** 摘除文本内的整数。
[ "Extract", "integer", "from", "text", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/brocade_interface_ext_rpc/get_media_detail/output/interface/on_board/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/brocade_interface_ext_rpc/get_media_detail/output/interface/on_board/__init__.py#L99-L122
def _set_speed(self, v, load=False): """ Setter method for speed, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/on_board/speed (line-speed) If this variable is read-only (config: false) in the source YANG file, then _set_speed is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_speed() directly. YANG Description: The actual line speed of this interface. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'8Gbps': {'value': 9}, u'nil': {'value': 1}, u'40Gbps': {'value': 5}, u'1Gbps': {'value': 3}, u'auto': {'value': 2}, u'25Gbps': {'value': 12}, u'10Gbps': {'value': 4}, u'4Gbps': {'value': 8}, u'100Gbps': {'value': 11}, u'100Mbps': {'value': 6}, u'16Gbps': {'value': 10}, u'2Gbps': {'value': 7}},), is_leaf=True, yang_name="speed", rest_name="speed", parent=self, choice=(u'interface-identifier', u'on-board'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-interface-ext', defining_module='brocade-interface-ext', yang_type='line-speed', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """speed must be of a type compatible with line-speed""", 'defined-type': "brocade-interface-ext:line-speed", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'8Gbps': {'value': 9}, u'nil': {'value': 1}, u'40Gbps': {'value': 5}, u'1Gbps': {'value': 3}, u'auto': {'value': 2}, u'25Gbps': {'value': 12}, u'10Gbps': {'value': 4}, u'4Gbps': {'value': 8}, u'100Gbps': {'value': 11}, u'100Mbps': {'value': 6}, u'16Gbps': {'value': 10}, u'2Gbps': {'value': 7}},), is_leaf=True, yang_name="speed", rest_name="speed", parent=self, choice=(u'interface-identifier', u'on-board'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-interface-ext', defining_module='brocade-interface-ext', yang_type='line-speed', is_config=True)""", }) self.__speed = t if hasattr(self, '_set'): self._set()
[ "def", "_set_speed", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for speed, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/on_board/speed (line-speed) If this variable is read-only (config: false) in the source YANG file, then _set_speed is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_speed() directly. YANG Description: The actual line speed of this interface.
[ "Setter", "method", "for", "speed", "mapped", "from", "YANG", "variable", "/", "brocade_interface_ext_rpc", "/", "get_media_detail", "/", "output", "/", "interface", "/", "on_board", "/", "speed", "(", "line", "-", "speed", ")", "If", "this", "variable", "is",...
python
train
ninuxorg/nodeshot
nodeshot/interop/oldimporter/db.py
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/oldimporter/db.py#L66-L72
def allow_migrate(self, db, model): """ Make sure the old_nodeshot app only appears in the 'old_nodeshot' database """ if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter': return False return True
[ "def", "allow_migrate", "(", "self", ",", "db", ",", "model", ")", ":", "if", "db", "!=", "'old_nodeshot'", "or", "model", ".", "_meta", ".", "app_label", "!=", "'oldimporter'", ":", "return", "False", "return", "True" ]
Make sure the old_nodeshot app only appears in the 'old_nodeshot' database
[ "Make", "sure", "the", "old_nodeshot", "app", "only", "appears", "in", "the", "old_nodeshot", "database" ]
python
train
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L339-L345
def getabsfile(object): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" return os.path.normcase( os.path.abspath(getsourcefile(object) or getfile(object)))
[ "def", "getabsfile", "(", "object", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "getsourcefile", "(", "object", ")", "or", "getfile", "(", "object", ")", ")", ")" ]
Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.
[ "Return", "an", "absolute", "path", "to", "the", "source", "or", "compiled", "file", "for", "an", "object", "." ]
python
train
apache/spark
python/pyspark/mllib/util.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/util.py#L201-L237
def convertVectorColumnsToML(dataset, *cols): """ Converts vector columns in an input DataFrame from the :py:class:`pyspark.mllib.linalg.Vector` type to the new :py:class:`pyspark.ml.linalg.Vector` type under the `spark.ml` package. :param dataset: input dataset :param cols: a list of vector columns to be converted. New vector columns will be ignored. If unspecified, all old vector columns will be converted excepted nested ones. :return: the input dataset with old vector columns converted to the new vector type >>> import pyspark >>> from pyspark.mllib.linalg import Vectors >>> from pyspark.mllib.util import MLUtils >>> df = spark.createDataFrame( ... [(0, Vectors.sparse(2, [1], [1.0]), Vectors.dense(2.0, 3.0))], ... ["id", "x", "y"]) >>> r1 = MLUtils.convertVectorColumnsToML(df).first() >>> isinstance(r1.x, pyspark.ml.linalg.SparseVector) True >>> isinstance(r1.y, pyspark.ml.linalg.DenseVector) True >>> r2 = MLUtils.convertVectorColumnsToML(df, "x").first() >>> isinstance(r2.x, pyspark.ml.linalg.SparseVector) True >>> isinstance(r2.y, pyspark.mllib.linalg.DenseVector) True """ if not isinstance(dataset, DataFrame): raise TypeError("Input dataset must be a DataFrame but got {}.".format(type(dataset))) return callMLlibFunc("convertVectorColumnsToML", dataset, list(cols))
[ "def", "convertVectorColumnsToML", "(", "dataset", ",", "*", "cols", ")", ":", "if", "not", "isinstance", "(", "dataset", ",", "DataFrame", ")", ":", "raise", "TypeError", "(", "\"Input dataset must be a DataFrame but got {}.\"", ".", "format", "(", "type", "(", ...
Converts vector columns in an input DataFrame from the :py:class:`pyspark.mllib.linalg.Vector` type to the new :py:class:`pyspark.ml.linalg.Vector` type under the `spark.ml` package. :param dataset: input dataset :param cols: a list of vector columns to be converted. New vector columns will be ignored. If unspecified, all old vector columns will be converted excepted nested ones. :return: the input dataset with old vector columns converted to the new vector type >>> import pyspark >>> from pyspark.mllib.linalg import Vectors >>> from pyspark.mllib.util import MLUtils >>> df = spark.createDataFrame( ... [(0, Vectors.sparse(2, [1], [1.0]), Vectors.dense(2.0, 3.0))], ... ["id", "x", "y"]) >>> r1 = MLUtils.convertVectorColumnsToML(df).first() >>> isinstance(r1.x, pyspark.ml.linalg.SparseVector) True >>> isinstance(r1.y, pyspark.ml.linalg.DenseVector) True >>> r2 = MLUtils.convertVectorColumnsToML(df, "x").first() >>> isinstance(r2.x, pyspark.ml.linalg.SparseVector) True >>> isinstance(r2.y, pyspark.mllib.linalg.DenseVector) True
[ "Converts", "vector", "columns", "in", "an", "input", "DataFrame", "from", "the", ":", "py", ":", "class", ":", "pyspark", ".", "mllib", ".", "linalg", ".", "Vector", "type", "to", "the", "new", ":", "py", ":", "class", ":", "pyspark", ".", "ml", "."...
python
train
sbg/sevenbridges-python
sevenbridges/meta/transformer.py
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/meta/transformer.py#L179-L192
def to_team(team): """Serializes team to id string :param team: object to serialize :return: string id """ from sevenbridges.models.team import Team if not team: raise SbgError('Team is required!') elif isinstance(team, Team): return team.id elif isinstance(team, six.string_types): return team else: raise SbgError('Invalid team parameter!')
[ "def", "to_team", "(", "team", ")", ":", "from", "sevenbridges", ".", "models", ".", "team", "import", "Team", "if", "not", "team", ":", "raise", "SbgError", "(", "'Team is required!'", ")", "elif", "isinstance", "(", "team", ",", "Team", ")", ":", "retu...
Serializes team to id string :param team: object to serialize :return: string id
[ "Serializes", "team", "to", "id", "string", ":", "param", "team", ":", "object", "to", "serialize", ":", "return", ":", "string", "id" ]
python
train
Miserlou/Zappa
zappa/utilities.py
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L430-L436
def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) return event_source_obj.status(funk)
[ "def", "get_event_source_status", "(", "event_source", ",", "lambda_arn", ",", "target_function", ",", "boto_session", ",", "dry", "=", "False", ")", ":", "event_source_obj", ",", "ctx", ",", "funk", "=", "get_event_source", "(", "event_source", ",", "lambda_arn",...
Given an event_source dictionary, create the object and get the event source status.
[ "Given", "an", "event_source", "dictionary", "create", "the", "object", "and", "get", "the", "event", "source", "status", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/__init__.py#L3714-L3737
def _set_overlay_policy_map(self, v, load=False): """ Setter method for overlay_policy_map, mapped from YANG variable /overlay_policy_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_overlay_policy_map is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_overlay_policy_map() directly. YANG Description: Define a policy-map[Actions on the classified packet]. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("pmap_name",overlay_policy_map.overlay_policy_map, yang_name="overlay-policy-map", rest_name="overlay-policy-map", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='pmap-name', extensions={u'tailf-common': {u'info': u'Overlay Policy Map Configuration', u'cli-no-key-completion': None, u'cli-full-no': None, u'sort-priority': u'75', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'OverlayPolicyMapCallPoint', u'cli-mode-name': u'config-overlay-policymap-$(pmap-name)'}}), is_container='list', yang_name="overlay-policy-map", rest_name="overlay-policy-map", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Overlay Policy Map Configuration', u'cli-no-key-completion': None, u'cli-full-no': None, u'sort-priority': u'75', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'OverlayPolicyMapCallPoint', u'cli-mode-name': u'config-overlay-policymap-$(pmap-name)'}}, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """overlay_policy_map must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("pmap_name",overlay_policy_map.overlay_policy_map, yang_name="overlay-policy-map", rest_name="overlay-policy-map", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='pmap-name', extensions={u'tailf-common': {u'info': u'Overlay Policy Map Configuration', u'cli-no-key-completion': None, u'cli-full-no': None, u'sort-priority': u'75', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'OverlayPolicyMapCallPoint', u'cli-mode-name': u'config-overlay-policymap-$(pmap-name)'}}), is_container='list', yang_name="overlay-policy-map", rest_name="overlay-policy-map", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Overlay Policy Map Configuration', u'cli-no-key-completion': None, u'cli-full-no': None, u'sort-priority': u'75', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'OverlayPolicyMapCallPoint', u'cli-mode-name': u'config-overlay-policymap-$(pmap-name)'}}, namespace='urn:brocade.com:mgmt:brocade-overlay-policy', defining_module='brocade-overlay-policy', yang_type='list', is_config=True)""", }) self.__overlay_policy_map = t if hasattr(self, '_set'): self._set()
[ "def", "_set_overlay_policy_map", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ","...
Setter method for overlay_policy_map, mapped from YANG variable /overlay_policy_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_overlay_policy_map is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_overlay_policy_map() directly. YANG Description: Define a policy-map[Actions on the classified packet].
[ "Setter", "method", "for", "overlay_policy_map", "mapped", "from", "YANG", "variable", "/", "overlay_policy_map", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file", ...
python
train
daknuett/py_register_machine2
core/parts.py
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/parts.py#L110-L125
def write_word(self, offset, word): """ .. _write_word: Writes one word from a device, see read_word_. """ self._lock = True if(offset > self.current_max_offset): raise BUSError("Offset({}) exceeds address space of BUS({})".format(offset, self.current_max_offset)) self.writes += 1 self.truncate.setvalue(word) for addresspace, device in self.index.items(): if(offset in addresspace): device.write(offset - self.start_addresses[device], self.truncate.getvalue())
[ "def", "write_word", "(", "self", ",", "offset", ",", "word", ")", ":", "self", ".", "_lock", "=", "True", "if", "(", "offset", ">", "self", ".", "current_max_offset", ")", ":", "raise", "BUSError", "(", "\"Offset({}) exceeds address space of BUS({})\"", ".", ...
.. _write_word: Writes one word from a device, see read_word_.
[ "..", "_write_word", ":" ]
python
train
saltstack/salt
salt/utils/win_lgpo_netsh.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L473-L538
def set_settings(profile, setting, value, store='local'): ''' Configure firewall settings. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall setting to configure. Valid options are: - localfirewallrules - localconsecrules - inboundusernotification - remotemanagement - unicastresponsetomulticast value (str): The value to apply to the setting. Valid options are - enable - disable - notconfigured store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect ''' # Input validation if profile.lower() not in ('domain', 'public', 'private'): raise ValueError('Incorrect profile: {0}'.format(profile)) if setting.lower() not in ('localfirewallrules', 'localconsecrules', 'inboundusernotification', 'remotemanagement', 'unicastresponsetomulticast'): raise ValueError('Incorrect setting: {0}'.format(setting)) if value.lower() not in ('enable', 'disable', 'notconfigured'): raise ValueError('Incorrect value: {0}'.format(value)) # Run the command command = 'set {0}profile settings {1} {2}'.format(profile, setting, value) results = _netsh_command(command=command, store=store) # A successful run should return an empty list if results: raise CommandExecutionError('An error occurred: {0}'.format(results)) return True
[ "def", "set_settings", "(", "profile", ",", "setting", ",", "value", ",", "store", "=", "'local'", ")", ":", "# Input validation", "if", "profile", ".", "lower", "(", ")", "not", "in", "(", "'domain'", ",", "'public'", ",", "'private'", ")", ":", "raise"...
Configure firewall settings. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall setting to configure. Valid options are: - localfirewallrules - localconsecrules - inboundusernotification - remotemanagement - unicastresponsetomulticast value (str): The value to apply to the setting. Valid options are - enable - disable - notconfigured store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect
[ "Configure", "firewall", "settings", "." ]
python
train
gc3-uzh-ch/elasticluster
elasticluster/cluster.py
https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L209-L218
def to_dict(self, omit=()): """ Return a (shallow) copy of self cast to a dictionary, optionally omitting some key/value pairs. """ result = self.__dict__.copy() for key in omit: if key in result: del result[key] return result
[ "def", "to_dict", "(", "self", ",", "omit", "=", "(", ")", ")", ":", "result", "=", "self", ".", "__dict__", ".", "copy", "(", ")", "for", "key", "in", "omit", ":", "if", "key", "in", "result", ":", "del", "result", "[", "key", "]", "return", "...
Return a (shallow) copy of self cast to a dictionary, optionally omitting some key/value pairs.
[ "Return", "a", "(", "shallow", ")", "copy", "of", "self", "cast", "to", "a", "dictionary", "optionally", "omitting", "some", "key", "/", "value", "pairs", "." ]
python
train
ewels/MultiQC
multiqc/modules/goleft_indexcov/goleft_indexcov.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/goleft_indexcov/goleft_indexcov.py#L26-L46
def _short_chrom(self, chrom): """Plot standard chromosomes + X, sorted numerically. Allows specification from a list of chromosomes via config for non-standard genomes. """ default_allowed = set(["X"]) allowed_chroms = set(getattr(config, "goleft_indexcov_config", {}).get("chromosomes", [])) chrom_clean = chrom.replace("chr", "") try: chrom_clean = int(chrom_clean) except ValueError: if chrom_clean not in default_allowed and chrom_clean not in allowed_chroms: chrom_clean = None if allowed_chroms: if chrom in allowed_chroms or chrom_clean in allowed_chroms: return chrom_clean elif isinstance(chrom_clean, int) or chrom_clean in default_allowed: return chrom_clean
[ "def", "_short_chrom", "(", "self", ",", "chrom", ")", ":", "default_allowed", "=", "set", "(", "[", "\"X\"", "]", ")", "allowed_chroms", "=", "set", "(", "getattr", "(", "config", ",", "\"goleft_indexcov_config\"", ",", "{", "}", ")", ".", "get", "(", ...
Plot standard chromosomes + X, sorted numerically. Allows specification from a list of chromosomes via config for non-standard genomes.
[ "Plot", "standard", "chromosomes", "+", "X", "sorted", "numerically", "." ]
python
train
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3117-L3137
def can_be_internationally_dialled(numobj): """Returns True if the number can only be dialled from outside the region, or unknown. If the number can only be dialled from within the region as well, returns False. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country). Arguments: numobj -- the phone number objectfor which we want to know whether it is diallable from outside the region. """ metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) if metadata is None: # Note numbers belonging to non-geographical entities (e.g. +800 # numbers) are always internationally diallable, and will be caught # here. return True nsn = national_significant_number(numobj) return not _is_number_matching_desc(nsn, metadata.no_international_dialling)
[ "def", "can_be_internationally_dialled", "(", "numobj", ")", ":", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code_for_number", "(", "numobj", ")", ",", "None", ")", "if", "metadata", "is", "None", ":", "# Note numbers belonging to non-g...
Returns True if the number can only be dialled from outside the region, or unknown. If the number can only be dialled from within the region as well, returns False. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country). Arguments: numobj -- the phone number objectfor which we want to know whether it is diallable from outside the region.
[ "Returns", "True", "if", "the", "number", "can", "only", "be", "dialled", "from", "outside", "the", "region", "or", "unknown", "." ]
python
train
rojopolis/lycanthropy
lycanthropy/lycanthropy.py
https://github.com/rojopolis/lycanthropy/blob/1a5ce2828714fc0e34780ac866532d4106d1a05b/lycanthropy/lycanthropy.py#L53-L76
def morph_dict(d, convert_function): """ Convert a nested dictionary from one convention to another. Args: d (dict): dictionary (nested or not) to be converted. convert_function (func): function that takes the string in one convention and returns it in the other one. Returns: Dictionary with the new keys. """ # Attribution: https://stackoverflow.com/a/33668421/633213 new = {} for k, v in six.iteritems(d): new_v = v if isinstance(v, dict): new_v = morph_dict(v, convert_function) elif isinstance(v, list): new_v = list() for x in v: new_v.append( morph_dict(x, convert_function) ) new[convert_function(k)] = new_v return new
[ "def", "morph_dict", "(", "d", ",", "convert_function", ")", ":", "# Attribution: https://stackoverflow.com/a/33668421/633213", "new", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "d", ")", ":", "new_v", "=", "v", "if", "isinstanc...
Convert a nested dictionary from one convention to another. Args: d (dict): dictionary (nested or not) to be converted. convert_function (func): function that takes the string in one convention and returns it in the other one. Returns: Dictionary with the new keys.
[ "Convert", "a", "nested", "dictionary", "from", "one", "convention", "to", "another", ".", "Args", ":", "d", "(", "dict", ")", ":", "dictionary", "(", "nested", "or", "not", ")", "to", "be", "converted", ".", "convert_function", "(", "func", ")", ":", ...
python
train
gwpy/gwpy
gwpy/io/ligolw.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/ligolw.py#L434-L451
def get_ligolw_element(xmldoc): """Find an existing <LIGO_LW> element in this XML Document """ from ligo.lw.ligolw import LIGO_LW try: from glue.ligolw.ligolw import LIGO_LW as LIGO_LW2 except ImportError: ligolw_types = (LIGO_LW,) else: ligolw_types = (LIGO_LW, LIGO_LW2) if isinstance(xmldoc, ligolw_types): return xmldoc else: for node in xmldoc.childNodes: if isinstance(node, ligolw_types): return node raise ValueError("Cannot find LIGO_LW element in XML Document")
[ "def", "get_ligolw_element", "(", "xmldoc", ")", ":", "from", "ligo", ".", "lw", ".", "ligolw", "import", "LIGO_LW", "try", ":", "from", "glue", ".", "ligolw", ".", "ligolw", "import", "LIGO_LW", "as", "LIGO_LW2", "except", "ImportError", ":", "ligolw_types"...
Find an existing <LIGO_LW> element in this XML Document
[ "Find", "an", "existing", "<LIGO_LW", ">", "element", "in", "this", "XML", "Document" ]
python
train
SuperCowPowers/workbench
workbench/server/data_store.py
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/data_store.py#L280-L290
def _list_samples(self, predicate=None): """List all samples that meet the predicate or all if predicate is not specified. Args: predicate: Match samples against this predicate (or all if not specified) Returns: List of the md5s for the matching samples """ cursor = self.database[self.sample_collection].find(predicate, {'_id':0, 'md5':1}) return [item['md5'] for item in cursor]
[ "def", "_list_samples", "(", "self", ",", "predicate", "=", "None", ")", ":", "cursor", "=", "self", ".", "database", "[", "self", ".", "sample_collection", "]", ".", "find", "(", "predicate", ",", "{", "'_id'", ":", "0", ",", "'md5'", ":", "1", "}",...
List all samples that meet the predicate or all if predicate is not specified. Args: predicate: Match samples against this predicate (or all if not specified) Returns: List of the md5s for the matching samples
[ "List", "all", "samples", "that", "meet", "the", "predicate", "or", "all", "if", "predicate", "is", "not", "specified", "." ]
python
train
TrainerDex/TrainerDex.py
trainerdex/client.py
https://github.com/TrainerDex/TrainerDex.py/blob/a693e1321abf2825f74bcbf29f0800f0c6835b62/trainerdex/client.py#L184-L190
def get_detailed_update(self, uid, uuid): """Returns the update object for the ID""" r = requests.get(api_url+'users/'+str(uid)+'/update/'+str(uuid)+'/', headers=self.headers) print(request_status(r)) r.raise_for_status() return Update(r.json())
[ "def", "get_detailed_update", "(", "self", ",", "uid", ",", "uuid", ")", ":", "r", "=", "requests", ".", "get", "(", "api_url", "+", "'users/'", "+", "str", "(", "uid", ")", "+", "'/update/'", "+", "str", "(", "uuid", ")", "+", "'/'", ",", "headers...
Returns the update object for the ID
[ "Returns", "the", "update", "object", "for", "the", "ID" ]
python
train