identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
WorkingSet.find
(self, req)
Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned.
Find a distribution matching requirement `req`
def find(self, req): """Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned. """ dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) return dist
[ "def", "find", "(", "self", ",", "req", ")", ":", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "not", "None", "and", "dist", "not", "in", "req", ":", "# XXX add more info", "raise", "VersionConflict", "(", "dist", ",", "req", ")", "return", "dist" ]
[ 629, 4 ]
[ 643, 19 ]
python
en
['en', 'en', 'en']
True
WorkingSet.iter_entry_points
(self, group, name=None)
Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order).
Yield entry point objects from `group` matching `name`
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order). """ return ( entry for dist in self for entry in dist.get_entry_map(group).values() if name is None or name == entry.name )
[ "def", "iter_entry_points", "(", "self", ",", "group", ",", "name", "=", "None", ")", ":", "return", "(", "entry", "for", "dist", "in", "self", "for", "entry", "in", "dist", ".", "get_entry_map", "(", "group", ")", ".", "values", "(", ")", "if", "name", "is", "None", "or", "name", "==", "entry", ".", "name", ")" ]
[ 645, 4 ]
[ 657, 9 ]
python
en
['en', 'en', 'en']
True
WorkingSet.run_script
(self, requires, script_name)
Locate distribution for `requires` and run `script_name` script
Locate distribution for `requires` and run `script_name` script
def run_script(self, requires, script_name): """Locate distribution for `requires` and run `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
[ "def", "run_script", "(", "self", ",", "requires", ",", "script_name", ")", ":", "ns", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", "name", "=", "ns", "[", "'__name__'", "]", "ns", ".", "clear", "(", ")", "ns", "[", "'__name__'", "]", "=", "name", "self", ".", "require", "(", "requires", ")", "[", "0", "]", ".", "run_script", "(", "script_name", ",", "ns", ")" ]
[ 659, 4 ]
[ 665, 61 ]
python
en
['en', 'en', 'en']
True
WorkingSet.__iter__
(self)
Yield distributions for non-duplicate projects in the working set The yield order is the order in which the items' path entries were added to the working set.
Yield distributions for non-duplicate projects in the working set
def __iter__(self): """Yield distributions for non-duplicate projects in the working set The yield order is the order in which the items' path entries were added to the working set. """ seen = {} for item in self.entries: if item not in self.entry_keys: # workaround a cache issue continue for key in self.entry_keys[item]: if key not in seen: seen[key] = 1 yield self.by_key[key]
[ "def", "__iter__", "(", "self", ")", ":", "seen", "=", "{", "}", "for", "item", "in", "self", ".", "entries", ":", "if", "item", "not", "in", "self", ".", "entry_keys", ":", "# workaround a cache issue", "continue", "for", "key", "in", "self", ".", "entry_keys", "[", "item", "]", ":", "if", "key", "not", "in", "seen", ":", "seen", "[", "key", "]", "=", "1", "yield", "self", ".", "by_key", "[", "key", "]" ]
[ 667, 4 ]
[ 682, 42 ]
python
en
['en', 'en', 'en']
True
WorkingSet.add
(self, dist, entry=None, insert=True, replace=False)
Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set's ``.entries`` (if it wasn't already present). `dist` is only added to the working set if it's for a project that doesn't already have a distribution in the set, unless `replace=True`. If it's added, any callbacks registered with the ``subscribe()`` method will be called.
Add `dist` to working set, associated with `entry`
def add(self, dist, entry=None, insert=True, replace=False): """Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set's ``.entries`` (if it wasn't already present). `dist` is only added to the working set if it's for a project that doesn't already have a distribution in the set, unless `replace=True`. If it's added, any callbacks registered with the ``subscribe()`` method will be called. """ if insert: dist.insert_on(self.entries, entry, replace=replace) if entry is None: entry = dist.location keys = self.entry_keys.setdefault(entry, []) keys2 = self.entry_keys.setdefault(dist.location, []) if not replace and dist.key in self.by_key: # ignore hidden distros return self.by_key[dist.key] = dist if dist.key not in keys: keys.append(dist.key) if dist.key not in keys2: keys2.append(dist.key) self._added_new(dist)
[ "def", "add", "(", "self", ",", "dist", ",", "entry", "=", "None", ",", "insert", "=", "True", ",", "replace", "=", "False", ")", ":", "if", "insert", ":", "dist", ".", "insert_on", "(", "self", ".", "entries", ",", "entry", ",", "replace", "=", "replace", ")", "if", "entry", "is", "None", ":", "entry", "=", "dist", ".", "location", "keys", "=", "self", ".", "entry_keys", ".", "setdefault", "(", "entry", ",", "[", "]", ")", "keys2", "=", "self", ".", "entry_keys", ".", "setdefault", "(", "dist", ".", "location", ",", "[", "]", ")", "if", "not", "replace", "and", "dist", ".", "key", "in", "self", ".", "by_key", ":", "# ignore hidden distros", "return", "self", ".", "by_key", "[", "dist", ".", "key", "]", "=", "dist", "if", "dist", ".", "key", "not", "in", "keys", ":", "keys", ".", "append", "(", "dist", ".", "key", ")", "if", "dist", ".", "key", "not", "in", "keys2", ":", "keys2", ".", "append", "(", "dist", ".", "key", ")", "self", ".", "_added_new", "(", "dist", ")" ]
[ 684, 4 ]
[ 712, 29 ]
python
en
['en', 'en', 'en']
True
WorkingSet.resolve
(self, requirements, env=None, installer=None, replace_conflicting=False, extras=None)
List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. `extras` is a list of the extras to be used with these requirements. This is important because extra requirements may look like `my_req; extra = "my_extra"`, which would otherwise be interpreted as a purely optional requirement. Instead, we want to be able to assert that these requirements are truly required.
List all distributions needed to (recursively) meet `requirements`
def resolve(self, requirements, env=None, installer=None, replace_conflicting=False, extras=None): """List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. `extras` is a list of the extras to be used with these requirements. This is important because extra requirements may look like `my_req; extra = "my_extra"`, which would otherwise be interpreted as a purely optional requirement. Instead, we want to be able to assert that these requirements are truly required. """ # set up the stack requirements = list(requirements)[::-1] # set of processed requirements processed = {} # key -> dist best = {} to_activate = [] req_extras = _ReqExtras() # Mapping of requirement to set of distributions that required it; # useful for reporting info about conflicts. required_by = collections.defaultdict(set) while requirements: # process dependencies breadth-first req = requirements.pop(0) if req in processed: # Ignore cyclic or redundant dependencies continue if not req_extras.markers_pass(req, extras): continue dist = best.get(req.key) if dist is None: # Find the best distribution and add it to the map dist = self.by_key.get(req.key) if dist is None or (dist not in req and replace_conflicting): ws = self if env is None: if dist is None: env = Environment(self.entries) else: # Use an empty environment and workingset to avoid # any further conflicts with the conflicting # distribution env = Environment([]) ws = WorkingSet([]) dist = best[req.key] = env.best_match( req, ws, installer, replace_conflicting=replace_conflicting ) if dist is None: requirers = required_by.get(req, None) raise DistributionNotFound(req, requirers) to_activate.append(dist) if dist not in req: # Oops, the "best" so far conflicts with a dependency dependent_req = required_by[req] raise VersionConflict(dist, req).with_context(dependent_req) # push the new requirements onto the stack new_requirements = dist.requires(req.extras)[::-1] requirements.extend(new_requirements) # Register the new requirements needed by req for new_requirement in new_requirements: required_by[new_requirement].add(req.project_name) req_extras[new_requirement] = req.extras processed[req] = True # return list of distros to activate return to_activate
[ "def", "resolve", "(", "self", ",", "requirements", ",", "env", "=", "None", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ",", "extras", "=", "None", ")", ":", "# set up the stack", "requirements", "=", "list", "(", "requirements", ")", "[", ":", ":", "-", "1", "]", "# set of processed requirements", "processed", "=", "{", "}", "# key -> dist", "best", "=", "{", "}", "to_activate", "=", "[", "]", "req_extras", "=", "_ReqExtras", "(", ")", "# Mapping of requirement to set of distributions that required it;", "# useful for reporting info about conflicts.", "required_by", "=", "collections", ".", "defaultdict", "(", "set", ")", "while", "requirements", ":", "# process dependencies breadth-first", "req", "=", "requirements", ".", "pop", "(", "0", ")", "if", "req", "in", "processed", ":", "# Ignore cyclic or redundant dependencies", "continue", "if", "not", "req_extras", ".", "markers_pass", "(", "req", ",", "extras", ")", ":", "continue", "dist", "=", "best", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", ":", "# Find the best distribution and add it to the map", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", "or", "(", "dist", "not", "in", "req", "and", "replace_conflicting", ")", ":", "ws", "=", "self", "if", "env", "is", "None", ":", "if", "dist", "is", "None", ":", "env", "=", "Environment", "(", "self", ".", "entries", ")", "else", ":", "# Use an empty environment and workingset to avoid", "# any further conflicts with the conflicting", "# distribution", "env", "=", "Environment", "(", "[", "]", ")", "ws", "=", "WorkingSet", "(", "[", "]", ")", "dist", "=", "best", "[", "req", ".", "key", "]", "=", "env", ".", "best_match", "(", "req", ",", "ws", ",", "installer", ",", "replace_conflicting", "=", "replace_conflicting", ")", "if", "dist", "is", "None", ":", "requirers", "=", "required_by", ".", "get", "(", "req", ",", "None", ")", "raise", "DistributionNotFound", "(", "req", ",", "requirers", ")", "to_activate", ".", "append", "(", "dist", ")", "if", "dist", "not", "in", "req", ":", "# Oops, the \"best\" so far conflicts with a dependency", "dependent_req", "=", "required_by", "[", "req", "]", "raise", "VersionConflict", "(", "dist", ",", "req", ")", ".", "with_context", "(", "dependent_req", ")", "# push the new requirements onto the stack", "new_requirements", "=", "dist", ".", "requires", "(", "req", ".", "extras", ")", "[", ":", ":", "-", "1", "]", "requirements", ".", "extend", "(", "new_requirements", ")", "# Register the new requirements needed by req", "for", "new_requirement", "in", "new_requirements", ":", "required_by", "[", "new_requirement", "]", ".", "add", "(", "req", ".", "project_name", ")", "req_extras", "[", "new_requirement", "]", "=", "req", ".", "extras", "processed", "[", "req", "]", "=", "True", "# return list of distros to activate", "return", "to_activate" ]
[ 714, 4 ]
[ 804, 26 ]
python
en
['en', 'en', 'en']
True
WorkingSet.find_plugins
( self, plugin_env, full_env=None, installer=None, fallback=True)
Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance.
Find all activatable distributions in `plugin_env`
def find_plugins( self, plugin_env, full_env=None, installer=None, fallback=True): """Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance. """ plugin_projects = list(plugin_env) # scan project names in alphabetic order plugin_projects.sort() error_info = {} distributions = {} if full_env is None: env = Environment(self.entries) env += plugin_env else: env = full_env + plugin_env shadow_set = self.__class__([]) # put all our entries in shadow_set list(map(shadow_set.add, self)) for project_name in plugin_projects: for dist in plugin_env[project_name]: req = [dist.as_requirement()] try: resolvees = shadow_set.resolve(req, env, installer) except ResolutionError as v: # save error info error_info[dist] = v if fallback: # try the next older version of project continue else: # give up on this project, keep going break else: list(map(shadow_set.add, resolvees)) distributions.update(dict.fromkeys(resolvees)) # success, no need to try any more versions of this project break distributions = list(distributions) distributions.sort() return distributions, error_info
[ "def", "find_plugins", "(", "self", ",", "plugin_env", ",", "full_env", "=", "None", ",", "installer", "=", "None", ",", "fallback", "=", "True", ")", ":", "plugin_projects", "=", "list", "(", "plugin_env", ")", "# scan project names in alphabetic order", "plugin_projects", ".", "sort", "(", ")", "error_info", "=", "{", "}", "distributions", "=", "{", "}", "if", "full_env", "is", "None", ":", "env", "=", "Environment", "(", "self", ".", "entries", ")", "env", "+=", "plugin_env", "else", ":", "env", "=", "full_env", "+", "plugin_env", "shadow_set", "=", "self", ".", "__class__", "(", "[", "]", ")", "# put all our entries in shadow_set", "list", "(", "map", "(", "shadow_set", ".", "add", ",", "self", ")", ")", "for", "project_name", "in", "plugin_projects", ":", "for", "dist", "in", "plugin_env", "[", "project_name", "]", ":", "req", "=", "[", "dist", ".", "as_requirement", "(", ")", "]", "try", ":", "resolvees", "=", "shadow_set", ".", "resolve", "(", "req", ",", "env", ",", "installer", ")", "except", "ResolutionError", "as", "v", ":", "# save error info", "error_info", "[", "dist", "]", "=", "v", "if", "fallback", ":", "# try the next older version of project", "continue", "else", ":", "# give up on this project, keep going", "break", "else", ":", "list", "(", "map", "(", "shadow_set", ".", "add", ",", "resolvees", ")", ")", "distributions", ".", "update", "(", "dict", ".", "fromkeys", "(", "resolvees", ")", ")", "# success, no need to try any more versions of this project", "break", "distributions", "=", "list", "(", "distributions", ")", "distributions", ".", "sort", "(", ")", "return", "distributions", ",", "error_info" ]
[ 806, 4 ]
[ 888, 40 ]
python
en
['en', 'en', 'en']
True
WorkingSet.require
(self, *requirements)
Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set.
Ensure that distributions matching `requirements` are activated
def require(self, *requirements): """Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set. """ needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
[ "def", "require", "(", "self", ",", "*", "requirements", ")", ":", "needed", "=", "self", ".", "resolve", "(", "parse_requirements", "(", "requirements", ")", ")", "for", "dist", "in", "needed", ":", "self", ".", "add", "(", "dist", ")", "return", "needed" ]
[ 890, 4 ]
[ 904, 21 ]
python
en
['en', 'en', 'en']
True
WorkingSet.subscribe
(self, callback, existing=True)
Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well.
Invoke `callback` for all distributions
def subscribe(self, callback, existing=True): """Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well. """ if callback in self.callbacks: return self.callbacks.append(callback) if not existing: return for dist in self: callback(dist)
[ "def", "subscribe", "(", "self", ",", "callback", ",", "existing", "=", "True", ")", ":", "if", "callback", "in", "self", ".", "callbacks", ":", "return", "self", ".", "callbacks", ".", "append", "(", "callback", ")", "if", "not", "existing", ":", "return", "for", "dist", "in", "self", ":", "callback", "(", "dist", ")" ]
[ 906, 4 ]
[ 918, 26 ]
python
en
['en', 'no', 'en']
True
_ReqExtras.markers_pass
(self, req, extras=None)
Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True.
Evaluate markers for req against each extra that demanded it.
def markers_pass(self, req, extras=None): """ Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True. """ extra_evals = ( req.marker.evaluate({'extra': extra}) for extra in self.get(req, ()) + (extras or (None,)) ) return not req.marker or any(extra_evals)
[ "def", "markers_pass", "(", "self", ",", "req", ",", "extras", "=", "None", ")", ":", "extra_evals", "=", "(", "req", ".", "marker", ".", "evaluate", "(", "{", "'extra'", ":", "extra", "}", ")", "for", "extra", "in", "self", ".", "get", "(", "req", ",", "(", ")", ")", "+", "(", "extras", "or", "(", "None", ",", ")", ")", ")", "return", "not", "req", ".", "marker", "or", "any", "(", "extra_evals", ")" ]
[ 943, 4 ]
[ 955, 49 ]
python
en
['en', 'error', 'th']
False
Environment.__init__
( self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR)
Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distributions must be compatible with. If unspecified, it defaults to the current platform. `python` is an optional string naming the desired version of Python (e.g. ``'3.6'``); it defaults to the current version. You may explicitly set `platform` (and/or `python`) to ``None`` if you wish to map *all* distributions, not just those compatible with the running platform or Python version.
Snapshot distributions available on a search path
def __init__( self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR): """Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distributions must be compatible with. If unspecified, it defaults to the current platform. `python` is an optional string naming the desired version of Python (e.g. ``'3.6'``); it defaults to the current version. You may explicitly set `platform` (and/or `python`) to ``None`` if you wish to map *all* distributions, not just those compatible with the running platform or Python version. """ self._distmap = {} self.platform = platform self.python = python self.scan(search_path)
[ "def", "__init__", "(", "self", ",", "search_path", "=", "None", ",", "platform", "=", "get_supported_platform", "(", ")", ",", "python", "=", "PY_MAJOR", ")", ":", "self", ".", "_distmap", "=", "{", "}", "self", ".", "platform", "=", "platform", "self", ".", "python", "=", "python", "self", ".", "scan", "(", "search_path", ")" ]
[ 961, 4 ]
[ 983, 30 ]
python
en
['en', 'en', 'en']
True
Environment.can_add
(self, dist)
Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned.
Is distribution `dist` acceptable for this environment?
def can_add(self, dist): """Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned. """ py_compat = ( self.python is None or dist.py_version is None or dist.py_version == self.python ) return py_compat and compatible_platforms(dist.platform, self.platform)
[ "def", "can_add", "(", "self", ",", "dist", ")", ":", "py_compat", "=", "(", "self", ".", "python", "is", "None", "or", "dist", ".", "py_version", "is", "None", "or", "dist", ".", "py_version", "==", "self", ".", "python", ")", "return", "py_compat", "and", "compatible_platforms", "(", "dist", ".", "platform", ",", "self", ".", "platform", ")" ]
[ 985, 4 ]
[ 997, 79 ]
python
en
['en', 'en', 'en']
True
Environment.remove
(self, dist)
Remove `dist` from the environment
Remove `dist` from the environment
def remove(self, dist): """Remove `dist` from the environment""" self._distmap[dist.key].remove(dist)
[ "def", "remove", "(", "self", ",", "dist", ")", ":", "self", ".", "_distmap", "[", "dist", ".", "key", "]", ".", "remove", "(", "dist", ")" ]
[ 999, 4 ]
[ 1001, 44 ]
python
en
['en', 'en', 'en']
True
Environment.scan
(self, search_path=None)
Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added.
Scan `search_path` for distributions usable in this environment
def scan(self, search_path=None): """Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added. """ if search_path is None: search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
[ "def", "scan", "(", "self", ",", "search_path", "=", "None", ")", ":", "if", "search_path", "is", "None", ":", "search_path", "=", "sys", ".", "path", "for", "item", "in", "search_path", ":", "for", "dist", "in", "find_distributions", "(", "item", ")", ":", "self", ".", "add", "(", "dist", ")" ]
[ 1003, 4 ]
[ 1016, 30 ]
python
en
['en', 'en', 'en']
True
Environment.__getitem__
(self, project_name)
Return a newest-to-oldest list of distributions for `project_name` Uses case-insensitive `project_name` comparison, assuming all the project's distributions use their project's name converted to all lowercase as their key.
Return a newest-to-oldest list of distributions for `project_name`
def __getitem__(self, project_name): """Return a newest-to-oldest list of distributions for `project_name` Uses case-insensitive `project_name` comparison, assuming all the project's distributions use their project's name converted to all lowercase as their key. """ distribution_key = project_name.lower() return self._distmap.get(distribution_key, [])
[ "def", "__getitem__", "(", "self", ",", "project_name", ")", ":", "distribution_key", "=", "project_name", ".", "lower", "(", ")", "return", "self", ".", "_distmap", ".", "get", "(", "distribution_key", ",", "[", "]", ")" ]
[ 1018, 4 ]
[ 1027, 54 ]
python
en
['en', 'en', 'en']
True
Environment.add
(self, dist)
Add `dist` if we ``can_add()`` it and it has not already been added
Add `dist` if we ``can_add()`` it and it has not already been added
def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
[ "def", "add", "(", "self", ",", "dist", ")", ":", "if", "self", ".", "can_add", "(", "dist", ")", "and", "dist", ".", "has_version", "(", ")", ":", "dists", "=", "self", ".", "_distmap", ".", "setdefault", "(", "dist", ".", "key", ",", "[", "]", ")", "if", "dist", "not", "in", "dists", ":", "dists", ".", "append", "(", "dist", ")", "dists", ".", "sort", "(", "key", "=", "operator", ".", "attrgetter", "(", "'hashcmp'", ")", ",", "reverse", "=", "True", ")" ]
[ 1029, 4 ]
[ 1036, 76 ]
python
en
['en', 'en', 'en']
True
Environment.best_match
( self, req, working_set, installer=None, replace_conflicting=False)
Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned.
Find distribution best matching `req` and usable on `working_set`
def best_match( self, req, working_set, installer=None, replace_conflicting=False): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned. """ try: dist = working_set.find(req) except VersionConflict: if not replace_conflicting: raise dist = None if dist is not None: return dist for dist in self[req.key]: if dist in req: return dist # try to download/install return self.obtain(req, installer)
[ "def", "best_match", "(", "self", ",", "req", ",", "working_set", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ")", ":", "try", ":", "dist", "=", "working_set", ".", "find", "(", "req", ")", "except", "VersionConflict", ":", "if", "not", "replace_conflicting", ":", "raise", "dist", "=", "None", "if", "dist", "is", "not", "None", ":", "return", "dist", "for", "dist", "in", "self", "[", "req", ".", "key", "]", ":", "if", "dist", "in", "req", ":", "return", "dist", "# try to download/install", "return", "self", ".", "obtain", "(", "req", ",", "installer", ")" ]
[ 1038, 4 ]
[ 1064, 42 ]
python
en
['en', 'en', 'en']
True
Environment.obtain
(self, requirement, installer=None)
Obtain a distribution matching `requirement` (e.g. via download) Obtain a distro that matches requirement (e.g. via download). In the base ``Environment`` class, this routine just returns ``installer(requirement)``, unless `installer` is None, in which case None is returned instead. This method is a hook that allows subclasses to attempt other ways of obtaining a distribution before falling back to the `installer` argument.
Obtain a distribution matching `requirement` (e.g. via download)
def obtain(self, requirement, installer=None): """Obtain a distribution matching `requirement` (e.g. via download) Obtain a distro that matches requirement (e.g. via download). In the base ``Environment`` class, this routine just returns ``installer(requirement)``, unless `installer` is None, in which case None is returned instead. This method is a hook that allows subclasses to attempt other ways of obtaining a distribution before falling back to the `installer` argument.""" if installer is not None: return installer(requirement)
[ "def", "obtain", "(", "self", ",", "requirement", ",", "installer", "=", "None", ")", ":", "if", "installer", "is", "not", "None", ":", "return", "installer", "(", "requirement", ")" ]
[ 1066, 4 ]
[ 1076, 41 ]
python
en
['it', 'en', 'en']
True
Environment.__iter__
(self)
Yield the unique project names of the available distributions
Yield the unique project names of the available distributions
def __iter__(self): """Yield the unique project names of the available distributions""" for key in self._distmap.keys(): if self[key]: yield key
[ "def", "__iter__", "(", "self", ")", ":", "for", "key", "in", "self", ".", "_distmap", ".", "keys", "(", ")", ":", "if", "self", "[", "key", "]", ":", "yield", "key" ]
[ 1078, 4 ]
[ 1082, 25 ]
python
en
['en', 'en', 'en']
True
Environment.__iadd__
(self, other)
In-place addition of a distribution or environment
In-place addition of a distribution or environment
def __iadd__(self, other): """In-place addition of a distribution or environment""" if isinstance(other, Distribution): self.add(other) elif isinstance(other, Environment): for project in other: for dist in other[project]: self.add(dist) else: raise TypeError("Can't add %r to environment" % (other,)) return self
[ "def", "__iadd__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Distribution", ")", ":", "self", ".", "add", "(", "other", ")", "elif", "isinstance", "(", "other", ",", "Environment", ")", ":", "for", "project", "in", "other", ":", "for", "dist", "in", "other", "[", "project", "]", ":", "self", ".", "add", "(", "dist", ")", "else", ":", "raise", "TypeError", "(", "\"Can't add %r to environment\"", "%", "(", "other", ",", ")", ")", "return", "self" ]
[ 1084, 4 ]
[ 1094, 19 ]
python
en
['en', 'en', 'en']
True
Environment.__add__
(self, other)
Add an environment or distribution to an environment
Add an environment or distribution to an environment
def __add__(self, other): """Add an environment or distribution to an environment""" new = self.__class__([], platform=None, python=None) for env in self, other: new += env return new
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "new", "=", "self", ".", "__class__", "(", "[", "]", ",", "platform", "=", "None", ",", "python", "=", "None", ")", "for", "env", "in", "self", ",", "other", ":", "new", "+=", "env", "return", "new" ]
[ 1096, 4 ]
[ 1101, 18 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_exists
(self, package_or_requirement, resource_name)
Does the named resource exist?
Does the named resource exist?
def resource_exists(self, package_or_requirement, resource_name): """Does the named resource exist?""" return get_provider(package_or_requirement).has_resource(resource_name)
[ "def", "resource_exists", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "has_resource", "(", "resource_name", ")" ]
[ 1131, 4 ]
[ 1133, 79 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_isdir
(self, package_or_requirement, resource_name)
Is the named resource an existing directory?
Is the named resource an existing directory?
def resource_isdir(self, package_or_requirement, resource_name): """Is the named resource an existing directory?""" return get_provider(package_or_requirement).resource_isdir( resource_name )
[ "def", "resource_isdir", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "resource_isdir", "(", "resource_name", ")" ]
[ 1135, 4 ]
[ 1139, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_filename
(self, package_or_requirement, resource_name)
Return a true filesystem path for specified resource
Return a true filesystem path for specified resource
def resource_filename(self, package_or_requirement, resource_name): """Return a true filesystem path for specified resource""" return get_provider(package_or_requirement).get_resource_filename( self, resource_name )
[ "def", "resource_filename", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_filename", "(", "self", ",", "resource_name", ")" ]
[ 1141, 4 ]
[ 1145, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_stream
(self, package_or_requirement, resource_name)
Return a readable file-like object for specified resource
Return a readable file-like object for specified resource
def resource_stream(self, package_or_requirement, resource_name): """Return a readable file-like object for specified resource""" return get_provider(package_or_requirement).get_resource_stream( self, resource_name )
[ "def", "resource_stream", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_stream", "(", "self", ",", "resource_name", ")" ]
[ 1147, 4 ]
[ 1151, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_string
(self, package_or_requirement, resource_name)
Return specified resource as a string
Return specified resource as a string
def resource_string(self, package_or_requirement, resource_name): """Return specified resource as a string""" return get_provider(package_or_requirement).get_resource_string( self, resource_name )
[ "def", "resource_string", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_string", "(", "self", ",", "resource_name", ")" ]
[ 1153, 4 ]
[ 1157, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_listdir
(self, package_or_requirement, resource_name)
List the contents of the named resource directory
List the contents of the named resource directory
def resource_listdir(self, package_or_requirement, resource_name): """List the contents of the named resource directory""" return get_provider(package_or_requirement).resource_listdir( resource_name )
[ "def", "resource_listdir", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "resource_listdir", "(", "resource_name", ")" ]
[ 1159, 4 ]
[ 1163, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.extraction_error
(self)
Give an error message for problems extracting file(s)
Give an error message for problems extracting file(s)
def extraction_error(self): """Give an error message for problems extracting file(s)""" old_exc = sys.exc_info()[1] cache_path = self.extraction_path or get_default_cache() tmpl = textwrap.dedent(""" Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: {old_exc} The Python egg cache directory is currently set to: {cache_path} Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. """).lstrip() err = ExtractionError(tmpl.format(**locals())) err.manager = self err.cache_path = cache_path err.original_error = old_exc raise err
[ "def", "extraction_error", "(", "self", ")", ":", "old_exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "cache_path", "=", "self", ".", "extraction_path", "or", "get_default_cache", "(", ")", "tmpl", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n Can't extract file(s) to egg cache\n\n The following error occurred while trying to extract file(s)\n to the Python egg cache:\n\n {old_exc}\n\n The Python egg cache directory is currently set to:\n\n {cache_path}\n\n Perhaps your account does not have write access to this directory?\n You can change the cache directory by setting the PYTHON_EGG_CACHE\n environment variable to point to an accessible directory.\n \"\"\"", ")", ".", "lstrip", "(", ")", "err", "=", "ExtractionError", "(", "tmpl", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")", "err", ".", "manager", "=", "self", "err", ".", "cache_path", "=", "cache_path", "err", ".", "original_error", "=", "old_exc", "raise", "err" ]
[ 1165, 4 ]
[ 1191, 17 ]
python
en
['en', 'en', 'en']
True
ResourceManager.get_cache_path
(self, archive_name, names=())
Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if provided, should be a sequence of path name parts "under" the egg's extraction location. This method should only be called by resource providers that need to obtain an extraction location, and only for names they intend to extract, as it tracks the generated names for possible cleanup later.
Return absolute location in cache for `archive_name` and `names`
def get_cache_path(self, archive_name, names=()): """Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if provided, should be a sequence of path name parts "under" the egg's extraction location. This method should only be called by resource providers that need to obtain an extraction location, and only for names they intend to extract, as it tracks the generated names for possible cleanup later. """ extract_path = self.extraction_path or get_default_cache() target_path = os.path.join(extract_path, archive_name + '-tmp', *names) try: _bypass_ensure_directory(target_path) except Exception: self.extraction_error() self._warn_unsafe_extraction_path(extract_path) self.cached_files[target_path] = 1 return target_path
[ "def", "get_cache_path", "(", "self", ",", "archive_name", ",", "names", "=", "(", ")", ")", ":", "extract_path", "=", "self", ".", "extraction_path", "or", "get_default_cache", "(", ")", "target_path", "=", "os", ".", "path", ".", "join", "(", "extract_path", ",", "archive_name", "+", "'-tmp'", ",", "*", "names", ")", "try", ":", "_bypass_ensure_directory", "(", "target_path", ")", "except", "Exception", ":", "self", ".", "extraction_error", "(", ")", "self", ".", "_warn_unsafe_extraction_path", "(", "extract_path", ")", "self", ".", "cached_files", "[", "target_path", "]", "=", "1", "return", "target_path" ]
[ 1193, 4 ]
[ 1216, 26 ]
python
en
['en', 'en', 'en']
True
ResourceManager._warn_unsafe_extraction_path
(path)
If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details.
If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used.
def _warn_unsafe_extraction_path(path): """ If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details. """ if os.name == 'nt' and not path.startswith(os.environ['windir']): # On Windows, permissions are generally restrictive by default # and temp directories are not writable by other users, so # bypass the warning. return mode = os.stat(path).st_mode if mode & stat.S_IWOTH or mode & stat.S_IWGRP: msg = ( "%s is writable by group/others and vulnerable to attack " "when " "used with get_resource_filename. Consider a more secure " "location (set with .set_extraction_path or the " "PYTHON_EGG_CACHE environment variable)." % path ) warnings.warn(msg, UserWarning)
[ "def", "_warn_unsafe_extraction_path", "(", "path", ")", ":", "if", "os", ".", "name", "==", "'nt'", "and", "not", "path", ".", "startswith", "(", "os", ".", "environ", "[", "'windir'", "]", ")", ":", "# On Windows, permissions are generally restrictive by default", "# and temp directories are not writable by other users, so", "# bypass the warning.", "return", "mode", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "if", "mode", "&", "stat", ".", "S_IWOTH", "or", "mode", "&", "stat", ".", "S_IWGRP", ":", "msg", "=", "(", "\"%s is writable by group/others and vulnerable to attack \"", "\"when \"", "\"used with get_resource_filename. Consider a more secure \"", "\"location (set with .set_extraction_path or the \"", "\"PYTHON_EGG_CACHE environment variable).\"", "%", "path", ")", "warnings", ".", "warn", "(", "msg", ",", "UserWarning", ")" ]
[ 1219, 4 ]
[ 1242, 43 ]
python
en
['en', 'error', 'th']
False
ResourceManager.postprocess
(self, tempname, filename)
Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns.
Perform any platform-specific postprocessing of `tempname`
def postprocess(self, tempname, filename): """Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns. """ if os.name == 'posix': # Make the resource executable mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777 os.chmod(tempname, mode)
[ "def", "postprocess", "(", "self", ",", "tempname", ",", "filename", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "# Make the resource executable", "mode", "=", "(", "(", "os", ".", "stat", "(", "tempname", ")", ".", "st_mode", ")", "|", "0o555", ")", "&", "0o7777", "os", ".", "chmod", "(", "tempname", ",", "mode", ")" ]
[ 1244, 4 ]
[ 1262, 36 ]
python
en
['en', 'en', 'en']
True
ResourceManager.set_extraction_path
(self, path)
Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that routine's documentation for more details.) Resources are extracted to subdirectories of this path based upon information given by the ``IResourceProvider``. You may set this to a temporary directory, but then you must call ``cleanup_resources()`` to delete the extracted files when done. There is no guarantee that ``cleanup_resources()`` will be able to remove all extracted files. (Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call ``cleanup_resources()``.)
Set the base path where resources will be extracted to, if needed.
def set_extraction_path(self, path): """Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that routine's documentation for more details.) Resources are extracted to subdirectories of this path based upon information given by the ``IResourceProvider``. You may set this to a temporary directory, but then you must call ``cleanup_resources()`` to delete the extracted files when done. There is no guarantee that ``cleanup_resources()`` will be able to remove all extracted files. (Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call ``cleanup_resources()``.) """ if self.cached_files: raise ValueError( "Can't change extraction path, files already extracted" ) self.extraction_path = path
[ "def", "set_extraction_path", "(", "self", ",", "path", ")", ":", "if", "self", ".", "cached_files", ":", "raise", "ValueError", "(", "\"Can't change extraction path, files already extracted\"", ")", "self", ".", "extraction_path", "=", "path" ]
[ 1264, 4 ]
[ 1288, 35 ]
python
en
['en', 'en', 'en']
True
ResourceManager.cleanup_resources
(self, force=False)
Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions.
Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions.
def cleanup_resources(self, force=False): """ Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions. """
[ "def", "cleanup_resources", "(", "self", ",", "force", "=", "False", ")", ":" ]
[ 1290, 4 ]
[ 1300, 11 ]
python
en
['en', 'error', 'th']
False
NullProvider._validate_resource_path
(path)
Validate the resource paths according to the docs. https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access >>> warned = getfixture('recwarn') >>> warnings.simplefilter('always') >>> vrp = NullProvider._validate_resource_path >>> vrp('foo/bar.txt') >>> bool(warned) False >>> vrp('../foo/bar.txt') >>> bool(warned) True >>> warned.clear() >>> vrp('/foo/bar.txt') >>> bool(warned) True >>> vrp('foo/../../bar.txt') >>> bool(warned) True >>> warned.clear() >>> vrp('foo/f../bar.txt') >>> bool(warned) False Windows path separators are straight-up disallowed. >>> vrp(r'\\foo/bar.txt') Traceback (most recent call last): ... ValueError: Use of .. or absolute path in a resource path \ is not allowed. >>> vrp(r'C:\\foo/bar.txt') Traceback (most recent call last): ... ValueError: Use of .. or absolute path in a resource path \ is not allowed. Blank values are allowed >>> vrp('') >>> bool(warned) False Non-string values are not. >>> vrp(None) Traceback (most recent call last): ... AttributeError: ...
Validate the resource paths according to the docs. https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access
def _validate_resource_path(path): """ Validate the resource paths according to the docs. https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access >>> warned = getfixture('recwarn') >>> warnings.simplefilter('always') >>> vrp = NullProvider._validate_resource_path >>> vrp('foo/bar.txt') >>> bool(warned) False >>> vrp('../foo/bar.txt') >>> bool(warned) True >>> warned.clear() >>> vrp('/foo/bar.txt') >>> bool(warned) True >>> vrp('foo/../../bar.txt') >>> bool(warned) True >>> warned.clear() >>> vrp('foo/f../bar.txt') >>> bool(warned) False Windows path separators are straight-up disallowed. >>> vrp(r'\\foo/bar.txt') Traceback (most recent call last): ... ValueError: Use of .. or absolute path in a resource path \ is not allowed. >>> vrp(r'C:\\foo/bar.txt') Traceback (most recent call last): ... ValueError: Use of .. or absolute path in a resource path \ is not allowed. Blank values are allowed >>> vrp('') >>> bool(warned) False Non-string values are not. >>> vrp(None) Traceback (most recent call last): ... AttributeError: ... """ invalid = ( os.path.pardir in path.split(posixpath.sep) or posixpath.isabs(path) or ntpath.isabs(path) ) if not invalid: return msg = "Use of .. or absolute path in a resource path is not allowed." # Aggressively disallow Windows absolute paths if ntpath.isabs(path) and not posixpath.isabs(path): raise ValueError(msg) # for compatibility, warn; in future # raise ValueError(msg) warnings.warn( msg[:-1] + " and will raise exceptions in a future release.", DeprecationWarning, stacklevel=4, )
[ "def", "_validate_resource_path", "(", "path", ")", ":", "invalid", "=", "(", "os", ".", "path", ".", "pardir", "in", "path", ".", "split", "(", "posixpath", ".", "sep", ")", "or", "posixpath", ".", "isabs", "(", "path", ")", "or", "ntpath", ".", "isabs", "(", "path", ")", ")", "if", "not", "invalid", ":", "return", "msg", "=", "\"Use of .. or absolute path in a resource path is not allowed.\"", "# Aggressively disallow Windows absolute paths", "if", "ntpath", ".", "isabs", "(", "path", ")", "and", "not", "posixpath", ".", "isabs", "(", "path", ")", ":", "raise", "ValueError", "(", "msg", ")", "# for compatibility, warn; in future", "# raise ValueError(msg)", "warnings", ".", "warn", "(", "msg", "[", ":", "-", "1", "]", "+", "\" and will raise exceptions in a future release.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "4", ",", ")" ]
[ 1492, 4 ]
[ 1564, 9 ]
python
en
['en', 'error', 'th']
False
ZipManifests.build
(cls, path)
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows.
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects.
def build(cls, path): """ Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows. """ with zipfile.ZipFile(path) as zfile: items = ( ( name.replace('/', os.sep), zfile.getinfo(name), ) for name in zfile.namelist() ) return dict(items)
[ "def", "build", "(", "cls", ",", "path", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "path", ")", "as", "zfile", ":", "items", "=", "(", "(", "name", ".", "replace", "(", "'/'", ",", "os", ".", "sep", ")", ",", "zfile", ".", "getinfo", "(", "name", ")", ",", ")", "for", "name", "in", "zfile", ".", "namelist", "(", ")", ")", "return", "dict", "(", "items", ")" ]
[ 1655, 4 ]
[ 1671, 30 ]
python
en
['en', 'error', 'th']
False
MemoizedZipManifests.load
(self, path)
Load a manifest at path or return a suitable manifest already loaded.
Load a manifest at path or return a suitable manifest already loaded.
def load(self, path): """ Load a manifest at path or return a suitable manifest already loaded. """ path = os.path.normpath(path) mtime = os.stat(path).st_mtime if path not in self or self[path].mtime != mtime: manifest = self.build(path) self[path] = self.manifest_mod(manifest, mtime) return self[path].manifest
[ "def", "load", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "mtime", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mtime", "if", "path", "not", "in", "self", "or", "self", "[", "path", "]", ".", "mtime", "!=", "mtime", ":", "manifest", "=", "self", ".", "build", "(", "path", ")", "self", "[", "path", "]", "=", "self", ".", "manifest_mod", "(", "manifest", ",", "mtime", ")", "return", "self", "[", "path", "]", ".", "manifest" ]
[ 1682, 4 ]
[ 1693, 34 ]
python
en
['en', 'error', 'th']
False
ZipProvider._is_current
(self, file_path, zip_path)
Return True if the file_path is current for this zip_path
Return True if the file_path is current for this zip_path
def _is_current(self, file_path, zip_path): """ Return True if the file_path is current for this zip_path """ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not os.path.isfile(file_path): return False stat = os.stat(file_path) if stat.st_size != size or stat.st_mtime != timestamp: return False # check that the contents match zip_contents = self.loader.get_data(zip_path) with open(file_path, 'rb') as f: file_contents = f.read() return zip_contents == file_contents
[ "def", "_is_current", "(", "self", ",", "file_path", ",", "zip_path", ")", ":", "timestamp", ",", "size", "=", "self", ".", "_get_date_and_size", "(", "self", ".", "zipinfo", "[", "zip_path", "]", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "False", "stat", "=", "os", ".", "stat", "(", "file_path", ")", "if", "stat", ".", "st_size", "!=", "size", "or", "stat", ".", "st_mtime", "!=", "timestamp", ":", "return", "False", "# check that the contents match", "zip_contents", "=", "self", ".", "loader", ".", "get_data", "(", "zip_path", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "file_contents", "=", "f", ".", "read", "(", ")", "return", "zip_contents", "==", "file_contents" ]
[ 1809, 4 ]
[ 1823, 44 ]
python
en
['en', 'error', 'th']
False
EggMetadata.__init__
(self, importer)
Create a metadata provider from a zipimporter
Create a metadata provider from a zipimporter
def __init__(self, importer): """Create a metadata provider from a zipimporter""" self.zip_pre = importer.archive + os.sep self.loader = importer if importer.prefix: self.module_path = os.path.join(importer.archive, importer.prefix) else: self.module_path = importer.archive self._setup_prefix()
[ "def", "__init__", "(", "self", ",", "importer", ")", ":", "self", ".", "zip_pre", "=", "importer", ".", "archive", "+", "os", ".", "sep", "self", ".", "loader", "=", "importer", "if", "importer", ".", "prefix", ":", "self", ".", "module_path", "=", "os", ".", "path", ".", "join", "(", "importer", ".", "archive", ",", "importer", ".", "prefix", ")", "else", ":", "self", ".", "module_path", "=", "importer", ".", "archive", "self", ".", "_setup_prefix", "(", ")" ]
[ 1941, 4 ]
[ 1950, 28 ]
python
en
['en', 'en', 'en']
True
EntryPoint.load
(self, require=True, *args, **kwargs)
Require packages for this EntryPoint, then resolve it.
Require packages for this EntryPoint, then resolve it.
def load(self, require=True, *args, **kwargs): """ Require packages for this EntryPoint, then resolve it. """ if not require or args or kwargs: warnings.warn( "Parameters to load are deprecated. Call .resolve and " ".require separately.", PkgResourcesDeprecationWarning, stacklevel=2, ) if require: self.require(*args, **kwargs) return self.resolve()
[ "def", "load", "(", "self", ",", "require", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "require", "or", "args", "or", "kwargs", ":", "warnings", ".", "warn", "(", "\"Parameters to load are deprecated. Call .resolve and \"", "\".require separately.\"", ",", "PkgResourcesDeprecationWarning", ",", "stacklevel", "=", "2", ",", ")", "if", "require", ":", "self", ".", "require", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "resolve", "(", ")" ]
[ 2429, 4 ]
[ 2442, 29 ]
python
en
['en', 'error', 'th']
False
EntryPoint.resolve
(self)
Resolve the entry point from its module and attrs.
Resolve the entry point from its module and attrs.
def resolve(self): """ Resolve the entry point from its module and attrs. """ module = __import__(self.module_name, fromlist=['__name__'], level=0) try: return functools.reduce(getattr, self.attrs, module) except AttributeError as exc: raise ImportError(str(exc))
[ "def", "resolve", "(", "self", ")", ":", "module", "=", "__import__", "(", "self", ".", "module_name", ",", "fromlist", "=", "[", "'__name__'", "]", ",", "level", "=", "0", ")", "try", ":", "return", "functools", ".", "reduce", "(", "getattr", ",", "self", ".", "attrs", ",", "module", ")", "except", "AttributeError", "as", "exc", ":", "raise", "ImportError", "(", "str", "(", "exc", ")", ")" ]
[ 2444, 4 ]
[ 2452, 39 ]
python
en
['en', 'error', 'th']
False
EntryPoint.parse
(cls, src, dist=None)
Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional
Parse a single entry point from string `src`
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional """ m = cls.pattern.match(src) if not m: msg = "EntryPoint must be in 'name=module:attrs [extras]' format" raise ValueError(msg, src) res = m.groupdict() extras = cls._parse_extras(res['extras']) attrs = res['attr'].split('.') if res['attr'] else () return cls(res['name'], res['module'], attrs, extras, dist)
[ "def", "parse", "(", "cls", ",", "src", ",", "dist", "=", "None", ")", ":", "m", "=", "cls", ".", "pattern", ".", "match", "(", "src", ")", "if", "not", "m", ":", "msg", "=", "\"EntryPoint must be in 'name=module:attrs [extras]' format\"", "raise", "ValueError", "(", "msg", ",", "src", ")", "res", "=", "m", ".", "groupdict", "(", ")", "extras", "=", "cls", ".", "_parse_extras", "(", "res", "[", "'extras'", "]", ")", "attrs", "=", "res", "[", "'attr'", "]", ".", "split", "(", "'.'", ")", "if", "res", "[", "'attr'", "]", "else", "(", ")", "return", "cls", "(", "res", "[", "'name'", "]", ",", "res", "[", "'module'", "]", ",", "attrs", ",", "extras", ",", "dist", ")" ]
[ 2477, 4 ]
[ 2494, 67 ]
python
en
['en', 'en', 'en']
True
EntryPoint.parse_group
(cls, group, lines, dist=None)
Parse an entry point group
Parse an entry point group
def parse_group(cls, group, lines, dist=None): """Parse an entry point group""" if not MODULE(group): raise ValueError("Invalid group name", group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if ep.name in this: raise ValueError("Duplicate entry point", group, ep.name) this[ep.name] = ep return this
[ "def", "parse_group", "(", "cls", ",", "group", ",", "lines", ",", "dist", "=", "None", ")", ":", "if", "not", "MODULE", "(", "group", ")", ":", "raise", "ValueError", "(", "\"Invalid group name\"", ",", "group", ")", "this", "=", "{", "}", "for", "line", "in", "yield_lines", "(", "lines", ")", ":", "ep", "=", "cls", ".", "parse", "(", "line", ",", "dist", ")", "if", "ep", ".", "name", "in", "this", ":", "raise", "ValueError", "(", "\"Duplicate entry point\"", ",", "group", ",", "ep", ".", "name", ")", "this", "[", "ep", ".", "name", "]", "=", "ep", "return", "this" ]
[ 2506, 4 ]
[ 2516, 19 ]
python
en
['en', 'en', 'en']
True
EntryPoint.parse_map
(cls, data, dist=None)
Parse a map of entry point groups
Parse a map of entry point groups
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps
[ "def", "parse_map", "(", "cls", ",", "data", ",", "dist", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "data", ".", "items", "(", ")", "else", ":", "data", "=", "split_sections", "(", "data", ")", "maps", "=", "{", "}", "for", "group", ",", "lines", "in", "data", ":", "if", "group", "is", "None", ":", "if", "not", "lines", ":", "continue", "raise", "ValueError", "(", "\"Entry points must be listed in groups\"", ")", "group", "=", "group", ".", "strip", "(", ")", "if", "group", "in", "maps", ":", "raise", "ValueError", "(", "\"Duplicate group name\"", ",", "group", ")", "maps", "[", "group", "]", "=", "cls", ".", "parse_group", "(", "group", ",", "lines", ",", "dist", ")", "return", "maps" ]
[ 2519, 4 ]
[ 2535, 19 ]
python
en
['en', 'en', 'en']
True
Distribution._dep_map
(self)
A map of extra to its list of (direct) requirements for this distribution, including the null extra.
A map of extra to its list of (direct) requirements for this distribution, including the null extra.
def _dep_map(self): """ A map of extra to its list of (direct) requirements for this distribution, including the null extra. """ try: return self.__dep_map except AttributeError: self.__dep_map = self._filter_extras(self._build_dep_map()) return self.__dep_map
[ "def", "_dep_map", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__dep_map", "except", "AttributeError", ":", "self", ".", "__dep_map", "=", "self", ".", "_filter_extras", "(", "self", ".", "_build_dep_map", "(", ")", ")", "return", "self", ".", "__dep_map" ]
[ 2693, 4 ]
[ 2702, 29 ]
python
en
['en', 'error', 'th']
False
Distribution._filter_extras
(dm)
Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers.
Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers.
def _filter_extras(dm): """ Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers. """ for extra in list(filter(None, dm)): new_extra = extra reqs = dm.pop(extra) new_extra, _, marker = extra.partition(':') fails_marker = marker and ( invalid_marker(marker) or not evaluate_marker(marker) ) if fails_marker: reqs = [] new_extra = safe_extra(new_extra) or None dm.setdefault(new_extra, []).extend(reqs) return dm
[ "def", "_filter_extras", "(", "dm", ")", ":", "for", "extra", "in", "list", "(", "filter", "(", "None", ",", "dm", ")", ")", ":", "new_extra", "=", "extra", "reqs", "=", "dm", ".", "pop", "(", "extra", ")", "new_extra", ",", "_", ",", "marker", "=", "extra", ".", "partition", "(", "':'", ")", "fails_marker", "=", "marker", "and", "(", "invalid_marker", "(", "marker", ")", "or", "not", "evaluate_marker", "(", "marker", ")", ")", "if", "fails_marker", ":", "reqs", "=", "[", "]", "new_extra", "=", "safe_extra", "(", "new_extra", ")", "or", "None", "dm", ".", "setdefault", "(", "new_extra", ",", "[", "]", ")", ".", "extend", "(", "reqs", ")", "return", "dm" ]
[ 2705, 4 ]
[ 2724, 17 ]
python
en
['en', 'error', 'th']
False
Distribution.requires
(self, extras=())
List of Requirements needed for this distro if `extras` are used
List of Requirements needed for this distro if `extras` are used
def requires(self, extras=()): """List of Requirements needed for this distro if `extras` are used""" dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such extra feature %r" % (self, ext) ) return deps
[ "def", "requires", "(", "self", ",", "extras", "=", "(", ")", ")", ":", "dm", "=", "self", ".", "_dep_map", "deps", "=", "[", "]", "deps", ".", "extend", "(", "dm", ".", "get", "(", "None", ",", "(", ")", ")", ")", "for", "ext", "in", "extras", ":", "try", ":", "deps", ".", "extend", "(", "dm", "[", "safe_extra", "(", "ext", ")", "]", ")", "except", "KeyError", ":", "raise", "UnknownExtra", "(", "\"%s has no such extra feature %r\"", "%", "(", "self", ",", "ext", ")", ")", "return", "deps" ]
[ 2733, 4 ]
[ 2745, 19 ]
python
en
['en', 'en', 'en']
True
Distribution._get_metadata_path_for_display
(self, name)
Return the path to the given metadata file, if available.
Return the path to the given metadata file, if available.
def _get_metadata_path_for_display(self, name): """ Return the path to the given metadata file, if available. """ try: # We need to access _get_metadata_path() on the provider object # directly rather than through this class's __getattr__() # since _get_metadata_path() is marked private. path = self._provider._get_metadata_path(name) # Handle exceptions e.g. in case the distribution's metadata # provider doesn't support _get_metadata_path(). except Exception: return '[could not detect]' return path
[ "def", "_get_metadata_path_for_display", "(", "self", ",", "name", ")", ":", "try", ":", "# We need to access _get_metadata_path() on the provider object", "# directly rather than through this class's __getattr__()", "# since _get_metadata_path() is marked private.", "path", "=", "self", ".", "_provider", ".", "_get_metadata_path", "(", "name", ")", "# Handle exceptions e.g. in case the distribution's metadata", "# provider doesn't support _get_metadata_path().", "except", "Exception", ":", "return", "'[could not detect]'", "return", "path" ]
[ 2747, 4 ]
[ 2762, 19 ]
python
en
['en', 'error', 'th']
False
Distribution.activate
(self, path=None, replace=False)
Ensure distribution is importable on `path` (default=sys.path)
Ensure distribution is importable on `path` (default=sys.path)
def activate(self, path=None, replace=False): """Ensure distribution is importable on `path` (default=sys.path)""" if path is None: path = sys.path self.insert_on(path, replace=replace) if path is sys.path: fixup_namespace_packages(self.location) for pkg in self._get_metadata('namespace_packages.txt'): if pkg in sys.modules: declare_namespace(pkg)
[ "def", "activate", "(", "self", ",", "path", "=", "None", ",", "replace", "=", "False", ")", ":", "if", "path", "is", "None", ":", "path", "=", "sys", ".", "path", "self", ".", "insert_on", "(", "path", ",", "replace", "=", "replace", ")", "if", "path", "is", "sys", ".", "path", ":", "fixup_namespace_packages", "(", "self", ".", "location", ")", "for", "pkg", "in", "self", ".", "_get_metadata", "(", "'namespace_packages.txt'", ")", ":", "if", "pkg", "in", "sys", ".", "modules", ":", "declare_namespace", "(", "pkg", ")" ]
[ 2775, 4 ]
[ 2784, 42 ]
python
en
['en', 'en', 'en']
True
Distribution.egg_name
(self)
Return what this distribution's standard .egg filename should be
Return what this distribution's standard .egg filename should be
def egg_name(self): """Return what this distribution's standard .egg filename should be""" filename = "%s-%s-py%s" % ( to_filename(self.project_name), to_filename(self.version), self.py_version or PY_MAJOR ) if self.platform: filename += '-' + self.platform return filename
[ "def", "egg_name", "(", "self", ")", ":", "filename", "=", "\"%s-%s-py%s\"", "%", "(", "to_filename", "(", "self", ".", "project_name", ")", ",", "to_filename", "(", "self", ".", "version", ")", ",", "self", ".", "py_version", "or", "PY_MAJOR", ")", "if", "self", ".", "platform", ":", "filename", "+=", "'-'", "+", "self", ".", "platform", "return", "filename" ]
[ 2786, 4 ]
[ 2795, 23 ]
python
en
['en', 'en', 'en']
True
Distribution.__getattr__
(self, attr)
Delegate all unrecognized public attributes to .metadata provider
Delegate all unrecognized public attributes to .metadata provider
def __getattr__(self, attr): """Delegate all unrecognized public attributes to .metadata provider""" if attr.startswith('_'): raise AttributeError(attr) return getattr(self._provider, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", ".", "startswith", "(", "'_'", ")", ":", "raise", "AttributeError", "(", "attr", ")", "return", "getattr", "(", "self", ".", "_provider", ",", "attr", ")" ]
[ 2811, 4 ]
[ 2815, 44 ]
python
en
['en', 'it', 'en']
True
Distribution.as_requirement
(self)
Return a ``Requirement`` that matches this distribution exactly
Return a ``Requirement`` that matches this distribution exactly
def as_requirement(self): """Return a ``Requirement`` that matches this distribution exactly""" if isinstance(self.parsed_version, packaging.version.Version): spec = "%s==%s" % (self.project_name, self.parsed_version) else: spec = "%s===%s" % (self.project_name, self.parsed_version) return Requirement.parse(spec)
[ "def", "as_requirement", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "parsed_version", ",", "packaging", ".", "version", ".", "Version", ")", ":", "spec", "=", "\"%s==%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "else", ":", "spec", "=", "\"%s===%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "return", "Requirement", ".", "parse", "(", "spec", ")" ]
[ 2837, 4 ]
[ 2844, 38 ]
python
en
['en', 'en', 'en']
True
Distribution.load_entry_point
(self, group, name)
Return the `name` entry point of `group` or raise ImportError
Return the `name` entry point of `group` or raise ImportError
def load_entry_point(self, group, name): """Return the `name` entry point of `group` or raise ImportError""" ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load()
[ "def", "load_entry_point", "(", "self", ",", "group", ",", "name", ")", ":", "ep", "=", "self", ".", "get_entry_info", "(", "group", ",", "name", ")", "if", "ep", "is", "None", ":", "raise", "ImportError", "(", "\"Entry point %r not found\"", "%", "(", "(", "group", ",", "name", ")", ",", ")", ")", "return", "ep", ".", "load", "(", ")" ]
[ 2846, 4 ]
[ 2851, 24 ]
python
en
['en', 'en', 'en']
True
Distribution.get_entry_map
(self, group=None)
Return the entry point map for `group`, or the full entry map
Return the entry point map for `group`, or the full entry map
def get_entry_map(self, group=None): """Return the entry point map for `group`, or the full entry map""" try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map( self._get_metadata('entry_points.txt'), self ) if group is not None: return ep_map.get(group, {}) return ep_map
[ "def", "get_entry_map", "(", "self", ",", "group", "=", "None", ")", ":", "try", ":", "ep_map", "=", "self", ".", "_ep_map", "except", "AttributeError", ":", "ep_map", "=", "self", ".", "_ep_map", "=", "EntryPoint", ".", "parse_map", "(", "self", ".", "_get_metadata", "(", "'entry_points.txt'", ")", ",", "self", ")", "if", "group", "is", "not", "None", ":", "return", "ep_map", ".", "get", "(", "group", ",", "{", "}", ")", "return", "ep_map" ]
[ 2853, 4 ]
[ 2863, 21 ]
python
en
['en', 'en', 'en']
True
Distribution.get_entry_info
(self, group, name)
Return the EntryPoint object for `group`+`name`, or ``None``
Return the EntryPoint object for `group`+`name`, or ``None``
def get_entry_info(self, group, name): """Return the EntryPoint object for `group`+`name`, or ``None``""" return self.get_entry_map(group).get(name)
[ "def", "get_entry_info", "(", "self", ",", "group", ",", "name", ")", ":", "return", "self", ".", "get_entry_map", "(", "group", ")", ".", "get", "(", "name", ")" ]
[ 2865, 4 ]
[ 2867, 50 ]
python
en
['en', 'en', 'en']
True
Distribution.insert_on
(self, path, loc=None, replace=False)
Ensure self.location is on path If replace=False (default): - If location is already in path anywhere, do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent. - Else: add to the end of path. If replace=True: - If location is already on path anywhere (not eggs) or higher priority than its parent (eggs) do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent, removing any lower-priority entries. - Else: add it to the front of path.
Ensure self.location is on path
def insert_on(self, path, loc=None, replace=False): """Ensure self.location is on path If replace=False (default): - If location is already in path anywhere, do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent. - Else: add to the end of path. If replace=True: - If location is already on path anywhere (not eggs) or higher priority than its parent (eggs) do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent, removing any lower-priority entries. - Else: add it to the front of path. """ loc = loc or self.location if not loc: return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [(p and _normalize_cached(p) or p) for p in path] for p, item in enumerate(npath): if item == nloc: if replace: break else: # don't modify path (even removing duplicates) if # found and not replace return elif item == bdir and self.precedence == EGG_DIST: # if it's an .egg, give it precedence over its directory # UNLESS it's already been added to sys.path and replace=False if (not replace) and nloc in npath[p:]: return if path is sys.path: self.check_version_conflict() path.insert(p, loc) npath.insert(p, nloc) break else: if path is sys.path: self.check_version_conflict() if replace: path.insert(0, loc) else: path.append(loc) return # p is the spot where we found or inserted loc; now remove duplicates while True: try: np = npath.index(nloc, p + 1) except ValueError: break else: del npath[np], path[np] # ha! p = np return
[ "def", "insert_on", "(", "self", ",", "path", ",", "loc", "=", "None", ",", "replace", "=", "False", ")", ":", "loc", "=", "loc", "or", "self", ".", "location", "if", "not", "loc", ":", "return", "nloc", "=", "_normalize_cached", "(", "loc", ")", "bdir", "=", "os", ".", "path", ".", "dirname", "(", "nloc", ")", "npath", "=", "[", "(", "p", "and", "_normalize_cached", "(", "p", ")", "or", "p", ")", "for", "p", "in", "path", "]", "for", "p", ",", "item", "in", "enumerate", "(", "npath", ")", ":", "if", "item", "==", "nloc", ":", "if", "replace", ":", "break", "else", ":", "# don't modify path (even removing duplicates) if", "# found and not replace", "return", "elif", "item", "==", "bdir", "and", "self", ".", "precedence", "==", "EGG_DIST", ":", "# if it's an .egg, give it precedence over its directory", "# UNLESS it's already been added to sys.path and replace=False", "if", "(", "not", "replace", ")", "and", "nloc", "in", "npath", "[", "p", ":", "]", ":", "return", "if", "path", "is", "sys", ".", "path", ":", "self", ".", "check_version_conflict", "(", ")", "path", ".", "insert", "(", "p", ",", "loc", ")", "npath", ".", "insert", "(", "p", ",", "nloc", ")", "break", "else", ":", "if", "path", "is", "sys", ".", "path", ":", "self", ".", "check_version_conflict", "(", ")", "if", "replace", ":", "path", ".", "insert", "(", "0", ",", "loc", ")", "else", ":", "path", ".", "append", "(", "loc", ")", "return", "# p is the spot where we found or inserted loc; now remove duplicates", "while", "True", ":", "try", ":", "np", "=", "npath", ".", "index", "(", "nloc", ",", "p", "+", "1", ")", "except", "ValueError", ":", "break", "else", ":", "del", "npath", "[", "np", "]", ",", "path", "[", "np", "]", "# ha!", "p", "=", "np", "return" ]
[ 2869, 4 ]
[ 2935, 14 ]
python
en
['en', 'en', 'en']
True
Distribution.clone
(self, **kw)
Copy this distribution, substituting in any changed keyword args
Copy this distribution, substituting in any changed keyword args
def clone(self, **kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
[ "def", "clone", "(", "self", ",", "*", "*", "kw", ")", ":", "names", "=", "'project_name version py_version platform location precedence'", "for", "attr", "in", "names", ".", "split", "(", ")", ":", "kw", ".", "setdefault", "(", "attr", ",", "getattr", "(", "self", ",", "attr", ",", "None", ")", ")", "kw", ".", "setdefault", "(", "'metadata'", ",", "self", ".", "_provider", ")", "return", "self", ".", "__class__", "(", "*", "*", "kw", ")" ]
[ 2967, 4 ]
[ 2973, 35 ]
python
en
['en', 'en', 'en']
True
EggInfoDistribution._reload_version
(self)
Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename.
Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename.
def _reload_version(self): """ Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename. """ md_version = self._get_version() if md_version: self._version = md_version return self
[ "def", "_reload_version", "(", "self", ")", ":", "md_version", "=", "self", ".", "_get_version", "(", ")", "if", "md_version", ":", "self", ".", "_version", "=", "md_version", "return", "self" ]
[ 2981, 4 ]
[ 2996, 19 ]
python
en
['en', 'error', 'th']
False
_normalize_name
(name)
Make a name consistent regardless of source (environment or file)
Make a name consistent regardless of source (environment or file)
def _normalize_name(name): # type: (str) -> str """Make a name consistent regardless of source (environment or file) """ name = name.lower().replace('_', '-') if name.startswith('--'): name = name[2:] # only prefer long opts return name
[ "def", "_normalize_name", "(", "name", ")", ":", "# type: (str) -> str", "name", "=", "name", ".", "lower", "(", ")", ".", "replace", "(", "'_'", ",", "'-'", ")", "if", "name", ".", "startswith", "(", "'--'", ")", ":", "name", "=", "name", "[", "2", ":", "]", "# only prefer long opts", "return", "name" ]
[ 49, 0 ]
[ 56, 15 ]
python
en
['en', 'en', 'en']
True
Configuration.load
(self)
Loads configuration from configuration files and environment
Loads configuration from configuration files and environment
def load(self): # type: () -> None """Loads configuration from configuration files and environment """ self._load_config_files() if not self.isolated: self._load_environment_vars()
[ "def", "load", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_load_config_files", "(", ")", "if", "not", "self", ".", "isolated", ":", "self", ".", "_load_environment_vars", "(", ")" ]
[ 129, 4 ]
[ 135, 41 ]
python
en
['en', 'en', 'en']
True
Configuration.get_file_to_edit
(self)
Returns the file with highest priority in configuration
Returns the file with highest priority in configuration
def get_file_to_edit(self): # type: () -> Optional[str] """Returns the file with highest priority in configuration """ assert self.load_only is not None, \ "Need to be specified a file to be editing" try: return self._get_parser_to_modify()[0] except IndexError: return None
[ "def", "get_file_to_edit", "(", "self", ")", ":", "# type: () -> Optional[str]", "assert", "self", ".", "load_only", "is", "not", "None", ",", "\"Need to be specified a file to be editing\"", "try", ":", "return", "self", ".", "_get_parser_to_modify", "(", ")", "[", "0", "]", "except", "IndexError", ":", "return", "None" ]
[ 137, 4 ]
[ 147, 23 ]
python
en
['en', 'en', 'en']
True
Configuration.items
(self)
Returns key-value pairs like dict.items() representing the loaded configuration
Returns key-value pairs like dict.items() representing the loaded configuration
def items(self): # type: () -> Iterable[Tuple[str, Any]] """Returns key-value pairs like dict.items() representing the loaded configuration """ return self._dictionary.items()
[ "def", "items", "(", "self", ")", ":", "# type: () -> Iterable[Tuple[str, Any]]", "return", "self", ".", "_dictionary", ".", "items", "(", ")" ]
[ 149, 4 ]
[ 154, 39 ]
python
en
['en', 'en', 'en']
True
Configuration.get_value
(self, key)
Get a value from the configuration.
Get a value from the configuration.
def get_value(self, key): # type: (str) -> Any """Get a value from the configuration. """ try: return self._dictionary[key] except KeyError: raise ConfigurationError(f"No such key - {key}")
[ "def", "get_value", "(", "self", ",", "key", ")", ":", "# type: (str) -> Any", "try", ":", "return", "self", ".", "_dictionary", "[", "key", "]", "except", "KeyError", ":", "raise", "ConfigurationError", "(", "f\"No such key - {key}\"", ")" ]
[ 156, 4 ]
[ 163, 60 ]
python
en
['en', 'en', 'en']
True
Configuration.set_value
(self, key, value)
Modify a value in the configuration.
Modify a value in the configuration.
def set_value(self, key, value): # type: (str, Any) -> None """Modify a value in the configuration. """ self._ensure_have_load_only() assert self.load_only fname, parser = self._get_parser_to_modify() if parser is not None: section, name = _disassemble_key(key) # Modify the parser and the configuration if not parser.has_section(section): parser.add_section(section) parser.set(section, name, value) self._config[self.load_only][key] = value self._mark_as_modified(fname, parser)
[ "def", "set_value", "(", "self", ",", "key", ",", "value", ")", ":", "# type: (str, Any) -> None", "self", ".", "_ensure_have_load_only", "(", ")", "assert", "self", ".", "load_only", "fname", ",", "parser", "=", "self", ".", "_get_parser_to_modify", "(", ")", "if", "parser", "is", "not", "None", ":", "section", ",", "name", "=", "_disassemble_key", "(", "key", ")", "# Modify the parser and the configuration", "if", "not", "parser", ".", "has_section", "(", "section", ")", ":", "parser", ".", "add_section", "(", "section", ")", "parser", ".", "set", "(", "section", ",", "name", ",", "value", ")", "self", ".", "_config", "[", "self", ".", "load_only", "]", "[", "key", "]", "=", "value", "self", ".", "_mark_as_modified", "(", "fname", ",", "parser", ")" ]
[ 165, 4 ]
[ 183, 45 ]
python
en
['en', 'it', 'en']
True
Configuration.unset_value
(self, key)
Unset a value in the configuration.
Unset a value in the configuration.
def unset_value(self, key): # type: (str) -> None """Unset a value in the configuration.""" self._ensure_have_load_only() assert self.load_only if key not in self._config[self.load_only]: raise ConfigurationError(f"No such key - {key}") fname, parser = self._get_parser_to_modify() if parser is not None: section, name = _disassemble_key(key) if not (parser.has_section(section) and parser.remove_option(section, name)): # The option was not removed. raise ConfigurationError( "Fatal Internal error [id=1]. Please report as a bug." ) # The section may be empty after the option was removed. if not parser.items(section): parser.remove_section(section) self._mark_as_modified(fname, parser) del self._config[self.load_only][key]
[ "def", "unset_value", "(", "self", ",", "key", ")", ":", "# type: (str) -> None", "self", ".", "_ensure_have_load_only", "(", ")", "assert", "self", ".", "load_only", "if", "key", "not", "in", "self", ".", "_config", "[", "self", ".", "load_only", "]", ":", "raise", "ConfigurationError", "(", "f\"No such key - {key}\"", ")", "fname", ",", "parser", "=", "self", ".", "_get_parser_to_modify", "(", ")", "if", "parser", "is", "not", "None", ":", "section", ",", "name", "=", "_disassemble_key", "(", "key", ")", "if", "not", "(", "parser", ".", "has_section", "(", "section", ")", "and", "parser", ".", "remove_option", "(", "section", ",", "name", ")", ")", ":", "# The option was not removed.", "raise", "ConfigurationError", "(", "\"Fatal Internal error [id=1]. Please report as a bug.\"", ")", "# The section may be empty after the option was removed.", "if", "not", "parser", ".", "items", "(", "section", ")", ":", "parser", ".", "remove_section", "(", "section", ")", "self", ".", "_mark_as_modified", "(", "fname", ",", "parser", ")", "del", "self", ".", "_config", "[", "self", ".", "load_only", "]", "[", "key", "]" ]
[ 185, 4 ]
[ 210, 45 ]
python
en
['en', 'en', 'en']
True
Configuration.save
(self)
Save the current in-memory state.
Save the current in-memory state.
def save(self): # type: () -> None """Save the current in-memory state. """ self._ensure_have_load_only() for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname) # Ensure directory exists. ensure_dir(os.path.dirname(fname)) with open(fname, "w") as f: parser.write(f)
[ "def", "save", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_ensure_have_load_only", "(", ")", "for", "fname", ",", "parser", "in", "self", ".", "_modified_parsers", ":", "logger", ".", "info", "(", "\"Writing to %s\"", ",", "fname", ")", "# Ensure directory exists.", "ensure_dir", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", ")", "with", "open", "(", "fname", ",", "\"w\"", ")", "as", "f", ":", "parser", ".", "write", "(", "f", ")" ]
[ 212, 4 ]
[ 225, 31 ]
python
en
['en', 'en', 'en']
True
Configuration._dictionary
(self)
A dictionary representing the loaded configuration.
A dictionary representing the loaded configuration.
def _dictionary(self): # type: () -> Dict[str, Any] """A dictionary representing the loaded configuration. """ # NOTE: Dictionaries are not populated if not loaded. So, conditionals # are not needed here. retval = {} for variant in OVERRIDE_ORDER: retval.update(self._config[variant]) return retval
[ "def", "_dictionary", "(", "self", ")", ":", "# type: () -> Dict[str, Any]", "# NOTE: Dictionaries are not populated if not loaded. So, conditionals", "# are not needed here.", "retval", "=", "{", "}", "for", "variant", "in", "OVERRIDE_ORDER", ":", "retval", ".", "update", "(", "self", ".", "_config", "[", "variant", "]", ")", "return", "retval" ]
[ 238, 4 ]
[ 249, 21 ]
python
en
['en', 'en', 'en']
True
Configuration._load_config_files
(self)
Loads configuration from configuration files
Loads configuration from configuration files
def _load_config_files(self): # type: () -> None """Loads configuration from configuration files """ config_files = dict(self.iter_config_files()) if config_files[kinds.ENV][0:1] == [os.devnull]: logger.debug( "Skipping loading configuration files due to " "environment's PIP_CONFIG_FILE being os.devnull" ) return for variant, files in config_files.items(): for fname in files: # If there's specific variant set in `load_only`, load only # that variant, not the others. if self.load_only is not None and variant != self.load_only: logger.debug( "Skipping file '%s' (variant: %s)", fname, variant ) continue parser = self._load_file(variant, fname) # Keeping track of the parsers used self._parsers[variant].append((fname, parser))
[ "def", "_load_config_files", "(", "self", ")", ":", "# type: () -> None", "config_files", "=", "dict", "(", "self", ".", "iter_config_files", "(", ")", ")", "if", "config_files", "[", "kinds", ".", "ENV", "]", "[", "0", ":", "1", "]", "==", "[", "os", ".", "devnull", "]", ":", "logger", ".", "debug", "(", "\"Skipping loading configuration files due to \"", "\"environment's PIP_CONFIG_FILE being os.devnull\"", ")", "return", "for", "variant", ",", "files", "in", "config_files", ".", "items", "(", ")", ":", "for", "fname", "in", "files", ":", "# If there's specific variant set in `load_only`, load only", "# that variant, not the others.", "if", "self", ".", "load_only", "is", "not", "None", "and", "variant", "!=", "self", ".", "load_only", ":", "logger", ".", "debug", "(", "\"Skipping file '%s' (variant: %s)\"", ",", "fname", ",", "variant", ")", "continue", "parser", "=", "self", ".", "_load_file", "(", "variant", ",", "fname", ")", "# Keeping track of the parsers used", "self", ".", "_parsers", "[", "variant", "]", ".", "append", "(", "(", "fname", ",", "parser", ")", ")" ]
[ 251, 4 ]
[ 276, 62 ]
python
en
['en', 'en', 'en']
True
Configuration._load_environment_vars
(self)
Loads configuration from environment variables
Loads configuration from environment variables
def _load_environment_vars(self): # type: () -> None """Loads configuration from environment variables """ self._config[kinds.ENV_VAR].update( self._normalized_keys(":env:", self.get_environ_vars()) )
[ "def", "_load_environment_vars", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_config", "[", "kinds", ".", "ENV_VAR", "]", ".", "update", "(", "self", ".", "_normalized_keys", "(", "\":env:\"", ",", "self", ".", "get_environ_vars", "(", ")", ")", ")" ]
[ 312, 4 ]
[ 318, 9 ]
python
en
['en', 'en', 'en']
True
Configuration._normalized_keys
(self, section, items)
Normalizes items to construct a dictionary with normalized keys. This routine is where the names become keys and are made the same regardless of source - configuration files or environment.
Normalizes items to construct a dictionary with normalized keys.
def _normalized_keys(self, section, items): # type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any] """Normalizes items to construct a dictionary with normalized keys. This routine is where the names become keys and are made the same regardless of source - configuration files or environment. """ normalized = {} for name, val in items: key = section + "." + _normalize_name(name) normalized[key] = val return normalized
[ "def", "_normalized_keys", "(", "self", ",", "section", ",", "items", ")", ":", "# type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any]", "normalized", "=", "{", "}", "for", "name", ",", "val", "in", "items", ":", "key", "=", "section", "+", "\".\"", "+", "_normalize_name", "(", "name", ")", "normalized", "[", "key", "]", "=", "val", "return", "normalized" ]
[ 320, 4 ]
[ 331, 25 ]
python
en
['en', 'en', 'en']
True
Configuration.get_environ_vars
(self)
Returns a generator with all environmental vars with prefix PIP_
Returns a generator with all environmental vars with prefix PIP_
def get_environ_vars(self): # type: () -> Iterable[Tuple[str, str]] """Returns a generator with all environmental vars with prefix PIP_""" for key, val in os.environ.items(): if key.startswith("PIP_"): name = key[4:].lower() if name not in ENV_NAMES_IGNORED: yield name, val
[ "def", "get_environ_vars", "(", "self", ")", ":", "# type: () -> Iterable[Tuple[str, str]]", "for", "key", ",", "val", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "\"PIP_\"", ")", ":", "name", "=", "key", "[", "4", ":", "]", ".", "lower", "(", ")", "if", "name", "not", "in", "ENV_NAMES_IGNORED", ":", "yield", "name", ",", "val" ]
[ 333, 4 ]
[ 340, 35 ]
python
en
['en', 'en', 'en']
True
Configuration.iter_config_files
(self)
Yields variant and configuration files associated with it. This should be treated like items of a dictionary.
Yields variant and configuration files associated with it.
def iter_config_files(self): # type: () -> Iterable[Tuple[Kind, List[str]]] """Yields variant and configuration files associated with it. This should be treated like items of a dictionary. """ # SMELL: Move the conditions out of this function # environment variables have the lowest priority config_file = os.environ.get('PIP_CONFIG_FILE', None) if config_file is not None: yield kinds.ENV, [config_file] else: yield kinds.ENV, [] config_files = get_configuration_files() # at the base we have any global configuration yield kinds.GLOBAL, config_files[kinds.GLOBAL] # per-user configuration next should_load_user_config = not self.isolated and not ( config_file and os.path.exists(config_file) ) if should_load_user_config: # The legacy config file is overridden by the new config file yield kinds.USER, config_files[kinds.USER] # finally virtualenv configuration first trumping others yield kinds.SITE, config_files[kinds.SITE]
[ "def", "iter_config_files", "(", "self", ")", ":", "# type: () -> Iterable[Tuple[Kind, List[str]]]", "# SMELL: Move the conditions out of this function", "# environment variables have the lowest priority", "config_file", "=", "os", ".", "environ", ".", "get", "(", "'PIP_CONFIG_FILE'", ",", "None", ")", "if", "config_file", "is", "not", "None", ":", "yield", "kinds", ".", "ENV", ",", "[", "config_file", "]", "else", ":", "yield", "kinds", ".", "ENV", ",", "[", "]", "config_files", "=", "get_configuration_files", "(", ")", "# at the base we have any global configuration", "yield", "kinds", ".", "GLOBAL", ",", "config_files", "[", "kinds", ".", "GLOBAL", "]", "# per-user configuration next", "should_load_user_config", "=", "not", "self", ".", "isolated", "and", "not", "(", "config_file", "and", "os", ".", "path", ".", "exists", "(", "config_file", ")", ")", "if", "should_load_user_config", ":", "# The legacy config file is overridden by the new config file", "yield", "kinds", ".", "USER", ",", "config_files", "[", "kinds", ".", "USER", "]", "# finally virtualenv configuration first trumping others", "yield", "kinds", ".", "SITE", ",", "config_files", "[", "kinds", ".", "SITE", "]" ]
[ 343, 4 ]
[ 372, 50 ]
python
en
['en', 'en', 'en']
True
Configuration.get_values_in_config
(self, variant)
Get values present in a config file
Get values present in a config file
def get_values_in_config(self, variant): # type: (Kind) -> Dict[str, Any] """Get values present in a config file""" return self._config[variant]
[ "def", "get_values_in_config", "(", "self", ",", "variant", ")", ":", "# type: (Kind) -> Dict[str, Any]", "return", "self", ".", "_config", "[", "variant", "]" ]
[ 374, 4 ]
[ 377, 36 ]
python
en
['en', 'en', 'en']
True
parse_args_to_fbcode_builder_opts
(add_args_fn, top_level_opts, opts, help)
Provides some standard arguments: --debug, --option, --shell-quoted-option Then, calls `add_args_fn(parser)` to add application-specific arguments. `opts` are first used as defaults for the various command-line arguments. Then, the parsed arguments are mapped back into `opts`, which then become the values for `FBCodeBuilder.option()`, to be used both by the builder and by `get_steps_fn()`. `help` is printed in response to the `--help` argument.
def parse_args_to_fbcode_builder_opts(add_args_fn, top_level_opts, opts, help): ''' Provides some standard arguments: --debug, --option, --shell-quoted-option Then, calls `add_args_fn(parser)` to add application-specific arguments. `opts` are first used as defaults for the various command-line arguments. Then, the parsed arguments are mapped back into `opts`, which then become the values for `FBCodeBuilder.option()`, to be used both by the builder and by `get_steps_fn()`. `help` is printed in response to the `--help` argument. ''' top_level_opts = set(top_level_opts) parser = argparse.ArgumentParser( description=help, formatter_class=argparse.RawDescriptionHelpFormatter ) add_args_fn(parser) parser.add_argument( '--option', nargs=2, metavar=('KEY', 'VALUE'), action='append', default=[ (k, v) for k, v in opts.items() if k not in top_level_opts and not isinstance(v, ShellQuoted) ], help='Set project-specific options. These are assumed to be raw ' 'strings, to be shell-escaped as needed. Default: %(default)s.', ) parser.add_argument( '--shell-quoted-option', nargs=2, metavar=('KEY', 'VALUE'), action='append', default=[ (k, raw_shell(v)) for k, v in opts.items() if k not in top_level_opts and isinstance(v, ShellQuoted) ], help='Set project-specific options. These are assumed to be shell-' 'quoted, and may be used in commands as-is. Default: %(default)s.', ) parser.add_argument('--debug', action='store_true', help='Log more') args = parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format='%(levelname)s: %(message)s' ) # Map command-line args back into opts. logging.debug('opts before command-line arguments: {0}'.format(opts)) new_opts = {} for key in top_level_opts: val = getattr(args, key) # Allow clients to unset a default by passing a value of None in opts if val is not None: new_opts[key] = val for key, val in args.option: new_opts[key] = val for key, val in args.shell_quoted_option: new_opts[key] = ShellQuoted(val) logging.debug('opts after command-line arguments: {0}'.format(new_opts)) return new_opts
[ "def", "parse_args_to_fbcode_builder_opts", "(", "add_args_fn", ",", "top_level_opts", ",", "opts", ",", "help", ")", ":", "top_level_opts", "=", "set", "(", "top_level_opts", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "help", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ")", "add_args_fn", "(", "parser", ")", "parser", ".", "add_argument", "(", "'--option'", ",", "nargs", "=", "2", ",", "metavar", "=", "(", "'KEY'", ",", "'VALUE'", ")", ",", "action", "=", "'append'", ",", "default", "=", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "opts", ".", "items", "(", ")", "if", "k", "not", "in", "top_level_opts", "and", "not", "isinstance", "(", "v", ",", "ShellQuoted", ")", "]", ",", "help", "=", "'Set project-specific options. These are assumed to be raw '", "'strings, to be shell-escaped as needed. Default: %(default)s.'", ",", ")", "parser", ".", "add_argument", "(", "'--shell-quoted-option'", ",", "nargs", "=", "2", ",", "metavar", "=", "(", "'KEY'", ",", "'VALUE'", ")", ",", "action", "=", "'append'", ",", "default", "=", "[", "(", "k", ",", "raw_shell", "(", "v", ")", ")", "for", "k", ",", "v", "in", "opts", ".", "items", "(", ")", "if", "k", "not", "in", "top_level_opts", "and", "isinstance", "(", "v", ",", "ShellQuoted", ")", "]", ",", "help", "=", "'Set project-specific options. These are assumed to be shell-'", "'quoted, and may be used in commands as-is. Default: %(default)s.'", ",", ")", "parser", ".", "add_argument", "(", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Log more'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", "if", "args", ".", "debug", "else", "logging", ".", "INFO", ",", "format", "=", "'%(levelname)s: %(message)s'", ")", "# Map command-line args back into opts.", "logging", ".", "debug", "(", "'opts before command-line arguments: {0}'", ".", "format", "(", "opts", ")", ")", "new_opts", "=", "{", "}", "for", "key", "in", "top_level_opts", ":", "val", "=", "getattr", "(", "args", ",", "key", ")", "# Allow clients to unset a default by passing a value of None in opts", "if", "val", "is", "not", "None", ":", "new_opts", "[", "key", "]", "=", "val", "for", "key", ",", "val", "in", "args", ".", "option", ":", "new_opts", "[", "key", "]", "=", "val", "for", "key", ",", "val", "in", "args", ".", "shell_quoted_option", ":", "new_opts", "[", "key", "]", "=", "ShellQuoted", "(", "val", ")", "logging", ".", "debug", "(", "'opts after command-line arguments: {0}'", ".", "format", "(", "new_opts", ")", ")", "return", "new_opts" ]
[ 13, 0 ]
[ 81, 19 ]
python
en
['en', 'error', 'th']
False
mark_safe
(s)
Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate. If used on a method as a decorator, mark the returned data as safe. Can be called multiple times on a single string.
Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate.
def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate. If used on a method as a decorator, mark the returned data as safe. Can be called multiple times on a single string. """ if hasattr(s, '__html__'): return s if callable(s): return _safety_decorator(mark_safe, s) return SafeString(s)
[ "def", "mark_safe", "(", "s", ")", ":", "if", "hasattr", "(", "s", ",", "'__html__'", ")", ":", "return", "s", "if", "callable", "(", "s", ")", ":", "return", "_safety_decorator", "(", "mark_safe", ",", "s", ")", "return", "SafeString", "(", "s", ")" ]
[ 49, 0 ]
[ 62, 24 ]
python
en
['en', 'error', 'th']
False
SafeData.__html__
(self)
Return the html representation of a string for interoperability. This allows other template engines to understand Django's SafeData.
Return the html representation of a string for interoperability.
def __html__(self): """ Return the html representation of a string for interoperability. This allows other template engines to understand Django's SafeData. """ return self
[ "def", "__html__", "(", "self", ")", ":", "return", "self" ]
[ 11, 4 ]
[ 17, 19 ]
python
en
['en', 'error', 'th']
False
SafeString.__add__
(self, rhs)
Concatenating a safe string with another safe bytestring or safe string is safe. Otherwise, the result is no longer safe.
Concatenating a safe string with another safe bytestring or safe string is safe. Otherwise, the result is no longer safe.
def __add__(self, rhs): """ Concatenating a safe string with another safe bytestring or safe string is safe. Otherwise, the result is no longer safe. """ t = super().__add__(rhs) if isinstance(rhs, SafeData): return SafeString(t) return t
[ "def", "__add__", "(", "self", ",", "rhs", ")", ":", "t", "=", "super", "(", ")", ".", "__add__", "(", "rhs", ")", "if", "isinstance", "(", "rhs", ",", "SafeData", ")", ":", "return", "SafeString", "(", "t", ")", "return", "t" ]
[ 25, 4 ]
[ 33, 16 ]
python
en
['en', 'error', 'th']
False
ChangeList.get_filters_params
(self, params=None)
Return all params except IGNORED_PARAMS.
Return all params except IGNORED_PARAMS.
def get_filters_params(self, params=None): """ Return all params except IGNORED_PARAMS. """ params = params or self.params lookup_params = params.copy() # a dictionary of the query string # Remove all the parameters that are globally and systematically # ignored. for ignored in IGNORED_PARAMS: if ignored in lookup_params: del lookup_params[ignored] return lookup_params
[ "def", "get_filters_params", "(", "self", ",", "params", "=", "None", ")", ":", "params", "=", "params", "or", "self", ".", "params", "lookup_params", "=", "params", ".", "copy", "(", ")", "# a dictionary of the query string", "# Remove all the parameters that are globally and systematically", "# ignored.", "for", "ignored", "in", "IGNORED_PARAMS", ":", "if", "ignored", "in", "lookup_params", ":", "del", "lookup_params", "[", "ignored", "]", "return", "lookup_params" ]
[ 109, 4 ]
[ 120, 28 ]
python
en
['en', 'error', 'th']
False
ChangeList.get_ordering_field
(self, field_name)
Return the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Return None if no proper model field name can be matched.
Return the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Return None if no proper model field name can be matched.
def get_ordering_field(self, field_name): """ Return the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Return None if no proper model field name can be matched. """ try: field = self.lookup_opts.get_field(field_name) return field.name except FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self.model_admin, field_name): attr = getattr(self.model_admin, field_name) else: attr = getattr(self.model, field_name) if isinstance(attr, property) and hasattr(attr, 'fget'): attr = attr.fget return getattr(attr, 'admin_order_field', None)
[ "def", "get_ordering_field", "(", "self", ",", "field_name", ")", ":", "try", ":", "field", "=", "self", ".", "lookup_opts", ".", "get_field", "(", "field_name", ")", "return", "field", ".", "name", "except", "FieldDoesNotExist", ":", "# See whether field_name is a name of a non-field", "# that allows sorting.", "if", "callable", "(", "field_name", ")", ":", "attr", "=", "field_name", "elif", "hasattr", "(", "self", ".", "model_admin", ",", "field_name", ")", ":", "attr", "=", "getattr", "(", "self", ".", "model_admin", ",", "field_name", ")", "else", ":", "attr", "=", "getattr", "(", "self", ".", "model", ",", "field_name", ")", "if", "isinstance", "(", "attr", ",", "property", ")", "and", "hasattr", "(", "attr", ",", "'fget'", ")", ":", "attr", "=", "attr", ".", "fget", "return", "getattr", "(", "attr", ",", "'admin_order_field'", ",", "None", ")" ]
[ 272, 4 ]
[ 294, 59 ]
python
en
['en', 'error', 'th']
False
ChangeList.get_ordering
(self, request, queryset)
Return the list of ordering fields for the change list. First check the get_ordering() method in model admin, then check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by calling _get_deterministic_ordering() with the constructed ordering.
Return the list of ordering fields for the change list. First check the get_ordering() method in model admin, then check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by calling _get_deterministic_ordering() with the constructed ordering.
def get_ordering(self, request, queryset): """ Return the list of ordering fields for the change list. First check the get_ordering() method in model admin, then check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by calling _get_deterministic_ordering() with the constructed ordering. """ params = self.params ordering = list(self.model_admin.get_ordering(request) or self._get_default_ordering()) if ORDER_VAR in params: # Clear ordering and used params ordering = [] order_params = params[ORDER_VAR].split('.') for p in order_params: try: none, pfx, idx = p.rpartition('-') field_name = self.list_display[int(idx)] order_field = self.get_ordering_field(field_name) if not order_field: continue # No 'admin_order_field', skip it if isinstance(order_field, OrderBy): if pfx == '-': order_field = order_field.copy() order_field.reverse_ordering() ordering.append(order_field) elif hasattr(order_field, 'resolve_expression'): # order_field is an expression. ordering.append(order_field.desc() if pfx == '-' else order_field.asc()) # reverse order if order_field has already "-" as prefix elif order_field.startswith('-') and pfx == '-': ordering.append(order_field[1:]) else: ordering.append(pfx + order_field) except (IndexError, ValueError): continue # Invalid ordering specified, skip it. # Add the given query's ordering fields, if any. ordering.extend(queryset.query.order_by) return self._get_deterministic_ordering(ordering)
[ "def", "get_ordering", "(", "self", ",", "request", ",", "queryset", ")", ":", "params", "=", "self", ".", "params", "ordering", "=", "list", "(", "self", ".", "model_admin", ".", "get_ordering", "(", "request", ")", "or", "self", ".", "_get_default_ordering", "(", ")", ")", "if", "ORDER_VAR", "in", "params", ":", "# Clear ordering and used params", "ordering", "=", "[", "]", "order_params", "=", "params", "[", "ORDER_VAR", "]", ".", "split", "(", "'.'", ")", "for", "p", "in", "order_params", ":", "try", ":", "none", ",", "pfx", ",", "idx", "=", "p", ".", "rpartition", "(", "'-'", ")", "field_name", "=", "self", ".", "list_display", "[", "int", "(", "idx", ")", "]", "order_field", "=", "self", ".", "get_ordering_field", "(", "field_name", ")", "if", "not", "order_field", ":", "continue", "# No 'admin_order_field', skip it", "if", "isinstance", "(", "order_field", ",", "OrderBy", ")", ":", "if", "pfx", "==", "'-'", ":", "order_field", "=", "order_field", ".", "copy", "(", ")", "order_field", ".", "reverse_ordering", "(", ")", "ordering", ".", "append", "(", "order_field", ")", "elif", "hasattr", "(", "order_field", ",", "'resolve_expression'", ")", ":", "# order_field is an expression.", "ordering", ".", "append", "(", "order_field", ".", "desc", "(", ")", "if", "pfx", "==", "'-'", "else", "order_field", ".", "asc", "(", ")", ")", "# reverse order if order_field has already \"-\" as prefix", "elif", "order_field", ".", "startswith", "(", "'-'", ")", "and", "pfx", "==", "'-'", ":", "ordering", ".", "append", "(", "order_field", "[", "1", ":", "]", ")", "else", ":", "ordering", ".", "append", "(", "pfx", "+", "order_field", ")", "except", "(", "IndexError", ",", "ValueError", ")", ":", "continue", "# Invalid ordering specified, skip it.", "# Add the given query's ordering fields, if any.", "ordering", ".", "extend", "(", "queryset", ".", "query", ".", "order_by", ")", "return", "self", ".", "_get_deterministic_ordering", "(", "ordering", ")" ]
[ 296, 4 ]
[ 337, 57 ]
python
en
['en', 'error', 'th']
False
ChangeList._get_deterministic_ordering
(self, ordering)
Ensure a deterministic order across all database backends. Search for a single field or unique together set of fields providing a total ordering. If these are missing, augment the ordering with a descendant primary key.
Ensure a deterministic order across all database backends. Search for a single field or unique together set of fields providing a total ordering. If these are missing, augment the ordering with a descendant primary key.
def _get_deterministic_ordering(self, ordering): """ Ensure a deterministic order across all database backends. Search for a single field or unique together set of fields providing a total ordering. If these are missing, augment the ordering with a descendant primary key. """ ordering = list(ordering) ordering_fields = set() total_ordering_fields = {'pk'} | { field.attname for field in self.lookup_opts.fields if field.unique and not field.null } for part in ordering: # Search for single field providing a total ordering. field_name = None if isinstance(part, str): field_name = part.lstrip('-') elif isinstance(part, F): field_name = part.name elif isinstance(part, OrderBy) and isinstance(part.expression, F): field_name = part.expression.name if field_name: # Normalize attname references by using get_field(). try: field = self.lookup_opts.get_field(field_name) except FieldDoesNotExist: # Could be "?" for random ordering or a related field # lookup. Skip this part of introspection for now. continue # Ordering by a related field name orders by the referenced # model's ordering. Skip this part of introspection for now. if field.remote_field and field_name == field.name: continue if field.attname in total_ordering_fields: break ordering_fields.add(field.attname) else: # No single total ordering field, try unique_together and total # unique constraints. constraint_field_names = ( *self.lookup_opts.unique_together, *( constraint.fields for constraint in self.lookup_opts.total_unique_constraints ), ) for field_names in constraint_field_names: # Normalize attname references by using get_field(). fields = [self.lookup_opts.get_field(field_name) for field_name in field_names] # Composite unique constraints containing a nullable column # cannot ensure total ordering. if any(field.null for field in fields): continue if ordering_fields.issuperset(field.attname for field in fields): break else: # If no set of unique fields is present in the ordering, rely # on the primary key to provide total ordering. ordering.append('-pk') return ordering
[ "def", "_get_deterministic_ordering", "(", "self", ",", "ordering", ")", ":", "ordering", "=", "list", "(", "ordering", ")", "ordering_fields", "=", "set", "(", ")", "total_ordering_fields", "=", "{", "'pk'", "}", "|", "{", "field", ".", "attname", "for", "field", "in", "self", ".", "lookup_opts", ".", "fields", "if", "field", ".", "unique", "and", "not", "field", ".", "null", "}", "for", "part", "in", "ordering", ":", "# Search for single field providing a total ordering.", "field_name", "=", "None", "if", "isinstance", "(", "part", ",", "str", ")", ":", "field_name", "=", "part", ".", "lstrip", "(", "'-'", ")", "elif", "isinstance", "(", "part", ",", "F", ")", ":", "field_name", "=", "part", ".", "name", "elif", "isinstance", "(", "part", ",", "OrderBy", ")", "and", "isinstance", "(", "part", ".", "expression", ",", "F", ")", ":", "field_name", "=", "part", ".", "expression", ".", "name", "if", "field_name", ":", "# Normalize attname references by using get_field().", "try", ":", "field", "=", "self", ".", "lookup_opts", ".", "get_field", "(", "field_name", ")", "except", "FieldDoesNotExist", ":", "# Could be \"?\" for random ordering or a related field", "# lookup. Skip this part of introspection for now.", "continue", "# Ordering by a related field name orders by the referenced", "# model's ordering. Skip this part of introspection for now.", "if", "field", ".", "remote_field", "and", "field_name", "==", "field", ".", "name", ":", "continue", "if", "field", ".", "attname", "in", "total_ordering_fields", ":", "break", "ordering_fields", ".", "add", "(", "field", ".", "attname", ")", "else", ":", "# No single total ordering field, try unique_together and total", "# unique constraints.", "constraint_field_names", "=", "(", "*", "self", ".", "lookup_opts", ".", "unique_together", ",", "*", "(", "constraint", ".", "fields", "for", "constraint", "in", "self", ".", "lookup_opts", ".", "total_unique_constraints", ")", ",", ")", "for", "field_names", "in", "constraint_field_names", ":", "# Normalize attname references by using get_field().", "fields", "=", "[", "self", ".", "lookup_opts", ".", "get_field", "(", "field_name", ")", "for", "field_name", "in", "field_names", "]", "# Composite unique constraints containing a nullable column", "# cannot ensure total ordering.", "if", "any", "(", "field", ".", "null", "for", "field", "in", "fields", ")", ":", "continue", "if", "ordering_fields", ".", "issuperset", "(", "field", ".", "attname", "for", "field", "in", "fields", ")", ":", "break", "else", ":", "# If no set of unique fields is present in the ordering, rely", "# on the primary key to provide total ordering.", "ordering", ".", "append", "(", "'-pk'", ")", "return", "ordering" ]
[ 339, 4 ]
[ 399, 23 ]
python
en
['en', 'error', 'th']
False
ChangeList.get_ordering_field_columns
(self)
Return a dictionary of ordering field column numbers and asc/desc.
Return a dictionary of ordering field column numbers and asc/desc.
def get_ordering_field_columns(self): """ Return a dictionary of ordering field column numbers and asc/desc. """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = {} if ORDER_VAR not in self.params: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if isinstance(field, (Combinable, OrderBy)): if not isinstance(field, OrderBy): field = field.asc() if isinstance(field.expression, F): order_type = 'desc' if field.descending else 'asc' field = field.expression.name else: continue elif field.startswith('-'): field = field[1:] order_type = 'desc' else: order_type = 'asc' for index, attr in enumerate(self.list_display): if self.get_ordering_field(attr) == field: ordering_fields[index] = order_type break else: for p in self.params[ORDER_VAR].split('.'): none, pfx, idx = p.rpartition('-') try: idx = int(idx) except ValueError: continue # skip it ordering_fields[idx] = 'desc' if pfx == '-' else 'asc' return ordering_fields
[ "def", "get_ordering_field_columns", "(", "self", ")", ":", "# We must cope with more than one column having the same underlying sort", "# field, so we base things on column numbers.", "ordering", "=", "self", ".", "_get_default_ordering", "(", ")", "ordering_fields", "=", "{", "}", "if", "ORDER_VAR", "not", "in", "self", ".", "params", ":", "# for ordering specified on ModelAdmin or model Meta, we don't know", "# the right column numbers absolutely, because there might be more", "# than one column associated with that ordering, so we guess.", "for", "field", "in", "ordering", ":", "if", "isinstance", "(", "field", ",", "(", "Combinable", ",", "OrderBy", ")", ")", ":", "if", "not", "isinstance", "(", "field", ",", "OrderBy", ")", ":", "field", "=", "field", ".", "asc", "(", ")", "if", "isinstance", "(", "field", ".", "expression", ",", "F", ")", ":", "order_type", "=", "'desc'", "if", "field", ".", "descending", "else", "'asc'", "field", "=", "field", ".", "expression", ".", "name", "else", ":", "continue", "elif", "field", ".", "startswith", "(", "'-'", ")", ":", "field", "=", "field", "[", "1", ":", "]", "order_type", "=", "'desc'", "else", ":", "order_type", "=", "'asc'", "for", "index", ",", "attr", "in", "enumerate", "(", "self", ".", "list_display", ")", ":", "if", "self", ".", "get_ordering_field", "(", "attr", ")", "==", "field", ":", "ordering_fields", "[", "index", "]", "=", "order_type", "break", "else", ":", "for", "p", "in", "self", ".", "params", "[", "ORDER_VAR", "]", ".", "split", "(", "'.'", ")", ":", "none", ",", "pfx", ",", "idx", "=", "p", ".", "rpartition", "(", "'-'", ")", "try", ":", "idx", "=", "int", "(", "idx", ")", "except", "ValueError", ":", "continue", "# skip it", "ordering_fields", "[", "idx", "]", "=", "'desc'", "if", "pfx", "==", "'-'", "else", "'asc'", "return", "ordering_fields" ]
[ 401, 4 ]
[ 439, 30 ]
python
en
['en', 'error', 'th']
False
CPointerBase.__del__
(self)
Free the memory used by the C++ object.
Free the memory used by the C++ object.
def __del__(self): """ Free the memory used by the C++ object. """ if self.destructor and self._ptr: try: self.destructor(self.ptr) except (AttributeError, ImportError, TypeError): pass
[ "def", "__del__", "(", "self", ")", ":", "if", "self", ".", "destructor", "and", "self", ".", "_ptr", ":", "try", ":", "self", ".", "destructor", "(", "self", ".", "ptr", ")", "except", "(", "AttributeError", ",", "ImportError", ",", "TypeError", ")", ":", "pass" ]
[ 29, 4 ]
[ 37, 20 ]
python
en
['en', 'error', 'th']
False
dumps
(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)
Return URL-safe, hmac signed base64 compressed JSON string. If key is None, use settings.SECRET_KEY instead. The hmac algorithm is the default Signer algorithm. If compress is True (not the default), check if compressing using zlib can save some space. Prepend a '.' to signify compression. This is included in the signature, to protect against zip bombs. Salt can be used to namespace the hash, so that a signed string is only valid for a given namespace. Leaving this at the default value or re-using a salt value across different parts of your application without good cause is a security risk. The serializer is expected to return a bytestring.
Return URL-safe, hmac signed base64 compressed JSON string. If key is None, use settings.SECRET_KEY instead. The hmac algorithm is the default Signer algorithm.
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False): """ Return URL-safe, hmac signed base64 compressed JSON string. If key is None, use settings.SECRET_KEY instead. The hmac algorithm is the default Signer algorithm. If compress is True (not the default), check if compressing using zlib can save some space. Prepend a '.' to signify compression. This is included in the signature, to protect against zip bombs. Salt can be used to namespace the hash, so that a signed string is only valid for a given namespace. Leaving this at the default value or re-using a salt value across different parts of your application without good cause is a security risk. The serializer is expected to return a bytestring. """ return TimestampSigner(key, salt=salt).sign_object(obj, serializer=serializer, compress=compress)
[ "def", "dumps", "(", "obj", ",", "key", "=", "None", ",", "salt", "=", "'django.core.signing'", ",", "serializer", "=", "JSONSerializer", ",", "compress", "=", "False", ")", ":", "return", "TimestampSigner", "(", "key", ",", "salt", "=", "salt", ")", ".", "sign_object", "(", "obj", ",", "serializer", "=", "serializer", ",", "compress", "=", "compress", ")" ]
[ 92, 0 ]
[ 109, 101 ]
python
en
['en', 'error', 'th']
False
loads
(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None)
Reverse of dumps(), raise BadSignature if signature fails. The serializer is expected to accept a bytestring.
Reverse of dumps(), raise BadSignature if signature fails.
def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None): """ Reverse of dumps(), raise BadSignature if signature fails. The serializer is expected to accept a bytestring. """ return TimestampSigner(key, salt=salt).unsign_object(s, serializer=serializer, max_age=max_age)
[ "def", "loads", "(", "s", ",", "key", "=", "None", ",", "salt", "=", "'django.core.signing'", ",", "serializer", "=", "JSONSerializer", ",", "max_age", "=", "None", ")", ":", "return", "TimestampSigner", "(", "key", ",", "salt", "=", "salt", ")", ".", "unsign_object", "(", "s", ",", "serializer", "=", "serializer", ",", "max_age", "=", "max_age", ")" ]
[ 112, 0 ]
[ 118, 99 ]
python
en
['en', 'error', 'th']
False
Signer.sign_object
(self, obj, serializer=JSONSerializer, compress=False)
Return URL-safe, hmac signed base64 compressed JSON string. If compress is True (not the default), check if compressing using zlib can save some space. Prepend a '.' to signify compression. This is included in the signature, to protect against zip bombs. The serializer is expected to return a bytestring.
Return URL-safe, hmac signed base64 compressed JSON string.
def sign_object(self, obj, serializer=JSONSerializer, compress=False): """ Return URL-safe, hmac signed base64 compressed JSON string. If compress is True (not the default), check if compressing using zlib can save some space. Prepend a '.' to signify compression. This is included in the signature, to protect against zip bombs. The serializer is expected to return a bytestring. """ data = serializer().dumps(obj) # Flag for if it's been compressed or not. is_compressed = False if compress: # Avoid zlib dependency unless compress is being used. compressed = zlib.compress(data) if len(compressed) < (len(data) - 1): data = compressed is_compressed = True base64d = b64_encode(data).decode() if is_compressed: base64d = '.' + base64d return self.sign(base64d)
[ "def", "sign_object", "(", "self", ",", "obj", ",", "serializer", "=", "JSONSerializer", ",", "compress", "=", "False", ")", ":", "data", "=", "serializer", "(", ")", ".", "dumps", "(", "obj", ")", "# Flag for if it's been compressed or not.", "is_compressed", "=", "False", "if", "compress", ":", "# Avoid zlib dependency unless compress is being used.", "compressed", "=", "zlib", ".", "compress", "(", "data", ")", "if", "len", "(", "compressed", ")", "<", "(", "len", "(", "data", ")", "-", "1", ")", ":", "data", "=", "compressed", "is_compressed", "=", "True", "base64d", "=", "b64_encode", "(", "data", ")", ".", "decode", "(", ")", "if", "is_compressed", ":", "base64d", "=", "'.'", "+", "base64d", "return", "self", ".", "sign", "(", "base64d", ")" ]
[ 161, 4 ]
[ 184, 33 ]
python
en
['en', 'error', 'th']
False
TimestampSigner.unsign
(self, value, max_age=None)
Retrieve original value and check it wasn't signed more than max_age seconds ago.
Retrieve original value and check it wasn't signed more than max_age seconds ago.
def unsign(self, value, max_age=None): """ Retrieve original value and check it wasn't signed more than max_age seconds ago. """ result = super().unsign(value) value, timestamp = result.rsplit(self.sep, 1) timestamp = baseconv.base62.decode(timestamp) if max_age is not None: if isinstance(max_age, datetime.timedelta): max_age = max_age.total_seconds() # Check timestamp is not older than max_age age = time.time() - timestamp if age > max_age: raise SignatureExpired( 'Signature age %s > %s seconds' % (age, max_age)) return value
[ "def", "unsign", "(", "self", ",", "value", ",", "max_age", "=", "None", ")", ":", "result", "=", "super", "(", ")", ".", "unsign", "(", "value", ")", "value", ",", "timestamp", "=", "result", ".", "rsplit", "(", "self", ".", "sep", ",", "1", ")", "timestamp", "=", "baseconv", ".", "base62", ".", "decode", "(", "timestamp", ")", "if", "max_age", "is", "not", "None", ":", "if", "isinstance", "(", "max_age", ",", "datetime", ".", "timedelta", ")", ":", "max_age", "=", "max_age", ".", "total_seconds", "(", ")", "# Check timestamp is not older than max_age", "age", "=", "time", ".", "time", "(", ")", "-", "timestamp", "if", "age", ">", "max_age", ":", "raise", "SignatureExpired", "(", "'Signature age %s > %s seconds'", "%", "(", "age", ",", "max_age", ")", ")", "return", "value" ]
[ 209, 4 ]
[ 225, 20 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_table_list
(self, cursor)
Return a list of table and view names in the current database.
Return a list of table and view names in the current database.
def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" cursor.execute(""" SELECT table_name, 't' FROM user_tables WHERE NOT EXISTS ( SELECT 1 FROM user_mviews WHERE user_mviews.mview_name = user_tables.table_name ) UNION ALL SELECT view_name, 'v' FROM user_views UNION ALL SELECT mview_name, 'v' FROM user_mviews """) return [TableInfo(self.identifier_converter(row[0]), row[1]) for row in cursor.fetchall()]
[ "def", "get_table_list", "(", "self", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "\"\"\"\n SELECT table_name, 't'\n FROM user_tables\n WHERE\n NOT EXISTS (\n SELECT 1\n FROM user_mviews\n WHERE user_mviews.mview_name = user_tables.table_name\n )\n UNION ALL\n SELECT view_name, 'v' FROM user_views\n UNION ALL\n SELECT mview_name, 'v' FROM user_mviews\n \"\"\"", ")", "return", "[", "TableInfo", "(", "self", ".", "identifier_converter", "(", "row", "[", "0", "]", ")", ",", "row", "[", "1", "]", ")", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", "]" ]
[ 71, 4 ]
[ 87, 98 ]
python
en
['en', 'en', 'en']
True
DatabaseIntrospection.get_table_description
(self, cursor, table_name)
Return a description of the table with the DB-API cursor.description interface.
Return a description of the table with the DB-API cursor.description interface.
def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ # user_tab_columns gives data default for columns cursor.execute(""" SELECT user_tab_cols.column_name, user_tab_cols.data_default, CASE WHEN user_tab_cols.collation = user_tables.default_collation THEN NULL ELSE user_tab_cols.collation END collation, CASE WHEN user_tab_cols.char_used IS NULL THEN user_tab_cols.data_length ELSE user_tab_cols.char_length END as internal_size, CASE WHEN user_tab_cols.identity_column = 'YES' THEN 1 ELSE 0 END as is_autofield, CASE WHEN EXISTS ( SELECT 1 FROM user_json_columns WHERE user_json_columns.table_name = user_tab_cols.table_name AND user_json_columns.column_name = user_tab_cols.column_name ) THEN 1 ELSE 0 END as is_json FROM user_tab_cols LEFT OUTER JOIN user_tables ON user_tables.table_name = user_tab_cols.table_name WHERE user_tab_cols.table_name = UPPER(%s) """, [table_name]) field_map = { column: (internal_size, default if default != 'NULL' else None, collation, is_autofield, is_json) for column, default, collation, internal_size, is_autofield, is_json in cursor.fetchall() } self.cache_bust_counter += 1 cursor.execute("SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0".format( self.connection.ops.quote_name(table_name), self.cache_bust_counter)) description = [] for desc in cursor.description: name = desc[0] internal_size, default, collation, is_autofield, is_json = field_map[name] name = name % {} # cx_Oracle, for some reason, doubles percent signs. description.append(FieldInfo( self.identifier_converter(name), *desc[1:3], internal_size, desc[4] or 0, desc[5] or 0, *desc[6:], default, collation, is_autofield, is_json, )) return description
[ "def", "get_table_description", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "# user_tab_columns gives data default for columns", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n user_tab_cols.column_name,\n user_tab_cols.data_default,\n CASE\n WHEN user_tab_cols.collation = user_tables.default_collation\n THEN NULL\n ELSE user_tab_cols.collation\n END collation,\n CASE\n WHEN user_tab_cols.char_used IS NULL\n THEN user_tab_cols.data_length\n ELSE user_tab_cols.char_length\n END as internal_size,\n CASE\n WHEN user_tab_cols.identity_column = 'YES' THEN 1\n ELSE 0\n END as is_autofield,\n CASE\n WHEN EXISTS (\n SELECT 1\n FROM user_json_columns\n WHERE\n user_json_columns.table_name = user_tab_cols.table_name AND\n user_json_columns.column_name = user_tab_cols.column_name\n )\n THEN 1\n ELSE 0\n END as is_json\n FROM user_tab_cols\n LEFT OUTER JOIN\n user_tables ON user_tables.table_name = user_tab_cols.table_name\n WHERE user_tab_cols.table_name = UPPER(%s)\n \"\"\"", ",", "[", "table_name", "]", ")", "field_map", "=", "{", "column", ":", "(", "internal_size", ",", "default", "if", "default", "!=", "'NULL'", "else", "None", ",", "collation", ",", "is_autofield", ",", "is_json", ")", "for", "column", ",", "default", ",", "collation", ",", "internal_size", ",", "is_autofield", ",", "is_json", "in", "cursor", ".", "fetchall", "(", ")", "}", "self", ".", "cache_bust_counter", "+=", "1", "cursor", ".", "execute", "(", "\"SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0\"", ".", "format", "(", "self", ".", "connection", ".", "ops", ".", "quote_name", "(", "table_name", ")", ",", "self", ".", "cache_bust_counter", ")", ")", "description", "=", "[", "]", "for", "desc", "in", "cursor", ".", "description", ":", "name", "=", "desc", "[", "0", "]", "internal_size", ",", "default", ",", "collation", ",", "is_autofield", ",", "is_json", "=", "field_map", "[", "name", "]", "name", "=", "name", "%", "{", "}", "# cx_Oracle, for some reason, doubles percent signs.", "description", ".", "append", "(", "FieldInfo", "(", "self", ".", "identifier_converter", "(", "name", ")", ",", "*", "desc", "[", "1", ":", "3", "]", ",", "internal_size", ",", "desc", "[", "4", "]", "or", "0", ",", "desc", "[", "5", "]", "or", "0", ",", "*", "desc", "[", "6", ":", "]", ",", "default", ",", "collation", ",", "is_autofield", ",", "is_json", ",", ")", ")", "return", "description" ]
[ 89, 4 ]
[ 146, 26 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.identifier_converter
(self, name)
Identifier comparison is case insensitive under Oracle.
Identifier comparison is case insensitive under Oracle.
def identifier_converter(self, name): """Identifier comparison is case insensitive under Oracle.""" return name.lower()
[ "def", "identifier_converter", "(", "self", ",", "name", ")", ":", "return", "name", ".", "lower", "(", ")" ]
[ 148, 4 ]
[ 150, 27 ]
python
en
['en', 'fr', 'en']
True
DatabaseIntrospection.get_relations
(self, cursor, table_name)
Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table. """ table_name = table_name.upper() cursor.execute(""" SELECT ca.column_name, cb.table_name, cb.column_name FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb WHERE user_constraints.table_name = %s AND user_constraints.constraint_name = ca.constraint_name AND user_constraints.r_constraint_name = cb.constraint_name AND ca.position = cb.position""", [table_name]) return { self.identifier_converter(field_name): ( self.identifier_converter(rel_field_name), self.identifier_converter(rel_table_name), ) for field_name, rel_table_name, rel_field_name in cursor.fetchall() }
[ "def", "get_relations", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "table_name", "=", "table_name", ".", "upper", "(", ")", "cursor", ".", "execute", "(", "\"\"\"\n SELECT ca.column_name, cb.table_name, cb.column_name\n FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb\n WHERE user_constraints.table_name = %s AND\n user_constraints.constraint_name = ca.constraint_name AND\n user_constraints.r_constraint_name = cb.constraint_name AND\n ca.position = cb.position\"\"\"", ",", "[", "table_name", "]", ")", "return", "{", "self", ".", "identifier_converter", "(", "field_name", ")", ":", "(", "self", ".", "identifier_converter", "(", "rel_field_name", ")", ",", "self", ".", "identifier_converter", "(", "rel_table_name", ")", ",", ")", "for", "field_name", ",", "rel_table_name", ",", "rel_field_name", "in", "cursor", ".", "fetchall", "(", ")", "}" ]
[ 183, 4 ]
[ 202, 9 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_constraints
(self, cursor, table_name)
Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns.
Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns.
def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Loop over the constraints, getting PKs, uniques, and checks cursor.execute(""" SELECT user_constraints.constraint_name, LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), CASE user_constraints.constraint_type WHEN 'P' THEN 1 ELSE 0 END AS is_primary_key, CASE WHEN user_constraints.constraint_type IN ('P', 'U') THEN 1 ELSE 0 END AS is_unique, CASE user_constraints.constraint_type WHEN 'C' THEN 1 ELSE 0 END AS is_check_constraint FROM user_constraints LEFT OUTER JOIN user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name WHERE user_constraints.constraint_type = ANY('P', 'U', 'C') AND user_constraints.table_name = UPPER(%s) GROUP BY user_constraints.constraint_name, user_constraints.constraint_type """, [table_name]) for constraint, columns, pk, unique, check in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { 'columns': columns.split(','), 'primary_key': pk, 'unique': unique, 'foreign_key': None, 'check': check, 'index': unique, # All uniques come with an index } # Foreign key constraints cursor.execute(""" SELECT cons.constraint_name, LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), LOWER(rcols.table_name), LOWER(rcols.column_name) FROM user_constraints cons INNER JOIN user_cons_columns rcols ON rcols.constraint_name = cons.r_constraint_name AND rcols.position = 1 LEFT OUTER JOIN user_cons_columns cols ON cons.constraint_name = cols.constraint_name WHERE cons.constraint_type = 'R' AND cons.table_name = UPPER(%s) GROUP BY cons.constraint_name, rcols.table_name, rcols.column_name """, [table_name]) for constraint, columns, other_table, other_column in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { 'primary_key': False, 'unique': False, 'foreign_key': (other_table, other_column), 'check': False, 'index': False, 'columns': columns.split(','), } # Now get indexes cursor.execute(""" SELECT ind.index_name, LOWER(ind.index_type), LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.column_position), LISTAGG(cols.descend, ',') WITHIN GROUP (ORDER BY cols.column_position) FROM user_ind_columns cols, user_indexes ind WHERE cols.table_name = UPPER(%s) AND NOT EXISTS ( SELECT 1 FROM user_constraints cons WHERE ind.index_name = cons.index_name ) AND cols.index_name = ind.index_name GROUP BY ind.index_name, ind.index_type """, [table_name]) for constraint, type_, columns, orders in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { 'primary_key': False, 'unique': False, 'foreign_key': None, 'check': False, 'index': True, 'type': 'idx' if type_ == 'normal' else type_, 'columns': columns.split(','), 'orders': orders.split(','), } return constraints
[ "def", "get_constraints", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "constraints", "=", "{", "}", "# Loop over the constraints, getting PKs, uniques, and checks", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n user_constraints.constraint_name,\n LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position),\n CASE user_constraints.constraint_type\n WHEN 'P' THEN 1\n ELSE 0\n END AS is_primary_key,\n CASE\n WHEN user_constraints.constraint_type IN ('P', 'U') THEN 1\n ELSE 0\n END AS is_unique,\n CASE user_constraints.constraint_type\n WHEN 'C' THEN 1\n ELSE 0\n END AS is_check_constraint\n FROM\n user_constraints\n LEFT OUTER JOIN\n user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name\n WHERE\n user_constraints.constraint_type = ANY('P', 'U', 'C')\n AND user_constraints.table_name = UPPER(%s)\n GROUP BY user_constraints.constraint_name, user_constraints.constraint_type\n \"\"\"", ",", "[", "table_name", "]", ")", "for", "constraint", ",", "columns", ",", "pk", ",", "unique", ",", "check", "in", "cursor", ".", "fetchall", "(", ")", ":", "constraint", "=", "self", ".", "identifier_converter", "(", "constraint", ")", "constraints", "[", "constraint", "]", "=", "{", "'columns'", ":", "columns", ".", "split", "(", "','", ")", ",", "'primary_key'", ":", "pk", ",", "'unique'", ":", "unique", ",", "'foreign_key'", ":", "None", ",", "'check'", ":", "check", ",", "'index'", ":", "unique", ",", "# All uniques come with an index", "}", "# Foreign key constraints", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n cons.constraint_name,\n LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position),\n LOWER(rcols.table_name),\n LOWER(rcols.column_name)\n FROM\n user_constraints cons\n INNER JOIN\n user_cons_columns rcols ON rcols.constraint_name = cons.r_constraint_name AND rcols.position = 1\n LEFT OUTER JOIN\n user_cons_columns cols ON cons.constraint_name = cols.constraint_name\n WHERE\n cons.constraint_type = 'R' AND\n cons.table_name = UPPER(%s)\n GROUP BY cons.constraint_name, rcols.table_name, rcols.column_name\n \"\"\"", ",", "[", "table_name", "]", ")", "for", "constraint", ",", "columns", ",", "other_table", ",", "other_column", "in", "cursor", ".", "fetchall", "(", ")", ":", "constraint", "=", "self", ".", "identifier_converter", "(", "constraint", ")", "constraints", "[", "constraint", "]", "=", "{", "'primary_key'", ":", "False", ",", "'unique'", ":", "False", ",", "'foreign_key'", ":", "(", "other_table", ",", "other_column", ")", ",", "'check'", ":", "False", ",", "'index'", ":", "False", ",", "'columns'", ":", "columns", ".", "split", "(", "','", ")", ",", "}", "# Now get indexes", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n ind.index_name,\n LOWER(ind.index_type),\n LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.column_position),\n LISTAGG(cols.descend, ',') WITHIN GROUP (ORDER BY cols.column_position)\n FROM\n user_ind_columns cols, user_indexes ind\n WHERE\n cols.table_name = UPPER(%s) AND\n NOT EXISTS (\n SELECT 1\n FROM user_constraints cons\n WHERE ind.index_name = cons.index_name\n ) AND cols.index_name = ind.index_name\n GROUP BY ind.index_name, ind.index_type\n \"\"\"", ",", "[", "table_name", "]", ")", "for", "constraint", ",", "type_", ",", "columns", ",", "orders", "in", "cursor", ".", "fetchall", "(", ")", ":", "constraint", "=", "self", ".", "identifier_converter", "(", "constraint", ")", "constraints", "[", "constraint", "]", "=", "{", "'primary_key'", ":", "False", ",", "'unique'", ":", "False", ",", "'foreign_key'", ":", "None", ",", "'check'", ":", "False", ",", "'index'", ":", "True", ",", "'type'", ":", "'idx'", "if", "type_", "==", "'normal'", "else", "type_", ",", "'columns'", ":", "columns", ".", "split", "(", "','", ")", ",", "'orders'", ":", "orders", ".", "split", "(", "','", ")", ",", "}", "return", "constraints" ]
[ 234, 4 ]
[ 334, 26 ]
python
en
['en', 'error', 'th']
False
resolve_ctx
(cli, prog_name, args)
Parse into a hierarchy of contexts. Contexts are connected through the parent variable. :param cli: command definition :param prog_name: the program that is running :param args: full list of args :return: the final context/command parsed
Parse into a hierarchy of contexts. Contexts are connected through the parent variable. :param cli: command definition :param prog_name: the program that is running :param args: full list of args :return: the final context/command parsed
def resolve_ctx(cli, prog_name, args): """ Parse into a hierarchy of contexts. Contexts are connected through the parent variable. :param cli: command definition :param prog_name: the program that is running :param args: full list of args :return: the final context/command parsed """ ctx = cli.make_context(prog_name, args, resilient_parsing=True) args = ctx.protected_args + ctx.args while args: if isinstance(ctx.command, MultiCommand): if not ctx.command.chain: cmd_name, cmd, args = ctx.command.resolve_command(ctx, args) if cmd is None: return ctx ctx = cmd.make_context(cmd_name, args, parent=ctx, resilient_parsing=True) args = ctx.protected_args + ctx.args else: # Walk chained subcommand contexts saving the last one. while args: cmd_name, cmd, args = ctx.command.resolve_command(ctx, args) if cmd is None: return ctx sub_ctx = cmd.make_context(cmd_name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False, resilient_parsing=True) args = sub_ctx.args ctx = sub_ctx args = sub_ctx.protected_args + sub_ctx.args else: break return ctx
[ "def", "resolve_ctx", "(", "cli", ",", "prog_name", ",", "args", ")", ":", "ctx", "=", "cli", ".", "make_context", "(", "prog_name", ",", "args", ",", "resilient_parsing", "=", "True", ")", "args", "=", "ctx", ".", "protected_args", "+", "ctx", ".", "args", "while", "args", ":", "if", "isinstance", "(", "ctx", ".", "command", ",", "MultiCommand", ")", ":", "if", "not", "ctx", ".", "command", ".", "chain", ":", "cmd_name", ",", "cmd", ",", "args", "=", "ctx", ".", "command", ".", "resolve_command", "(", "ctx", ",", "args", ")", "if", "cmd", "is", "None", ":", "return", "ctx", "ctx", "=", "cmd", ".", "make_context", "(", "cmd_name", ",", "args", ",", "parent", "=", "ctx", ",", "resilient_parsing", "=", "True", ")", "args", "=", "ctx", ".", "protected_args", "+", "ctx", ".", "args", "else", ":", "# Walk chained subcommand contexts saving the last one.", "while", "args", ":", "cmd_name", ",", "cmd", ",", "args", "=", "ctx", ".", "command", ".", "resolve_command", "(", "ctx", ",", "args", ")", "if", "cmd", "is", "None", ":", "return", "ctx", "sub_ctx", "=", "cmd", ".", "make_context", "(", "cmd_name", ",", "args", ",", "parent", "=", "ctx", ",", "allow_extra_args", "=", "True", ",", "allow_interspersed_args", "=", "False", ",", "resilient_parsing", "=", "True", ")", "args", "=", "sub_ctx", ".", "args", "ctx", "=", "sub_ctx", "args", "=", "sub_ctx", ".", "protected_args", "+", "sub_ctx", ".", "args", "else", ":", "break", "return", "ctx" ]
[ 84, 0 ]
[ 118, 14 ]
python
en
['en', 'error', 'th']
False
start_of_option
(param_str)
:param param_str: param_str to check :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")
:param param_str: param_str to check :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")
def start_of_option(param_str): """ :param param_str: param_str to check :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--") """ return param_str and param_str[:1] == '-'
[ "def", "start_of_option", "(", "param_str", ")", ":", "return", "param_str", "and", "param_str", "[", ":", "1", "]", "==", "'-'" ]
[ 121, 0 ]
[ 126, 45 ]
python
en
['en', 'error', 'th']
False
is_incomplete_option
(all_args, cmd_param)
:param all_args: the full original list of args supplied :param cmd_param: the current command paramter :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and corresponds to this cmd_param. In other words whether this cmd_param option can still accept values
:param all_args: the full original list of args supplied :param cmd_param: the current command paramter :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and corresponds to this cmd_param. In other words whether this cmd_param option can still accept values
def is_incomplete_option(all_args, cmd_param): """ :param all_args: the full original list of args supplied :param cmd_param: the current command paramter :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and corresponds to this cmd_param. In other words whether this cmd_param option can still accept values """ if not isinstance(cmd_param, Option): return False if cmd_param.is_flag: return False last_option = None for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])): if index + 1 > cmd_param.nargs: break if start_of_option(arg_str): last_option = arg_str return True if last_option and last_option in cmd_param.opts else False
[ "def", "is_incomplete_option", "(", "all_args", ",", "cmd_param", ")", ":", "if", "not", "isinstance", "(", "cmd_param", ",", "Option", ")", ":", "return", "False", "if", "cmd_param", ".", "is_flag", ":", "return", "False", "last_option", "=", "None", "for", "index", ",", "arg_str", "in", "enumerate", "(", "reversed", "(", "[", "arg", "for", "arg", "in", "all_args", "if", "arg", "!=", "WORDBREAK", "]", ")", ")", ":", "if", "index", "+", "1", ">", "cmd_param", ".", "nargs", ":", "break", "if", "start_of_option", "(", "arg_str", ")", ":", "last_option", "=", "arg_str", "return", "True", "if", "last_option", "and", "last_option", "in", "cmd_param", ".", "opts", "else", "False" ]
[ 129, 0 ]
[ 148, 75 ]
python
en
['en', 'error', 'th']
False
is_incomplete_argument
(current_params, cmd_param)
:param current_params: the current params and values for this argument as already entered :param cmd_param: the current command parameter :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In other words whether or not the this cmd_param argument can still accept values
:param current_params: the current params and values for this argument as already entered :param cmd_param: the current command parameter :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In other words whether or not the this cmd_param argument can still accept values
def is_incomplete_argument(current_params, cmd_param): """ :param current_params: the current params and values for this argument as already entered :param cmd_param: the current command parameter :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In other words whether or not the this cmd_param argument can still accept values """ if not isinstance(cmd_param, Argument): return False current_param_values = current_params[cmd_param.name] if current_param_values is None: return True if cmd_param.nargs == -1: return True if isinstance(current_param_values, abc.Iterable) \ and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs: return True return False
[ "def", "is_incomplete_argument", "(", "current_params", ",", "cmd_param", ")", ":", "if", "not", "isinstance", "(", "cmd_param", ",", "Argument", ")", ":", "return", "False", "current_param_values", "=", "current_params", "[", "cmd_param", ".", "name", "]", "if", "current_param_values", "is", "None", ":", "return", "True", "if", "cmd_param", ".", "nargs", "==", "-", "1", ":", "return", "True", "if", "isinstance", "(", "current_param_values", ",", "abc", ".", "Iterable", ")", "and", "cmd_param", ".", "nargs", ">", "1", "and", "len", "(", "current_param_values", ")", "<", "cmd_param", ".", "nargs", ":", "return", "True", "return", "False" ]
[ 151, 0 ]
[ 168, 16 ]
python
en
['en', 'error', 'th']
False
get_user_autocompletions
(ctx, args, incomplete, cmd_param)
:param ctx: context associated with the parsed command :param args: full list of args :param incomplete: the incomplete text to autocomplete :param cmd_param: command definition :return: all the possible user-specified completions for the param
:param ctx: context associated with the parsed command :param args: full list of args :param incomplete: the incomplete text to autocomplete :param cmd_param: command definition :return: all the possible user-specified completions for the param
def get_user_autocompletions(ctx, args, incomplete, cmd_param): """ :param ctx: context associated with the parsed command :param args: full list of args :param incomplete: the incomplete text to autocomplete :param cmd_param: command definition :return: all the possible user-specified completions for the param """ results = [] if isinstance(cmd_param.type, Choice): # Choices don't support descriptions. results = [(c, None) for c in cmd_param.type.choices if str(c).startswith(incomplete)] elif cmd_param.autocompletion is not None: dynamic_completions = cmd_param.autocompletion(ctx=ctx, args=args, incomplete=incomplete) results = [c if isinstance(c, tuple) else (c, None) for c in dynamic_completions] return results
[ "def", "get_user_autocompletions", "(", "ctx", ",", "args", ",", "incomplete", ",", "cmd_param", ")", ":", "results", "=", "[", "]", "if", "isinstance", "(", "cmd_param", ".", "type", ",", "Choice", ")", ":", "# Choices don't support descriptions.", "results", "=", "[", "(", "c", ",", "None", ")", "for", "c", "in", "cmd_param", ".", "type", ".", "choices", "if", "str", "(", "c", ")", ".", "startswith", "(", "incomplete", ")", "]", "elif", "cmd_param", ".", "autocompletion", "is", "not", "None", ":", "dynamic_completions", "=", "cmd_param", ".", "autocompletion", "(", "ctx", "=", "ctx", ",", "args", "=", "args", ",", "incomplete", "=", "incomplete", ")", "results", "=", "[", "c", "if", "isinstance", "(", "c", ",", "tuple", ")", "else", "(", "c", ",", "None", ")", "for", "c", "in", "dynamic_completions", "]", "return", "results" ]
[ 171, 0 ]
[ 190, 18 ]
python
en
['en', 'error', 'th']
False
get_visible_commands_starting_with
(ctx, starts_with)
:param ctx: context associated with the parsed command :starts_with: string that visible commands must start with. :return: all visible (not hidden) commands that start with starts_with.
:param ctx: context associated with the parsed command :starts_with: string that visible commands must start with. :return: all visible (not hidden) commands that start with starts_with.
def get_visible_commands_starting_with(ctx, starts_with): """ :param ctx: context associated with the parsed command :starts_with: string that visible commands must start with. :return: all visible (not hidden) commands that start with starts_with. """ for c in ctx.command.list_commands(ctx): if c.startswith(starts_with): command = ctx.command.get_command(ctx, c) if not command.hidden: yield command
[ "def", "get_visible_commands_starting_with", "(", "ctx", ",", "starts_with", ")", ":", "for", "c", "in", "ctx", ".", "command", ".", "list_commands", "(", "ctx", ")", ":", "if", "c", ".", "startswith", "(", "starts_with", ")", ":", "command", "=", "ctx", ".", "command", ".", "get_command", "(", "ctx", ",", "c", ")", "if", "not", "command", ".", "hidden", ":", "yield", "command" ]
[ 193, 0 ]
[ 203, 29 ]
python
en
['en', 'error', 'th']
False
get_choices
(cli, prog_name, args, incomplete)
:param cli: command definition :param prog_name: the program that is running :param args: full list of args :param incomplete: the incomplete text to autocomplete :return: all the possible completions for the incomplete
:param cli: command definition :param prog_name: the program that is running :param args: full list of args :param incomplete: the incomplete text to autocomplete :return: all the possible completions for the incomplete
def get_choices(cli, prog_name, args, incomplete): """ :param cli: command definition :param prog_name: the program that is running :param args: full list of args :param incomplete: the incomplete text to autocomplete :return: all the possible completions for the incomplete """ all_args = copy.deepcopy(args) ctx = resolve_ctx(cli, prog_name, args) if ctx is None: return [] # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse # without the '=' if start_of_option(incomplete) and WORDBREAK in incomplete: partition_incomplete = incomplete.partition(WORDBREAK) all_args.append(partition_incomplete[0]) incomplete = partition_incomplete[2] elif incomplete == WORDBREAK: incomplete = '' completions = [] if start_of_option(incomplete): # completions for partial options for param in ctx.command.params: if isinstance(param, Option) and not param.hidden: param_opts = [param_opt for param_opt in param.opts + param.secondary_opts if param_opt not in all_args or param.multiple] completions.extend([(o, param.help) for o in param_opts if o.startswith(incomplete)]) return completions # completion for option values from user supplied values for param in ctx.command.params: if is_incomplete_option(all_args, param): return get_user_autocompletions(ctx, all_args, incomplete, param) # completion for argument values from user supplied values for param in ctx.command.params: if is_incomplete_argument(ctx.params, param): return get_user_autocompletions(ctx, all_args, incomplete, param) add_subcommand_completions(ctx, incomplete, completions) # Sort before returning so that proper ordering can be enforced in custom types. return sorted(completions)
[ "def", "get_choices", "(", "cli", ",", "prog_name", ",", "args", ",", "incomplete", ")", ":", "all_args", "=", "copy", ".", "deepcopy", "(", "args", ")", "ctx", "=", "resolve_ctx", "(", "cli", ",", "prog_name", ",", "args", ")", "if", "ctx", "is", "None", ":", "return", "[", "]", "# In newer versions of bash long opts with '='s are partitioned, but it's easier to parse", "# without the '='", "if", "start_of_option", "(", "incomplete", ")", "and", "WORDBREAK", "in", "incomplete", ":", "partition_incomplete", "=", "incomplete", ".", "partition", "(", "WORDBREAK", ")", "all_args", ".", "append", "(", "partition_incomplete", "[", "0", "]", ")", "incomplete", "=", "partition_incomplete", "[", "2", "]", "elif", "incomplete", "==", "WORDBREAK", ":", "incomplete", "=", "''", "completions", "=", "[", "]", "if", "start_of_option", "(", "incomplete", ")", ":", "# completions for partial options", "for", "param", "in", "ctx", ".", "command", ".", "params", ":", "if", "isinstance", "(", "param", ",", "Option", ")", "and", "not", "param", ".", "hidden", ":", "param_opts", "=", "[", "param_opt", "for", "param_opt", "in", "param", ".", "opts", "+", "param", ".", "secondary_opts", "if", "param_opt", "not", "in", "all_args", "or", "param", ".", "multiple", "]", "completions", ".", "extend", "(", "[", "(", "o", ",", "param", ".", "help", ")", "for", "o", "in", "param_opts", "if", "o", ".", "startswith", "(", "incomplete", ")", "]", ")", "return", "completions", "# completion for option values from user supplied values", "for", "param", "in", "ctx", ".", "command", ".", "params", ":", "if", "is_incomplete_option", "(", "all_args", ",", "param", ")", ":", "return", "get_user_autocompletions", "(", "ctx", ",", "all_args", ",", "incomplete", ",", "param", ")", "# completion for argument values from user supplied values", "for", "param", "in", "ctx", ".", "command", ".", "params", ":", "if", "is_incomplete_argument", "(", "ctx", ".", "params", ",", "param", ")", ":", "return", "get_user_autocompletions", "(", "ctx", ",", "all_args", ",", "incomplete", ",", "param", ")", "add_subcommand_completions", "(", "ctx", ",", "incomplete", ",", "completions", ")", "# Sort before returning so that proper ordering can be enforced in custom types.", "return", "sorted", "(", "completions", ")" ]
[ 221, 0 ]
[ 264, 30 ]
python
en
['en', 'error', 'th']
False
voice
()
Respond to incoming calls with a simple text message.
Respond to incoming calls with a simple text message.
def voice(): """Respond to incoming calls with a simple text message.""" resp = VoiceResponse() resp.say("Hello. It's me.") resp.play("http://howtodocs.s3.amazonaws.com/ahoyhoy.mp3") return str(resp)
[ "def", "voice", "(", ")", ":", "resp", "=", "VoiceResponse", "(", ")", "resp", ".", "say", "(", "\"Hello. It's me.\"", ")", "resp", ".", "play", "(", "\"http://howtodocs.s3.amazonaws.com/ahoyhoy.mp3\"", ")", "return", "str", "(", "resp", ")" ]
[ 7, 0 ]
[ 13, 20 ]
python
en
['en', 'en', 'en']
True
default_test_processes
()
Default number of test processes when using the --parallel option.
Default number of test processes when using the --parallel option.
def default_test_processes(): """Default number of test processes when using the --parallel option.""" # The current implementation of the parallel test runner requires # multiprocessing to start subprocesses with fork(). if multiprocessing.get_start_method() != 'fork': return 1 try: return int(os.environ['DJANGO_TEST_PROCESSES']) except KeyError: return multiprocessing.cpu_count()
[ "def", "default_test_processes", "(", ")", ":", "# The current implementation of the parallel test runner requires", "# multiprocessing to start subprocesses with fork().", "if", "multiprocessing", ".", "get_start_method", "(", ")", "!=", "'fork'", ":", "return", "1", "try", ":", "return", "int", "(", "os", ".", "environ", "[", "'DJANGO_TEST_PROCESSES'", "]", ")", "except", "KeyError", ":", "return", "multiprocessing", ".", "cpu_count", "(", ")" ]
[ 297, 0 ]
[ 306, 42 ]
python
en
['en', 'en', 'en']
True