Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def update_filter(self, filter_id, body, params=None): for param in (filter_id, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( ...
[ "\n `<>`_\n\n :arg filter_id: The ID of the filter to update\n :arg body: The filter update\n " ]
Please provide a description of the function:def update_model_snapshot(self, job_id, snapshot_id, body, params=None): for param in (job_id, snapshot_id, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.trans...
[ "\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-update-snapshot.html>`_\n\n :arg job_id: The ID of the job to fetch\n :arg snapshot_id: The ID of the snapshot to update\n :arg body: The model snapshot properties to update\n " ]
Please provide a description of the function:def validate(self, body, params=None): if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_ml/anomaly_detectors/_validate", params=p...
[ "\n `<>`_\n\n :arg body: The job config\n " ]
Please provide a description of the function:def validate_detector(self, body, params=None): if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_ml/anomaly_detectors...
[ "\n `<>`_\n\n :arg body: The detector\n " ]
Please provide a description of the function:def analyze(self, index=None, body=None, params=None): return self.transport.perform_request( "GET", _make_path(index, "_analyze"), params=params, body=body )
[ "\n Perform the analysis process on a text and return the tokens breakdown of the text.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-analyze.html>`_\n\n :arg index: The name of the index to scope the operation\n :arg body: Define analyzer/tokenizer parameter...
Please provide a description of the function:def refresh(self, index=None, params=None): return self.transport.perform_request( "POST", _make_path(index, "_refresh"), params=params )
[ "\n Explicitly refresh one or more index, making all operations performed\n since the last refresh available for search.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` or empty\n...
Please provide a description of the function:def flush(self, index=None, params=None): return self.transport.perform_request( "POST", _make_path(index, "_flush"), params=params )
[ "\n Explicitly flush one or more indices.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-flush.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` or empty\n string for all indices\n :arg allow_no_indices: Whether to ignore if ...
Please provide a description of the function:def get(self, index, feature=None, params=None): if index in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'index'.") return self.transport.perform_request( "GET", _make_path(index, feature), param...
[ "\n The get index API allows to retrieve information about one or more indexes.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-index.html>`_\n\n :arg index: A comma-separated list of index names\n :arg allow_no_indices: Ignore if a wildcard expression reso...
Please provide a description of the function:def exists_type(self, index, doc_type, params=None): for param in (index, doc_type): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( ...
[ "\n Check if a type/types exists in an index/indices.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-types-exists.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` to check\n the types across all indices\n :arg doc_type: A co...
Please provide a description of the function:def get_mapping(self, index=None, doc_type=None, params=None): return self.transport.perform_request( "GET", _make_path(index, "_mapping", doc_type), params=params )
[ "\n Retrieve mapping definition of index or index/type.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html>`_\n\n :arg index: A comma-separated list of index names\n :arg doc_type: A comma-separated list of document types\n :arg allow_no_in...
Please provide a description of the function:def get_field_mapping(self, fields, index=None, doc_type=None, params=None): if fields in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'fields'.") return self.transport.perform_request( "GET", ...
[ "\n Retrieve mapping definition of a specific field.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-field-mapping.html>`_\n\n :arg fields: A comma-separated list of fields\n :arg index: A comma-separated list of index names\n :arg doc_type: A comma-...
Please provide a description of the function:def put_alias(self, index, name, body=None, params=None): for param in (index, name): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( ...
[ "\n Create an alias for a specific index/indices.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_\n\n :arg index: A comma-separated list of index names the alias should point\n to (supports wildcards); use `_all` to perform the operation on ...
Please provide a description of the function:def exists_alias(self, index=None, name=None, params=None): return self.transport.perform_request( "HEAD", _make_path(index, "_alias", name), params=params )
[ "\n Return a boolean indicating whether given alias exists.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_\n\n :arg index: A comma-separated list of index names to filter aliases\n :arg name: A comma-separated list of alias names to return\n ...
Please provide a description of the function:def get_alias(self, index=None, name=None, params=None): return self.transport.perform_request( "GET", _make_path(index, "_alias", name), params=params )
[ "\n Retrieve a specified alias.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_\n\n :arg index: A comma-separated list of index names to filter aliases\n :arg name: A comma-separated list of alias names to return\n :arg allow_no_indices: ...
Please provide a description of the function:def update_aliases(self, body, params=None): if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_aliases", params=params, body=body ...
[ "\n Update specified aliases.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_\n\n :arg body: The definition of `actions` to perform\n :arg master_timeout: Specify timeout for connection to master\n :arg request_timeout: Request timeout\n ...
Please provide a description of the function:def delete_alias(self, index, name, params=None): for param in (index, name): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "DE...
[ "\n Delete specific alias.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_\n\n :arg index: A comma-separated list of index names (supports wildcards);\n use `_all` for all indices\n :arg name: A comma-separated list of aliases to dele...
Please provide a description of the function:def get_template(self, name=None, params=None): return self.transport.perform_request( "GET", _make_path("_template", name), params=params )
[ "\n Retrieve an index template by its name.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html>`_\n\n :arg name: The name of the template\n :arg flat_settings: Return settings in flat format (default: false)\n :arg local: Return local informa...
Please provide a description of the function:def get_settings(self, index=None, name=None, params=None): return self.transport.perform_request( "GET", _make_path(index, "_settings", name), params=params )
[ "\n Retrieve settings for one or more (or all) indices.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-settings.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` or empty\n string to perform the operation on all indices\n ...
Please provide a description of the function:def stats(self, index=None, metric=None, params=None): return self.transport.perform_request( "GET", _make_path(index, "_stats", metric), params=params )
[ "\n Retrieve statistics on different operations happening on an index.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-stats.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` or empty\n string to perform the operation on all indices\...
Please provide a description of the function:def clear_cache(self, index=None, params=None): return self.transport.perform_request( "POST", _make_path(index, "_cache", "clear"), params=params )
[ "\n Clear either all caches or specific cached associated with one ore more indices.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-clearcache.html>`_\n\n :arg index: A comma-separated list of index name to limit the operation\n :arg allow_no_indices: Whether ...
Please provide a description of the function:def upgrade(self, index=None, params=None): return self.transport.perform_request( "POST", _make_path(index, "_upgrade"), params=params )
[ "\n Upgrade one or more indices to the latest format through an API.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-upgrade.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` or empty\n string to perform the operation on all indices\...
Please provide a description of the function:def get_upgrade(self, index=None, params=None): return self.transport.perform_request( "GET", _make_path(index, "_upgrade"), params=params )
[ "\n Monitor how much of one or more index is upgraded.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-upgrade.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` or empty\n string to perform the operation on all indices\n :arg ...
Please provide a description of the function:def flush_synced(self, index=None, params=None): return self.transport.perform_request( "POST", _make_path(index, "_flush", "synced"), params=params )
[ "\n Perform a normal flush, then add a generated unique marker (sync_id) to all shards.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-synced-flush.html>`_\n\n :arg index: A comma-separated list of index names; use `_all` or empty\n string for all indices\...
Please provide a description of the function:def shard_stores(self, index=None, params=None): return self.transport.perform_request( "GET", _make_path(index, "_shard_stores"), params=params )
[ "\n Provides store information for shard copies of indices. Store\n information reports on which nodes shard copies exist, the shard copy\n version, indicating how recent they are, and any exceptions encountered\n while opening the shard index or from earlier engine failure.\n `<h...
Please provide a description of the function:def forcemerge(self, index=None, params=None): return self.transport.perform_request( "POST", _make_path(index, "_forcemerge"), params=params )
[ "\n The force merge API allows to force merging of one or more indices\n through an API. The merge relates to the number of segments a Lucene\n index holds within each shard. The force merge operation allows to\n reduce the number of segments by merging them.\n\n This call will bl...
Please provide a description of the function:def shrink(self, index, target, body=None, params=None): for param in (index, target): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( ...
[ "\n The shrink index API allows you to shrink an existing index into a new\n index with fewer primary shards. The number of primary shards in the\n target index must be a factor of the shards in the source index. For\n example an index with 8 primary shards can be shrunk into 4, 2 or 1\n...
Please provide a description of the function:def rollover(self, alias, new_index=None, body=None, params=None): if alias in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'alias'.") return self.transport.perform_request( "POST", _make_path(ali...
[ "\n The rollover index API rolls an alias over to a new index when the\n existing index is considered to be too large or too old.\n\n The API accepts a single alias name and a list of conditions. The alias\n must point to a single index only. If the index satisfies the specified\n ...
Please provide a description of the function:def get(self, repository, snapshot, params=None): for param in (repository, snapshot): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request('GET', ...
[ "\n Retrieve information about a snapshot.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_\n\n :arg repository: A repository name\n :arg snapshot: A comma-separated list of snapshot names\n :arg ignore_unavailable: Whether to ignore una...
Please provide a description of the function:def delete_repository(self, repository, params=None): if repository in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'repository'.") return self.transport.perform_request('DELETE', _make_path('_sna...
[ "\n Removes a shared file system repository.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_\n\n :arg repository: A comma-separated list of repository names\n :arg master_timeout: Explicit operation timeout for connection to master\n ...
Please provide a description of the function:def get_repository(self, repository=None, params=None): return self.transport.perform_request('GET', _make_path('_snapshot', repository), params=params)
[ "\n Return information about registered repositories.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_\n\n :arg repository: A comma-separated list of repository names\n :arg local: Return local information, do not retrieve the state from\n ...
Please provide a description of the function:def create_repository(self, repository, body, params=None): for param in (repository, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request('...
[ "\n Registers a shared file system repository.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_\n\n :arg repository: A repository name\n :arg body: The repository definition\n :arg master_timeout: Explicit operation timeout for connectio...
Please provide a description of the function:def restore(self, repository, snapshot, body=None, params=None): for param in (repository, snapshot): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_...
[ "\n Restore a snapshot.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_\n\n :arg repository: A repository name\n :arg snapshot: A snapshot name\n :arg body: Details of what to restore\n :arg master_timeout: Explicit operation tim...
Please provide a description of the function:def status(self, repository=None, snapshot=None, params=None): return self.transport.perform_request('GET', _make_path('_snapshot', repository, snapshot, '_status'), params=params)
[ "\n Return information about all currently running snapshots. By specifying\n a repository name, it's possible to limit the results to a particular\n repository.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_\n\n :arg repository: A rep...
Please provide a description of the function:def _escape(value): # make sequences into comma-separated stings if isinstance(value, (list, tuple)): value = ",".join(value) # dates and datetimes into isoformat elif isinstance(value, (date, datetime)): value = value.isoformat() ...
[ "\n Escape a single value of a URL string or a query parameter. If it is a list\n or tuple, turn it into a comma-separated string first.\n " ]
Please provide a description of the function:def _make_path(*parts): # TODO: maybe only allow some parts to be lists/tuples ? return "/" + "/".join( # preserve ',' and '*' in url for nicer URLs in logs quote_plus(_escape(p), b",*") for p in parts if p not in SKIP_IN_PATH ...
[ "\n Create a URL string from parts, omit all `None` values and empty strings.\n Convert lists and tuples to comma separated values.\n " ]
Please provide a description of the function:def query_params(*es_query_params): def _wrapper(func): @wraps(func) def _wrapped(*args, **kwargs): params = {} if "params" in kwargs: params = kwargs.pop("params").copy() for p in es_query_params ...
[ "\n Decorator that pops all accepted parameters from method's kwargs and puts\n them in the params argument.\n " ]
Please provide a description of the function:def get(self, task_id=None, params=None): return self.transport.perform_request('GET', _make_path('_tasks', task_id), params=params)
[ "\n Retrieve information for a particular task.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_\n\n :arg task_id: Return the task with specified id (node_id:task_number)\n :arg wait_for_completion: Wait for the matching tasks to complete\n (def...
Please provide a description of the function:def print_hits(results): " Simple utility function to print results of a search query. " print_search_stats(results) for hit in results['hits']['hits']: # get created date for a repo and fallback to authored_date for a commit created_at = parse_da...
[]
Please provide a description of the function:def post(self): body = tornado.escape.json_decode(self.request.body) try: self._bo.register( params=body["params"], target=body["target"], ) print("BO has registered: {} points.".fo...
[ "Deal with incoming requests." ]
Please provide a description of the function:def register(self, params, target): self._space.register(params, target) self.dispatch(Events.OPTMIZATION_STEP)
[ "Expect observation with known target" ]
Please provide a description of the function:def probe(self, params, lazy=True): if lazy: self._queue.add(params) else: self._space.probe(params) self.dispatch(Events.OPTMIZATION_STEP)
[ "Probe target of x" ]
Please provide a description of the function:def suggest(self, utility_function): if len(self._space) == 0: return self._space.array_to_params(self._space.random_sample()) # Sklearn's GP throws a large number of warnings at times, but # we don't really need to see them here...
[ "Most promissing point to probe next" ]
Please provide a description of the function:def _prime_queue(self, init_points): if self._queue.empty and self._space.empty: init_points = max(init_points, 1) for _ in range(init_points): self._queue.add(self._space.random_sample())
[ "Make sure there's something in the queue at the very beginning." ]
Please provide a description of the function:def maximize(self, init_points=5, n_iter=25, acq='ucb', kappa=2.576, xi=0.0, **gp_params): self._prime_subscriptions() self.dispatch(Events.OPTMIZAT...
[ "Mazimize your function" ]
Please provide a description of the function:def register(self, params, target): x = self._as_array(params) if x in self: raise KeyError('Data point {} is not unique'.format(x)) # Insert data into unique dictionary self._cache[_hashable(x.ravel())] = target ...
[ "\n Append a point and its target value to the known data.\n\n Parameters\n ----------\n x : ndarray\n a single point, with len(x) == self.dim\n\n y : float\n target function value\n\n Raises\n ------\n KeyError:\n if the point...
Please provide a description of the function:def probe(self, params): x = self._as_array(params) try: target = self._cache[_hashable(x)] except KeyError: params = dict(zip(self._keys, x)) target = self.target_func(**params) self.register(...
[ "\n Evaulates a single point x, to obtain the value y and then records them\n as observations.\n\n Notes\n -----\n If x has been previously seen returns a cached value of y.\n\n Parameters\n ----------\n x : ndarray\n a single point, with len(x) == ...
Please provide a description of the function:def random_sample(self): # TODO: support integer, category, and basic scipy.optimize constraints data = np.empty((1, self.dim)) for col, (lower, upper) in enumerate(self._bounds): data.T[col] = self.random_state.uniform(lower, upp...
[ "\n Creates random points within the bounds of the space.\n\n Returns\n ----------\n data: ndarray\n [num x dim] array points with dimensions corresponding to `self._keys`\n\n Example\n -------\n >>> target_func = lambda p1, p2: p1 + p2\n >>> pbound...
Please provide a description of the function:def max(self): try: res = { 'target': self.target.max(), 'params': dict( zip(self.keys, self.params[self.target.argmax()]) ) } except ValueError: ...
[ "Get maximum target value found and corresponding parametes." ]
Please provide a description of the function:def res(self): params = [dict(zip(self.keys, p)) for p in self.params] return [ {"target": target, "params": param} for target, param in zip(self.target, params) ]
[ "Get all target values found and corresponding parametes." ]
Please provide a description of the function:def set_bounds(self, new_bounds): for row, key in enumerate(self.keys): if key in new_bounds: self._bounds[row] = new_bounds[key]
[ "\n A method that allows changing the lower and upper searching bounds\n\n Parameters\n ----------\n new_bounds : dict\n A dictionary with the parameter name and its new bounds\n " ]
Please provide a description of the function:def get_data(): data, targets = make_classification( n_samples=1000, n_features=45, n_informative=12, n_redundant=7, random_state=134985745, ) return data, targets
[ "Synthetic binary classification dataset." ]
Please provide a description of the function:def svc_cv(C, gamma, data, targets): estimator = SVC(C=C, gamma=gamma, random_state=2) cval = cross_val_score(estimator, data, targets, scoring='roc_auc', cv=4) return cval.mean()
[ "SVC cross validation.\n\n This function will instantiate a SVC classifier with parameters C and\n gamma. Combined with data and targets this will in turn be used to perform\n cross validation. The result of cross validation is returned.\n\n Our goal is to find combinations of C and gamma that maximizes...
Please provide a description of the function:def rfc_cv(n_estimators, min_samples_split, max_features, data, targets): estimator = RFC( n_estimators=n_estimators, min_samples_split=min_samples_split, max_features=max_features, random_state=2 ) cval = cross_val_score(esti...
[ "Random Forest cross validation.\n\n This function will instantiate a random forest classifier with parameters\n n_estimators, min_samples_split, and max_features. Combined with data and\n targets this will in turn be used to perform cross validation. The result\n of cross validation is returned.\n\n ...
Please provide a description of the function:def optimize_svc(data, targets): def svc_crossval(expC, expGamma): C = 10 ** expC gamma = 10 ** expGamma return svc_cv(C=C, gamma=gamma, data=data, targets=targets) optimizer = BayesianOptimization( f=svc_crossval, ...
[ "Apply Bayesian Optimization to SVC parameters.", "Wrapper of SVC cross validation.\n\n Notice how we transform between regular and log scale. While this\n is not technically necessary, it greatly improves the performance\n of the optimizer.\n " ]
Please provide a description of the function:def optimize_rfc(data, targets): def rfc_crossval(n_estimators, min_samples_split, max_features): return rfc_cv( n_estimators=int(n_estimators), min_samples_split=int(min_samples_split), max_features=max(min(max_f...
[ "Apply Bayesian Optimization to Random Forest parameters.", "Wrapper of RandomForest cross validation.\n\n Notice how we ensure n_estimators and min_samples_split are casted\n to integer before we pass them along. Moreover, to avoid max_features\n taking values outside the (0, 1) range, we al...
Please provide a description of the function:def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=100000, n_iter=250): # Warm up with random points x_tries = random_state.uniform(bounds[:, 0], bounds[:, 1], size=(n_warmup, bounds.shape[0])) ys = ac(x_tries, gp=g...
[ "\n A function to find the maximum of the acquisition function\n\n It uses a combination of random sampling (cheap) and the 'L-BFGS-B'\n optimization method. First by sampling `n_warmup` (1e5) points at random,\n and then running L-BFGS-B from `n_iter` (250) random starting points.\n\n Parameters\n ...
Please provide a description of the function:def load_logs(optimizer, logs): import json if isinstance(logs, str): logs = [logs] for log in logs: with open(log, "r") as j: while True: try: iteration = next(j) except StopI...
[ "Load previous ...\n\n " ]
Please provide a description of the function:def ensure_rng(random_state=None): if random_state is None: random_state = np.random.RandomState() elif isinstance(random_state, int): random_state = np.random.RandomState(random_state) else: assert isinstance(random_state, np.random....
[ "\n Creates a random number generator based on an optional seed. This can be\n an integer or another random state for a seeded rng, or None for an\n unseeded rng.\n " ]
Please provide a description of the function:def expand_abbreviations(template, abbreviations): if template in abbreviations: return abbreviations[template] # Split on colon. If there is no colon, rest will be empty # and prefix will be the whole template prefix, sep, rest = template.parti...
[ "Expand abbreviations in a template name.\n\n :param template: The project template name.\n :param abbreviations: Abbreviation definitions.\n " ]
Please provide a description of the function:def repository_has_cookiecutter_json(repo_directory): repo_directory_exists = os.path.isdir(repo_directory) repo_config_exists = os.path.isfile( os.path.join(repo_directory, 'cookiecutter.json') ) return repo_directory_exists and repo_config_exi...
[ "Determine if `repo_directory` contains a `cookiecutter.json` file.\n\n :param repo_directory: The candidate repository directory.\n :return: True if the `repo_directory` is valid, else False.\n " ]
Please provide a description of the function:def determine_repo_dir(template, abbreviations, clone_to_dir, checkout, no_input, password=None): template = expand_abbreviations(template, abbreviations) if is_zip_file(template): unzipped_dir = unzip( zip_uri=templat...
[ "\n Locate the repository directory from a template reference.\n\n Applies repository abbreviations to the template reference.\n If the template refers to a repository URL, clone it.\n If the template is a path to a local repository, use it.\n\n :param template: A directory containing a project templ...
Please provide a description of the function:def find_template(repo_dir): logger.debug('Searching {} for the project template.'.format(repo_dir)) repo_dir_contents = os.listdir(repo_dir) project_template = None for item in repo_dir_contents: if 'cookiecutter' in item and '{{' in item and ...
[ "Determine which child directory of `repo_dir` is the project template.\n\n :param repo_dir: Local directory of newly cloned repo.\n :returns project_template: Relative path to project template.\n " ]
Please provide a description of the function:def is_copy_only_path(path, context): try: for dont_render in context['cookiecutter']['_copy_without_render']: if fnmatch.fnmatch(path, dont_render): return True except KeyError: return False return False
[ "Check whether the given `path` should only be copied and not rendered.\n\n Returns True if `path` matches a pattern in the given `context` dict,\n otherwise False.\n\n :param path: A file-system path referring to a file or dir that\n should be rendered or just copied.\n :param context: cookiecut...
Please provide a description of the function:def apply_overwrites_to_context(context, overwrite_context): for variable, overwrite in overwrite_context.items(): if variable not in context: # Do not include variables which are not used in the template continue context_val...
[ "Modify the given context in place based on the overwrite_context." ]
Please provide a description of the function:def generate_context(context_file='cookiecutter.json', default_context=None, extra_context=None): context = OrderedDict([]) try: with open(context_file) as file_handle: obj = json.load(file_handle, object_pairs_hook=Orde...
[ "Generate the context for a Cookiecutter project template.\n\n Loads the JSON file as a Python object, with key being the JSON filename.\n\n :param context_file: JSON file containing key/value pairs for populating\n the cookiecutter's variables.\n :param default_context: Dictionary containing config...
Please provide a description of the function:def generate_file(project_dir, infile, context, env): logger.debug('Processing file {}'.format(infile)) # Render the path to the output file (not including the root project dir) outfile_tmpl = env.from_string(infile) outfile = os.path.join(project_dir,...
[ "Render filename of infile as name of outfile, handle infile correctly.\n\n Dealing with infile appropriately:\n\n a. If infile is a binary file, copy it over without rendering.\n b. If infile is a text file, render its contents and write the\n rendered infile to outfile.\n\n Precondit...
Please provide a description of the function:def render_and_create_dir(dirname, context, output_dir, environment, overwrite_if_exists=False): name_tmpl = environment.from_string(dirname) rendered_dirname = name_tmpl.render(**context) dir_to_create = os.path.normpath( ...
[ "Render name of a directory, create the directory, return its path." ]
Please provide a description of the function:def _run_hook_from_repo_dir(repo_dir, hook_name, project_dir, context, delete_project_on_failure): with work_in(repo_dir): try: run_hook(hook_name, project_dir, context) except FailedHookException: ...
[ "Run hook from repo directory, clean project directory if hook fails.\n\n :param repo_dir: Project template input directory.\n :param hook_name: The hook to execute.\n :param project_dir: The directory to execute the script from.\n :param context: Cookiecutter project context.\n :param delete_project...
Please provide a description of the function:def generate_files(repo_dir, context=None, output_dir='.', overwrite_if_exists=False): template_dir = find_template(repo_dir) logger.debug('Generating project from {}...'.format(template_dir)) context = context or OrderedDict([]) unre...
[ "Render the templates and saves them to files.\n\n :param repo_dir: Project template input directory.\n :param context: Dict for populating the template's variables.\n :param output_dir: Where to output the generated project dir into.\n :param overwrite_if_exists: Overwrite the contents of the output di...
Please provide a description of the function:def _expand_path(path): path = os.path.expandvars(path) path = os.path.expanduser(path) return path
[ "Expand both environment variables and user home in the given path." ]
Please provide a description of the function:def merge_configs(default, overwrite): new_config = copy.deepcopy(default) for k, v in overwrite.items(): # Make sure to preserve existing items in # nested dicts, for example `abbreviations` if isinstance(v, dict): new_confi...
[ "Recursively update a dict with the key/value pair of another.\n\n Dict values that are dictionaries themselves will be updated, whilst\n preserving existing keys.\n " ]
Please provide a description of the function:def get_config(config_path): if not os.path.exists(config_path): raise ConfigDoesNotExistException logger.debug('config_path is {0}'.format(config_path)) with io.open(config_path, encoding='utf-8') as file_handle: try: yaml_dict ...
[ "Retrieve the config from the specified path, returning a config dict." ]
Please provide a description of the function:def get_user_config(config_file=None, default_config=False): # Do NOT load a config. Return defaults instead. if default_config: return copy.copy(DEFAULT_CONFIG) # Load the given config file if config_file and config_file is not USER_CONFIG_PATH...
[ "Return the user config as a dict.\n\n If ``default_config`` is True, ignore ``config_file`` and return default\n values for the config parameters.\n\n If a path to a ``config_file`` is given, that is different from the default\n location, load the user config from that.\n\n Otherwise look up the con...
Please provide a description of the function:def force_delete(func, path, exc_info): os.chmod(path, stat.S_IWRITE) func(path)
[ "Error handler for `shutil.rmtree()` equivalent to `rm -rf`.\n\n Usage: `shutil.rmtree(path, onerror=force_delete)`\n From stackoverflow.com/questions/1889597\n " ]
Please provide a description of the function:def make_sure_path_exists(path): logger.debug('Making sure path exists: {}'.format(path)) try: os.makedirs(path) logger.debug('Created directory at: {}'.format(path)) except OSError as exception: if exception.errno != errno.EEXIST: ...
[ "Ensure that a directory exists.\n\n :param path: A directory path.\n " ]
Please provide a description of the function:def work_in(dirname=None): curdir = os.getcwd() try: if dirname is not None: os.chdir(dirname) yield finally: os.chdir(curdir)
[ "Context manager version of os.chdir.\n\n When exited, returns to the working directory prior to entering.\n " ]
Please provide a description of the function:def make_executable(script_path): status = os.stat(script_path) os.chmod(script_path, status.st_mode | stat.S_IEXEC)
[ "Make `script_path` executable.\n\n :param script_path: The file to change\n " ]
Please provide a description of the function:def prompt_and_delete(path, no_input=False): # Suppress prompt if called via API if no_input: ok_to_delete = True else: question = ( "You've downloaded {} before. " "Is it okay to delete and re-download it?" )....
[ "\n Ask user if it's okay to delete the previously-downloaded file/directory.\n\n If yes, delete it. If no, checks to see if the old version should be\n reused. If yes, it's reused; otherwise, Cookiecutter exits.\n\n :param path: Previously downloaded zipfile.\n :param no_input: Suppress prompt to de...
Please provide a description of the function:def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None): # Ensure that clone_to_dir exists clone_to_dir = os.path.expanduser(clone_to_dir) make_sure_path_exists(clone_to_dir) if is_url: # Build the name of the cached zipfile,...
[ "Download and unpack a zipfile at a given URI.\n\n This will download the zipfile to the cookiecutter repository,\n and unpack into a temporary directory.\n\n :param zip_uri: The URI for the zipfile.\n :param is_url: Is the zip URI a URL or a file?\n :param clone_to_dir: The cookiecutter repository d...
Please provide a description of the function:def cookiecutter( template, checkout=None, no_input=False, extra_context=None, replay=False, overwrite_if_exists=False, output_dir='.', config_file=None, default_config=False, password=None): if replay and ((no_input is not False) or (extra_c...
[ "\n Run Cookiecutter just as if using it from the command line.\n\n :param template: A directory containing a project template directory,\n or a URL to a git repository.\n :param checkout: The branch, tag or commit ID to checkout after clone.\n :param no_input: Prompt the user at command line for...
Please provide a description of the function:def read_user_yes_no(question, default_value): # Please see http://click.pocoo.org/4/api/#click.prompt return click.prompt( question, default=default_value, type=click.BOOL )
[ "Prompt the user to reply with 'yes' or 'no' (or equivalent values).\n\n Note:\n Possible choices are 'true', '1', 'yes', 'y' or 'false', '0', 'no', 'n'\n\n :param str question: Question to the user\n :param default_value: Value that will be returned if no input happens\n " ]
Please provide a description of the function:def read_user_choice(var_name, options): # Please see http://click.pocoo.org/4/api/#click.prompt if not isinstance(options, list): raise TypeError if not options: raise ValueError choice_map = OrderedDict( (u'{}'.format(i), valu...
[ "Prompt the user to choose from several options for the given variable.\n\n The first item will be returned if no input happens.\n\n :param str var_name: Variable as specified in the context\n :param list options: Sequence of options that are available to select from\n :return: Exactly one item of ``opt...
Please provide a description of the function:def read_user_dict(var_name, default_value): # Please see http://click.pocoo.org/4/api/#click.prompt if not isinstance(default_value, dict): raise TypeError default_display = 'default' user_value = click.prompt( var_name, defaul...
[ "Prompt the user to provide a dictionary of data.\n\n :param str var_name: Variable as specified in the context\n :param default_value: Value that will be returned if no input is provided\n :return: A Python dictionary to use in the context.\n " ]
Please provide a description of the function:def render_variable(env, raw, cookiecutter_dict): if raw is None: return None elif isinstance(raw, dict): return { render_variable(env, k, cookiecutter_dict): render_variable(env, v, cookiecutter_dict) for ...
[ "Inside the prompting taken from the cookiecutter.json file, this renders\n the next variable. For example, if a project_name is \"Peanut Butter\n Cookie\", the repo_name could be be rendered with:\n\n `{{ cookiecutter.project_name.replace(\" \", \"_\") }}`.\n\n This is then presented to the user as...
Please provide a description of the function:def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input): rendered_options = [ render_variable(env, raw, cookiecutter_dict) for raw in options ] if no_input: return rendered_options[0] return read_user_choice(key, ren...
[ "Prompt the user which option to choose from the given. Each of the\n possible choices is rendered beforehand.\n " ]
Please provide a description of the function:def prompt_for_config(context, no_input=False): cookiecutter_dict = OrderedDict([]) env = StrictEnvironment(context=context) # First pass: Handle simple and raw variables, plus choices. # These must be done first because the dictionaries keys and # ...
[ "\n Prompts the user to enter new config, using context as a source for the\n field names and sample values.\n\n :param no_input: Prompt the user at command line for manual configuration?\n " ]
Please provide a description of the function:def _read_extensions(self, context): try: extensions = context['cookiecutter']['_extensions'] except KeyError: return [] else: return [str(ext) for ext in extensions]
[ "Return list of extensions as str to be passed on to the Jinja2 env.\n\n If context does not contain the relevant info, return an empty\n list instead.\n " ]
Please provide a description of the function:def configure_logger(stream_level='DEBUG', debug_file=None): # Set up 'cookiecutter' logger logger = logging.getLogger('cookiecutter') logger.setLevel(logging.DEBUG) # Remove all attached handlers, in case there was # a logger with using the name 'c...
[ "Configure logging for cookiecutter.\n\n Set up logging to stdout with given level. If ``debug_file`` is given set\n up logging to file with DEBUG level.\n " ]
Please provide a description of the function:def identify_repo(repo_url): repo_url_values = repo_url.split('+') if len(repo_url_values) == 2: repo_type = repo_url_values[0] if repo_type in ["git", "hg"]: return repo_type, repo_url_values[1] else: raise Unknow...
[ "Determine if `repo_url` should be treated as a URL to a git or hg repo.\n\n Repos can be identified by prepending \"hg+\" or \"git+\" to the repo URL.\n\n :param repo_url: Repo URL of unknown type.\n :returns: ('git', repo_url), ('hg', repo_url), or None.\n " ]
Please provide a description of the function:def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False): # Ensure that clone_to_dir exists clone_to_dir = os.path.expanduser(clone_to_dir) make_sure_path_exists(clone_to_dir) # identify the repo_type repo_type, repo_url = identify_repo(...
[ "Clone a repo to the current directory.\n\n :param repo_url: Repo URL of unknown type.\n :param checkout: The branch, tag or commit ID to checkout after clone.\n :param clone_to_dir: The directory to clone to.\n Defaults to the current directory.\n :param no_input: Suppress all u...
Please provide a description of the function:def valid_hook(hook_file, hook_name): filename = os.path.basename(hook_file) basename = os.path.splitext(filename)[0] matching_hook = basename == hook_name supported_hook = basename in _HOOKS backup_file = filename.endswith('~') return matching...
[ "Determine if a hook file is valid.\n\n :param hook_file: The hook file to consider for validity\n :param hook_name: The hook to find\n :return: The hook file validity\n " ]
Please provide a description of the function:def find_hook(hook_name, hooks_dir='hooks'): logger.debug('hooks_dir is {}'.format(os.path.abspath(hooks_dir))) if not os.path.isdir(hooks_dir): logger.debug('No hooks/ dir in template_dir') return None for hook_file in os.listdir(hooks_dir...
[ "Return a dict of all hook scripts provided.\n\n Must be called with the project template as the current working directory.\n Dict's key will be the hook/script's name, without extension, while values\n will be the absolute path to the script. Missing scripts will not be\n included in the returned dict....
Please provide a description of the function:def run_script(script_path, cwd='.'): run_thru_shell = sys.platform.startswith('win') if script_path.endswith('.py'): script_command = [sys.executable, script_path] else: script_command = [script_path] utils.make_executable(script_path) ...
[ "Execute a script from a working directory.\n\n :param script_path: Absolute path to the script to run.\n :param cwd: The directory to run the script from.\n " ]
Please provide a description of the function:def run_script_with_context(script_path, cwd, context): _, extension = os.path.splitext(script_path) contents = io.open(script_path, 'r', encoding='utf-8').read() with tempfile.NamedTemporaryFile( delete=False, mode='wb', suffix=ext...
[ "Execute a script after rendering it with Jinja.\n\n :param script_path: Absolute path to the script to run.\n :param cwd: The directory to run the script from.\n :param context: Cookiecutter project template context.\n " ]
Please provide a description of the function:def run_hook(hook_name, project_dir, context): script = find_hook(hook_name) if script is None: logger.debug('No {} hook found'.format(hook_name)) return logger.debug('Running hook {}'.format(hook_name)) run_script_with_context(script, pr...
[ "\n Try to find and execute a hook from the specified project directory.\n\n :param hook_name: The hook to execute.\n :param project_dir: The directory to execute the script from.\n :param context: Cookiecutter project context.\n " ]
Please provide a description of the function:def version_msg(): python_version = sys.version[:3] location = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) message = u'Cookiecutter %(version)s from {} (Python {})' return message.format(location, python_version)
[ "Return the Cookiecutter version, location and Python powering it." ]
Please provide a description of the function:def validate_extra_context(ctx, param, value): for s in value: if '=' not in s: raise click.BadParameter( 'EXTRA_CONTEXT should contain items of the form key=value; ' "'{}' doesn't match that form".format(s) ...
[ "Validate extra context." ]
Please provide a description of the function:def main( template, extra_context, no_input, checkout, verbose, replay, overwrite_if_exists, output_dir, config_file, default_config, debug_file): # If you _need_ to support a local template in a directory # called 'help', use a qualified...
[ "Create a project from a Cookiecutter project template (TEMPLATE).\n\n Cookiecutter is free and open source software, developed and managed by\n volunteers. If you would like to help out or fund the project, please get\n in touch at https://github.com/audreyr/cookiecutter.\n " ]
Please provide a description of the function:def mounted(cls, unmounted): # noqa: N802 assert isinstance(unmounted, UnmountedType), ("{} can't mount {}").format( cls.__name__, repr(unmounted) ) return cls( unmounted.get_type(), *unmounted.args, ...
[ "\n Mount the UnmountedType instance\n " ]
Please provide a description of the function:def replace( self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void, ): if name is _void: name = self._name if kind is _void: kind = self._kind...
[ "Creates a customized copy of the Parameter." ]