_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q237600
copy_modules
train
def copy_modules(filespath=None, modules_path=None, verbose=None): ''' Copy over the tree module files into your path ''' # find or define a modules path if not modules_path: modulepath = os.getenv("MODULEPATH") if not modulepath: modules_path = input('Enter the root path for yo...
python
{ "resource": "" }
q237601
_indent
train
def _indent(text, level=1): ''' Does a proper indenting for Sphinx rst ''' prefix = ' ' * (4 * level) def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return ''.join(prefixed_lines())
python
{ "resource": "" }
q237602
get_requirements
train
def get_requirements(opts): ''' Get the proper requirements file based on the optional argument ''' if opts.dev: name = 'requirements_dev.txt' elif opts.doc: name = 'requirements_doc.txt' else: name = 'requirements.txt' requirements_file = os.path.join(os.path.dirname(__fil...
python
{ "resource": "" }
q237603
remove_args
train
def remove_args(parser): ''' Remove custom arguments from the parser ''' arguments = [] for action in list(parser._get_optional_actions()): if '--help' not in action.option_strings: arguments += action.option_strings for arg in arguments: if arg in sys.argv: sys...
python
{ "resource": "" }
q237604
_render_log
train
def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, ...
python
{ "resource": "" }
q237605
adjust_name_for_printing
train
def adjust_name_for_printing(name): """ Make sure a name can be printed, alongside used as a variable name. """ if name is not None: name2 = name name = name.replace(" ", "_").replace(".", "_").replace("-", "_m_") name = name.replace("+", "_p_").replace("!", "_I_") name =...
python
{ "resource": "" }
q237606
Nameable.name
train
def name(self, name): """ Set the name of this object. Tell the parent if the name has changed. """ from_name = self.name assert isinstance(name, str) self._name = name if self.has_parent(): self._parent_._name_changed(self, from_name)
python
{ "resource": "" }
q237607
Nameable.hierarchy_name
train
def hierarchy_name(self, adjust_for_printing=True): """ return the name for this object with the parents names attached by dots. :param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()` on the names, recursively ...
python
{ "resource": "" }
q237608
Parameterized.grep_param_names
train
def grep_param_names(self, regexp): """ create a list of parameters, matching regular expression regexp """ if not isinstance(regexp, _pattern_type): regexp = compile(regexp) found_params = [] def visit(innerself, regexp): if (innerself is not self) and regexp...
python
{ "resource": "" }
q237609
Param._setup_observers
train
def _setup_observers(self): """ Setup the default observers 1: pass through to parent, if present """ if self.has_parent(): self.add_observer(self._parent_, self._parent_._pass_through_notify_observers, -np.inf)
python
{ "resource": "" }
q237610
Param._repr_html_
train
def _repr_html_(self, indices=None, iops=None, lx=None, li=None, lls=None): """Representation of the parameter in html for notebook display.""" filter_ = self._current_slice_ vals = self.flat if indices is None: indices = self._indices(filter_) if iops is None: ravi =...
python
{ "resource": "" }
q237611
Observable.add_observer
train
def add_observer(self, observer, callble, priority=0): """ Add an observer `observer` with the callback `callble` and priority `priority` to this observers list. """ self.observers.add(priority, observer, callble)
python
{ "resource": "" }
q237612
Observable.notify_observers
train
def notify_observers(self, which=None, min_priority=None): """ Notifies all observers. Which is the element, which kicked off this notification loop. The first argument will be self, the second `which`. .. note:: notifies only observers with priority p > min_prior...
python
{ "resource": "" }
q237613
Constrainable.constrain_fixed
train
def constrain_fixed(self, value=None, warning=True, trigger_parent=True): """ Constrain this parameter to be fixed to the current value it carries. This does not override the previous constraints, so unfixing will restore the constraint set before fixing. :param warning: print ...
python
{ "resource": "" }
q237614
Constrainable.unconstrain_fixed
train
def unconstrain_fixed(self): """ This parameter will no longer be fixed. If there was a constraint on this parameter when fixing it, it will be constraint with that previous constraint. """ unconstrained = self.unconstrain(__fixed__) self._highest_parent_._set_un...
python
{ "resource": "" }
q237615
Gradcheckable.checkgrad
train
def checkgrad(self, verbose=0, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of this parameter with respect to the highest parent's objective function. This is a three point estimate of the gradient, wiggling at the parameters with a stepsize step. ...
python
{ "resource": "" }
q237616
opt_tnc.opt
train
def opt(self, x_init, f_fp=None, f=None, fp=None): """ Run the TNC optimizer """ tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached', 'Line search failed', 'Function is constant'] assert f_fp != None, "TNC requires...
python
{ "resource": "" }
q237617
opt_simplex.opt
train
def opt(self, x_init, f_fp=None, f=None, fp=None): """ The simplex optimizer does not require gradients. """ statuses = ['Converged', 'Maximum number of function evaluations made', 'Maximum number of iterations reached'] opt_dict = {} if self.xtol is not None: ...
python
{ "resource": "" }
q237618
Cacher.combine_inputs
train
def combine_inputs(self, args, kw, ignore_args): "Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute" inputs= args + tuple(c[1] for c in sorted(kw.items(), key=lambda x: x[0])) # REMOVE the ignored arguments from input and PREVENT it from being chec...
python
{ "resource": "" }
q237619
Cacher.ensure_cache_length
train
def ensure_cache_length(self): "Ensures the cache is within its limits and has one place free" if len(self.order) == self.limit: # we have reached the limit, so lets release one element cache_id = self.order.popleft() combined_args_kw = self.cached_inputs[cache_id] ...
python
{ "resource": "" }
q237620
Cacher.add_to_cache
train
def add_to_cache(self, cache_id, inputs, output): """This adds cache_id to the cache, with inputs and output""" self.inputs_changed[cache_id] = False self.cached_outputs[cache_id] = output self.order.append(cache_id) self.cached_inputs[cache_id] = inputs for a in inputs: ...
python
{ "resource": "" }
q237621
Cacher.on_cache_changed
train
def on_cache_changed(self, direct, which=None): """ A callback funtion, which sets local flags when the elements of some cached inputs change this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here. """ for what in [d...
python
{ "resource": "" }
q237622
Cacher.reset
train
def reset(self): """ Totally reset the cache """ [a().remove_observer(self, self.on_cache_changed) if (a() is not None) else None for [a, _] in self.cached_input_ids.values()] self.order = collections.deque() self.cached_inputs = {} # point from cache_ids to a list of [...
python
{ "resource": "" }
q237623
FunctionCache.disable_caching
train
def disable_caching(self): "Disable the cache of this object. This also removes previously cached results" self.caching_enabled = False for c in self.values(): c.disable_cacher()
python
{ "resource": "" }
q237624
FunctionCache.enable_caching
train
def enable_caching(self): "Enable the cache of this object." self.caching_enabled = True for c in self.values(): c.enable_cacher()
python
{ "resource": "" }
q237625
ObserverList.remove
train
def remove(self, priority, observer, callble): """ Remove one observer, which had priority and callble. """ self.flush() for i in range(len(self) - 1, -1, -1): p,o,c = self[i] if priority==p and observer==o and callble==c: del self._poc[i]
python
{ "resource": "" }
q237626
ObserverList.add
train
def add(self, priority, observer, callble): """ Add an observer with priority and callble """ #if observer is not None: ins = 0 for pr, _, _ in self: if priority > pr: break ins += 1 self._poc.insert(ins, (priority, weakref....
python
{ "resource": "" }
q237627
ParameterIndexOperations.properties_for
train
def properties_for(self, index): """ Returns a list of properties, such that each entry in the list corresponds to the element of the index given. Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_for([2,3,5]) [['one'], ['one', 'two'], ['two...
python
{ "resource": "" }
q237628
ParameterIndexOperations.properties_dict_for
train
def properties_dict_for(self, index): """ Return a dictionary, containing properties as keys and indices as index Thus, the indices for each constraint, which is contained will be collected as one dictionary Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] ...
python
{ "resource": "" }
q237629
Model.optimize
train
def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs): """ Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors. kwargs are passed to the optimizer. They can be: ...
python
{ "resource": "" }
q237630
Model.optimize_restarts
train
def optimize_restarts(self, num_restarts=10, robust=False, verbose=True, parallel=False, num_processes=None, **kwargs): """ Perform random restarts of the model, and set the model to the best seen solution. If the robust flag is set, exceptions raised during optimizations will b...
python
{ "resource": "" }
q237631
Model._grads
train
def _grads(self, x): """ Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the paramete...
python
{ "resource": "" }
q237632
Model._objective
train
def _objective(self, x): """ The objective function passed to the optimizer. It combines the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the objective, and will raise the original exception if the objective can...
python
{ "resource": "" }
q237633
Model._repr_html_
train
def _repr_html_(self): """Representation of the model in html for notebook display.""" model_details = [['<b>Model</b>', self.name + '<br>'], ['<b>Objective</b>', '{}<br>'.format(float(self.objective_function()))], ["<b>Number of Parameters</b>", '{}<br>...
python
{ "resource": "" }
q237634
Indexable.add_index_operation
train
def add_index_operation(self, name, operations): """ Add index operation with name to the operations given. raises: attribute error if operations exist. """ if name not in self._index_operations: self._add_io(name, operations) else: raise Attribut...
python
{ "resource": "" }
q237635
Indexable._offset_for
train
def _offset_for(self, param): """ Return the offset of the param inside this parameterized object. This does not need to account for shaped parameters, as it basically just sums up the parameter sizes which come before param. """ if param.has_parent(): p = par...
python
{ "resource": "" }
q237636
Indexable._raveled_index_for
train
def _raveled_index_for(self, param): """ get the raveled index for a param that is an int array, containing the indexes for the flattened param inside this parameterized logic. !Warning! be sure to call this method on the highest parent of a hierarchy, as it uses the fix...
python
{ "resource": "" }
q237637
ObsAr.copy
train
def copy(self): """ Make a copy. This means, we delete all observers and return a copy of this array. It will still be an ObsAr! """ from .lists_and_dicts import ObserverList memo = {} memo[id(self)] = self memo[id(self.observers)] = ObserverList() ...
python
{ "resource": "" }
q237638
Updateable.update_model
train
def update_model(self, updates=None): """ Get or set, whether automatic updates are performed. When updates are off, the model might be in a non-working state. To make the model work turn updates on again. :param bool|None updates: bool: whether to do updates ...
python
{ "resource": "" }
q237639
Updateable.trigger_update
train
def trigger_update(self, trigger_parent=True): """ Update the model from the current state. Make sure that updates are on, otherwise this method will do nothing :param bool trigger_parent: Whether to trigger the parent, after self has updated """ if not self.upda...
python
{ "resource": "" }
q237640
OptimizationHandlable.optimizer_array
train
def optimizer_array(self): """ Array for the optimizer to work on. This array always lives in the space for the optimizer. Thus, it is untransformed, going from Transformations. Setting this array, will make sure the transformed parameters for this model will be set acco...
python
{ "resource": "" }
q237641
OptimizationHandlable._trigger_params_changed
train
def _trigger_params_changed(self, trigger_parent=True): """ First tell all children to update, then update yourself. If trigger_parent is True, we will tell the parent, otherwise not. """ [p._trigger_params_changed(trigger_parent=False) for p in self.parameters if not p....
python
{ "resource": "" }
q237642
OptimizationHandlable._transform_gradients
train
def _transform_gradients(self, g): """ Transform the gradients by multiplying the gradient factor for each constraint to it. """ #py3 fix #[np.put(g, i, c.gradfactor(self.param_array[i], g[i])) for c, i in self.constraints.iteritems() if c != __fixed__] [np.put(g,...
python
{ "resource": "" }
q237643
OptimizationHandlable.parameter_names
train
def parameter_names(self, add_self=False, adjust_for_printing=False, recursive=True, intermediate=False): """ Get the names of all parameters of this model or parameter. It starts from the parameterized object you are calling this method on. Note: This does not unravel multidimensional ...
python
{ "resource": "" }
q237644
OptimizationHandlable.parameter_names_flat
train
def parameter_names_flat(self, include_fixed=False): """ Return the flattened parameter names for all subsequent parameters of this parameter. We do not include the name for self here! If you want the names for fixed parameters as well in this list, set include_fixed to True. ...
python
{ "resource": "" }
q237645
OptimizationHandlable._propagate_param_grad
train
def _propagate_param_grad(self, parray, garray): """ For propagating the param_array and gradient_array. This ensures the in memory view of each subsequent array. 1.) connect param_array of children to self.param_array 2.) tell all children to propagate further """ ...
python
{ "resource": "" }
q237646
Parameterizable.initialize_parameter
train
def initialize_parameter(self): """ Call this function to initialize the model, if you built it without initialization. This HAS to be called manually before optmizing or it will be causing unexpected behaviour, if not errors! """ #logger.debug("connecting parameters") ...
python
{ "resource": "" }
q237647
Parameterizable.traverse_parents
train
def traverse_parents(self, visit, *args, **kwargs): """ Traverse the hierarchy upwards, visiting all parents and their children except self. See "visitor pattern" in literature. This is implemented in pre-order fashion. Example: parents = [] self.traverse_parents(parent...
python
{ "resource": "" }
q237648
RidgeRegression.phi
train
def phi(self, Xpred, degrees=None): """ Compute the design matrix for this model using the degrees given by the index array in degrees :param array-like Xpred: inputs to compute the design matrix for :param array-like degrees: array of degrees to use [default=range(self....
python
{ "resource": "" }
q237649
consolidate_dependencies
train
def consolidate_dependencies(needs_ipython, child_program, requirement_files, manual_dependencies): """Parse files, get deps and merge them. Deps read later overwrite those read earlier.""" # We get the logger here because it's not defined at module level logger = logging.getLog...
python
{ "resource": "" }
q237650
detect_inside_virtualenv
train
def detect_inside_virtualenv(prefix, real_prefix, base_prefix): """Tell if fades is running inside a virtualenv. The params 'real_prefix' and 'base_prefix' may be None. This is copied from pip code (slightly modified), see https://github.com/pypa/pip/blob/281eb61b09d87765d7c2b92f6982b3fe76ccb0af/...
python
{ "resource": "" }
q237651
_get_normalized_args
train
def _get_normalized_args(parser): """Return the parsed command line arguments. Support the case when executed from a shebang, where all the parameters come in sys.argv[1] in a single string separated by spaces (in this case, the third parameter is what is being executed) """ env = os.enviro...
python
{ "resource": "" }
q237652
parse_fade_requirement
train
def parse_fade_requirement(text): """Return a requirement and repo from the given text, already parsed and converted.""" text = text.strip() if "::" in text: repo_raw, requirement = text.split("::", 1) try: repo = {'pypi': REPO_PYPI, 'vcs': REPO_VCS}[repo_raw] except Key...
python
{ "resource": "" }
q237653
_parse_content
train
def _parse_content(fh): """Parse the content of a script to find marked dependencies.""" content = iter(fh) deps = {} for line in content: # quickly discard most of the lines if 'fades' not in line: continue # discard other string with 'fades' that isn't a comment ...
python
{ "resource": "" }
q237654
_parse_docstring
train
def _parse_docstring(fh): """Parse the docstrings of a script to find marked dependencies.""" find_fades = re.compile(r'\b(fades)\b:').search for line in fh: if line.startswith("'"): quote = "'" break if line.startswith('"'): quote = '"' break...
python
{ "resource": "" }
q237655
_parse_requirement
train
def _parse_requirement(iterable): """Actually parse the requirements, from file or manually specified.""" deps = {} for line in iterable: line = line.strip() if not line or line[0] == '#': continue parsed_req = parse_fade_requirement(line) if parsed_req is None: ...
python
{ "resource": "" }
q237656
_read_lines
train
def _read_lines(filepath): """Read a req file to a list to support nested requirement files.""" with open(filepath, 'rt', encoding='utf8') as fh: for line in fh: line = line.strip() if line.startswith("-r"): logger.debug("Reading deps from nested requirement file:...
python
{ "resource": "" }
q237657
create_venv
train
def create_venv(requested_deps, interpreter, is_current, options, pip_options): """Create a new virtualvenv with the requirements of this script.""" # create virtualenv env = _FadesEnvBuilder() env_path, env_bin_path, pip_installed = env.create_env(interpreter, is_current, options) venv_data = {} ...
python
{ "resource": "" }
q237658
destroy_venv
train
def destroy_venv(env_path, venvscache=None): """Destroy a venv.""" # remove the venv itself in disk logger.debug("Destroying virtualenv at: %s", env_path) shutil.rmtree(env_path, ignore_errors=True) # remove venv from cache if venvscache is not None: venvscache.remove(env_path)
python
{ "resource": "" }
q237659
_FadesEnvBuilder.create_with_virtualenv
train
def create_with_virtualenv(self, interpreter, virtualenv_options): """Create a virtualenv using the virtualenv lib.""" args = ['virtualenv', '--python', interpreter, self.env_path] args.extend(virtualenv_options) if not self.pip_installed: args.insert(3, '--no-pip') t...
python
{ "resource": "" }
q237660
_FadesEnvBuilder.create_env
train
def create_env(self, interpreter, is_current, options): """Create the virtualenv and return its info.""" if is_current: # apply pyvenv options pyvenv_options = options['pyvenv_options'] if "--system-site-packages" in pyvenv_options: self.system_site_pa...
python
{ "resource": "" }
q237661
UsageManager.store_usage_stat
train
def store_usage_stat(self, venv_data, cache): """Log an usage record for venv_data.""" with open(self.stat_file_path, 'at') as f: self._write_venv_usage(f, venv_data)
python
{ "resource": "" }
q237662
UsageManager.clean_unused_venvs
train
def clean_unused_venvs(self, max_days_to_keep): """Compact usage stats and remove venvs. This method loads the complete file usage in memory, for every venv compact all records in one (the lastest), updates this info for every env deleted and, finally, write the entire file to disk. ...
python
{ "resource": "" }
q237663
logged_exec
train
def logged_exec(cmd): """Execute a command, redirecting the output to the log.""" logger = logging.getLogger('fades.exec') logger.debug("Executing external command: %r", cmd) p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) stdout = [] ...
python
{ "resource": "" }
q237664
_get_specific_dir
train
def _get_specific_dir(dir_type): """Get a specific directory, using some XDG base, with sensible default.""" if SNAP_BASEDIR_NAME in os.environ: logger.debug("Getting base dir information from SNAP_BASEDIR_NAME env var.") direct = os.path.join(os.environ[SNAP_BASEDIR_NAME], dir_type) else: ...
python
{ "resource": "" }
q237665
_get_interpreter_info
train
def _get_interpreter_info(interpreter=None): """Return the interpreter's full path using pythonX.Y format.""" if interpreter is None: # If interpreter is None by default returns the current interpreter data. major, minor = sys.version_info[:2] executable = sys.executable else: ...
python
{ "resource": "" }
q237666
get_interpreter_version
train
def get_interpreter_version(requested_interpreter): """Return a 'sanitized' interpreter and indicates if it is the current one.""" logger.debug('Getting interpreter version for: %s', requested_interpreter) current_interpreter = _get_interpreter_info() logger.debug('Current interpreter is %s', current_in...
python
{ "resource": "" }
q237667
check_pypi_updates
train
def check_pypi_updates(dependencies): """Return a list of dependencies to upgrade.""" dependencies_up_to_date = [] for dependency in dependencies.get('pypi', []): # get latest version from PyPI api try: latest_version = get_latest_version_number(dependency.project_name) e...
python
{ "resource": "" }
q237668
_pypi_head_package
train
def _pypi_head_package(dependency): """Hit pypi with a http HEAD to check if pkg_name exists.""" if dependency.specs: _, version = dependency.specs[0] url = BASE_PYPI_URL_WITH_VERSION.format(name=dependency.project_name, version=version) else: url = BASE_PYPI_URL.format(name=dependen...
python
{ "resource": "" }
q237669
check_pypi_exists
train
def check_pypi_exists(dependencies): """Check if the indicated dependencies actually exists in pypi.""" for dependency in dependencies.get('pypi', []): logger.debug("Checking if %r exists in PyPI", dependency) try: exists = _pypi_head_package(dependency) except Exception as e...
python
{ "resource": "" }
q237670
download_remote_script
train
def download_remote_script(url): """Download the content of a remote script to a local temp file.""" temp_fh = tempfile.NamedTemporaryFile('wt', encoding='utf8', suffix=".py", delete=False) downloader = _ScriptDownloader(url) logger.info( "Downloading remote script from %r using (%r downloader) ...
python
{ "resource": "" }
q237671
ExecutionError.dump_to_log
train
def dump_to_log(self, logger): """Send the cmd info and collected stdout to logger.""" logger.error("Execution ended in %s for cmd %s", self._retcode, self._cmd) for line in self._collected_stdout: logger.error(STDOUT_LOG_PREFIX + line)
python
{ "resource": "" }
q237672
_ScriptDownloader._decide
train
def _decide(self): """Find out which method should be applied to download that URL.""" netloc = parse.urlparse(self.url).netloc name = self.NETLOCS.get(netloc, 'raw') return name
python
{ "resource": "" }
q237673
_ScriptDownloader.get
train
def get(self): """Get the script content from the URL using the decided downloader.""" method_name = "_download_" + self.name method = getattr(self, method_name) return method()
python
{ "resource": "" }
q237674
_ScriptDownloader._download_raw
train
def _download_raw(self, url=None): """Download content from URL directly.""" if url is None: url = self.url req = request.Request(url, headers=self.HEADERS_PLAIN) return request.urlopen(req).read().decode("utf8")
python
{ "resource": "" }
q237675
_ScriptDownloader._download_linkode
train
def _download_linkode(self): """Download content from Linkode pastebin.""" # build the API url linkode_id = self.url.split("/")[-1] if linkode_id.startswith("#"): linkode_id = linkode_id[1:] url = "https://linkode.org/api/1/linkodes/" + linkode_id req = reque...
python
{ "resource": "" }
q237676
_ScriptDownloader._download_pastebin
train
def _download_pastebin(self): """Download content from Pastebin itself.""" paste_id = self.url.split("/")[-1] url = "https://pastebin.com/raw/" + paste_id return self._download_raw(url)
python
{ "resource": "" }
q237677
_ScriptDownloader._download_gist
train
def _download_gist(self): """Download content from github's pastebin.""" parts = parse.urlparse(self.url) url = "https://gist.github.com" + parts.path + "/raw" return self._download_raw(url)
python
{ "resource": "" }
q237678
get_version
train
def get_version(): """Retrieves package version from the file.""" with open('fades/_version.py') as fh: m = re.search("\(([^']*)\)", fh.read()) if m is None: raise ValueError("Unrecognized version in 'fades/_version.py'") return m.groups()[0].replace(', ', '.')
python
{ "resource": "" }
q237679
CustomInstall.initialize_options
train
def initialize_options(self): """Run parent initialization and then fix the scripts var.""" install.initialize_options(self) # leave the proper script according to the platform script = SCRIPT_WIN if sys.platform == "win32" else SCRIPT_REST self.distribution.scripts = [script]
python
{ "resource": "" }
q237680
CustomInstall.run
train
def run(self): """Run parent install, and then save the man file.""" install.run(self) # man directory if self._custom_man_dir is not None: if not os.path.exists(self._custom_man_dir): os.makedirs(self._custom_man_dir) shutil.copy("man/fades.1", s...
python
{ "resource": "" }
q237681
CustomInstall.finalize_options
train
def finalize_options(self): """Alter the installation path.""" install.finalize_options(self) if self.prefix is None: # no place for man page (like in a 'snap') man_dir = None else: man_dir = os.path.join(self.prefix, "share", "man", "man1") ...
python
{ "resource": "" }
q237682
options_from_file
train
def options_from_file(args): """Get a argparse.Namespace and return it updated with options from config files. Config files will be parsed with priority equal to his order in CONFIG_FILES. """ logger.debug("updating options from config files") updated_from_file = [] for config_file in CONFIG_FI...
python
{ "resource": "" }
q237683
VEnvsCache._venv_match
train
def _venv_match(self, installed, requirements): """Return True if what is installed satisfies the requirements. This method has multiple exit-points, but only for False (because if *anything* is not satisified, the venv is no good). Only after all was checked, and it didn't exit, the ve...
python
{ "resource": "" }
q237684
VEnvsCache._match_by_uuid
train
def _match_by_uuid(self, current_venvs, uuid): """Select a venv matching exactly by uuid.""" for venv_str in current_venvs: venv = json.loads(venv_str) env_path = venv.get('metadata', {}).get('env_path') _, env_uuid = os.path.split(env_path) if env_uuid ==...
python
{ "resource": "" }
q237685
VEnvsCache._select_better_fit
train
def _select_better_fit(self, matching_venvs): """Receive a list of matching venvs, and decide which one is the best fit.""" # keep the venvs in a separate array, to pick up the winner, and the (sorted, to compare # each dependency with its equivalent) in other structure to later compare ...
python
{ "resource": "" }
q237686
VEnvsCache._match_by_requirements
train
def _match_by_requirements(self, current_venvs, requirements, interpreter, options): """Select a venv matching interpreter and options, complying with requirements. Several venvs can be found in this case, will return the better fit. """ matching_venvs = [] for venv_str in curre...
python
{ "resource": "" }
q237687
VEnvsCache._select
train
def _select(self, current_venvs, requirements=None, interpreter='', uuid='', options=None): """Select which venv satisfy the received requirements.""" if uuid: logger.debug("Searching a venv by uuid: %s", uuid) venv = self._match_by_uuid(current_venvs, uuid) else: ...
python
{ "resource": "" }
q237688
VEnvsCache.get_venv
train
def get_venv(self, requirements=None, interpreter='', uuid='', options=None): """Find a venv that serves these requirements, if any.""" lines = self._read_cache() return self._select(lines, requirements, interpreter, uuid=uuid, options=options)
python
{ "resource": "" }
q237689
VEnvsCache.store
train
def store(self, installed_stuff, metadata, interpreter, options): """Store the virtualenv metadata for the indicated installed_stuff.""" new_content = { 'timestamp': int(time.mktime(time.localtime())), 'installed': installed_stuff, 'metadata': metadata, 'i...
python
{ "resource": "" }
q237690
VEnvsCache.remove
train
def remove(self, env_path): """Remove metadata for a given virtualenv from cache.""" with filelock(self.lockpath): cache = self._read_cache() logger.debug("Removing virtualenv from cache: %s" % env_path) lines = [ line for line in cache ...
python
{ "resource": "" }
q237691
VEnvsCache._read_cache
train
def _read_cache(self): """Read virtualenv metadata from cache.""" if os.path.exists(self.filepath): with open(self.filepath, 'rt', encoding='utf8') as fh: lines = [x.strip() for x in fh] else: logger.debug("Index not found, starting empty") lin...
python
{ "resource": "" }
q237692
VEnvsCache._write_cache
train
def _write_cache(self, lines, append=False): """Write virtualenv metadata to cache.""" mode = 'at' if append else 'wt' with open(self.filepath, mode, encoding='utf8') as fh: fh.writelines(line + '\n' for line in lines)
python
{ "resource": "" }
q237693
PipManager.install
train
def install(self, dependency): """Install a new dependency.""" if not self.pip_installed: logger.info("Need to install a dependency with pip, but no builtin, " "doing it manually (just wait a little, all should go well)") self._brute_force_install_pip() ...
python
{ "resource": "" }
q237694
PipManager.get_version
train
def get_version(self, dependency): """Return the installed version parsing the output of 'pip show'.""" logger.debug("getting installed version for %s", dependency) stdout = helpers.logged_exec([self.pip_exe, "show", str(dependency)]) version = [line for line in stdout if line.startswith...
python
{ "resource": "" }
q237695
PipManager._brute_force_install_pip
train
def _brute_force_install_pip(self): """A brute force install of pip itself.""" if os.path.exists(self.pip_installer_fname): logger.debug("Using pip installer from %r", self.pip_installer_fname) else: logger.debug( "Installer for pip not found in %r, downlo...
python
{ "resource": "" }
q237696
Convert._generate_configs_from_default
train
def _generate_configs_from_default(self, overrides=None): # type: (Dict[str, int]) -> Dict[str, int] """ Generate configs by inheriting from defaults """ config = DEFAULT_CONFIG.copy() if not overrides: overrides = {} for k, v in overrides.items(): config[...
python
{ "resource": "" }
q237697
Convert.read_ical
train
def read_ical(self, ical_file_location): # type: (str) -> Calendar """ Read the ical file """ with open(ical_file_location, 'r') as ical_file: data = ical_file.read() self.cal = Calendar.from_ical(data) return self.cal
python
{ "resource": "" }
q237698
Convert.read_csv
train
def read_csv(self, csv_location, csv_configs=None): # type: (str, Dict[str, int]) -> List[List[str]] """ Read the csv file """ csv_configs = self._generate_configs_from_default(csv_configs) with open(csv_location, 'r') as csv_file: csv_reader = csv.reader(csv_file) ...
python
{ "resource": "" }
q237699
Convert.make_ical
train
def make_ical(self, csv_configs=None): # type: (Dict[str, int]) -> Calendar """ Make iCal entries """ csv_configs = self._generate_configs_from_default(csv_configs) self.cal = Calendar() for row in self.csv_data: event = Event() event.add('summary', row[cs...
python
{ "resource": "" }