_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q260700
SimilarityDistance.predict_proba
validation
def predict_proba(self, X): """Returns the value of the nearest neighbor from the training set. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and i...
python
{ "resource": "" }
q260701
Leverage.fit
validation
def fit(self, X, y=None): """Learning is to find the inverse matrix for X and calculate the threshold. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. ...
python
{ "resource": "" }
q260702
Leverage.predict_proba
validation
def predict_proba(self, X): """Predict the distances for X to center of the training set. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a spa...
python
{ "resource": "" }
q260703
Leverage.predict
validation
def predict(self, X): """Predict inside or outside AD for X. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided ...
python
{ "resource": "" }
q260704
Box.fit
validation
def fit(self, X, y=None): """Find min and max values of every feature. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The training input samples. y : Ignored not used, present for API consistency by convention. ...
python
{ "resource": "" }
q260705
CIMtoolsTransformerMixin.fit
validation
def fit(self, x, y=None): """Do nothing and return the estimator unchanged This method is just there to implement the usual API and hence work in pipelines. """ if self._dtype is not None: iter2array(x, dtype=self._dtype) else: iter2array(x) retur...
python
{ "resource": "" }
q260706
Fragmentor.finalize
validation
def finalize(self): """ finalize partial fitting procedure """ if self.__head_less: warn(f'{self.__class__.__name__} configured to head less mode. finalize unusable') elif not self.__head_generate: warn(f'{self.__class__.__name__} already finalized or fitt...
python
{ "resource": "" }
q260707
Fragmentor.fit
validation
def fit(self, x, y=None): """Compute the header. """ x = iter2array(x, dtype=(MoleculeContainer, CGRContainer)) if self.__head_less: warn(f'{self.__class__.__name__} configured to head less mode. fit unusable') return self self._reset() self.__pr...
python
{ "resource": "" }
q260708
ReactionTypeControl.fit
validation
def fit(self, X): """Fit structure-based AD. The training model memorizes the unique set of reaction signature. Parameters ---------- X : after read rdf file Returns ------- self : object """ X = iter2array(X, dtype=ReactionContainer) se...
python
{ "resource": "" }
q260709
_self_referential_fk
validation
def _self_referential_fk(klass_model): """ Return whether this model has a self ref FK, and the name for the field """ for f in klass_model._meta.concrete_fields: if f.related_model: if issubclass(klass_model, f.related_model): return f.attname return None
python
{ "resource": "" }
q260710
SyncableModel.serialize
validation
def serialize(self): """All concrete fields of the ``SyncableModel`` subclass, except for those specifically blacklisted, are returned in a dict.""" # NOTE: code adapted from https://github.com/django/django/blob/master/django/forms/models.py#L75 opts = self._meta data = {} for ...
python
{ "resource": "" }
q260711
SyncableModel.deserialize
validation
def deserialize(cls, dict_model): """Returns an unsaved class object based on the valid properties passed in.""" kwargs = {} for f in cls._meta.concrete_fields: if f.attname in dict_model: kwargs[f.attname] = dict_model[f.attname] return cls(**kwargs)
python
{ "resource": "" }
q260712
UUIDField.get_default
validation
def get_default(self): """ Returns the default value for this field. """ if self.has_default(): if callable(self.default): default = self.default() if isinstance(default, uuid.UUID): return default.hex return...
python
{ "resource": "" }
q260713
UUIDModelMixin.calculate_uuid
validation
def calculate_uuid(self): """Should return a 32-digit hex string for a UUID that is calculated as a function of a set of fields from the model.""" # raise an error if no inputs to the UUID calculation were specified if self.uuid_input_fields is None: raise NotImplementedError("""You...
python
{ "resource": "" }
q260714
add_to_deleted_models
validation
def add_to_deleted_models(sender, instance=None, *args, **kwargs): """ Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark the model as deleted in the store. """ if issubclass(sender, SyncableModel): instance._update_del...
python
{ "resource": "" }
q260715
APIWrapper._with_error_handling
validation
def _with_error_handling(resp, error, mode, response_format): """ Static method for error handling. :param resp - API response :param error - Error thrown :param mode - Error mode :param response_format - XML or json """ def safe_parse(r): try...
python
{ "resource": "" }
q260716
APIWrapper._default_poll_callback
validation
def _default_poll_callback(self, poll_resp): """ Checks the condition in poll response to determine if it is complete and no subsequent poll requests should be done. """ if poll_resp.parsed is None: return False success_list = ['UpdatesComplete', True, 'COMPLE...
python
{ "resource": "" }
q260717
_fsic_queuing_calc
validation
def _fsic_queuing_calc(fsic1, fsic2): """ We set the lower counter between two same instance ids. If an instance_id exists in one fsic but not the other we want to give that counter a value of 0. :param fsic1: dictionary containing (instance_id, counter) pairs :param fsic2: dictionary containing (i...
python
{ "resource": "" }
q260718
_deserialize_from_store
validation
def _deserialize_from_store(profile): """ Takes data from the store and integrates into the application. """ # we first serialize to avoid deserialization merge conflicts _serialize_into_store(profile) fk_cache = {} with transaction.atomic(): syncable_dict = _profile_models[profile]...
python
{ "resource": "" }
q260719
_dequeue_into_store
validation
def _dequeue_into_store(transfersession): """ Takes data from the buffers and merges into the store and record max counters. """ with connection.cursor() as cursor: DBBackend._dequeuing_delete_rmcb_records(cursor, transfersession.id) DBBackend._dequeuing_delete_buffered_records(cursor, t...
python
{ "resource": "" }
q260720
max_parameter_substitution
validation
def max_parameter_substitution(): """ SQLite has a limit on the max number of variables allowed for parameter substitution. This limit is usually 999, but can be compiled to a different number. This function calculates what the max is for the sqlite version running on the device. We use the calculated v...
python
{ "resource": "" }
q260721
BasicMultiArgumentAuthentication.authenticate_credentials
validation
def authenticate_credentials(self, userargs, password, request=None): """ Authenticate the userargs and password against Django auth backends. The "userargs" string may be just the username, or a querystring-encoded set of params. """ credentials = { 'password': pass...
python
{ "resource": "" }
q260722
_multiple_self_ref_fk_check
validation
def _multiple_self_ref_fk_check(class_model): """ We check whether a class has more than 1 FK reference to itself. """ self_fk = [] for f in class_model._meta.concrete_fields: if f.related_model in self_fk: return True if f.related_model == class_model: self_f...
python
{ "resource": "" }
q260723
add_syncable_models
validation
def add_syncable_models(): """ Per profile, adds each model to a dictionary mapping the morango model name to its model class. We sort by ForeignKey dependencies to safely sync data. """ import django.apps from morango.models import SyncableModel from morango.manager import SyncableModelMan...
python
{ "resource": "" }
q260724
NetworkSyncConnection._request
validation
def _request(self, endpoint, method="GET", lookup=None, data={}, params={}, userargs=None, password=None): """ Generic request method designed to handle any morango endpoint. :param endpoint: constant representing which morango endpoint we are querying :param method: HTTP verb/method fo...
python
{ "resource": "" }
q260725
TokenGenerator.create_access_token
validation
def create_access_token(self, valid_in_hours=1, data=None): """ Creates an access token. TODO: check valid in hours TODO: maybe specify how often a token can be used """ data = data or {} token = AccessToken( token=self.generate(), expires...
python
{ "resource": "" }
q260726
MongodbServiceStore.save_service
validation
def save_service(self, service, overwrite=True): """ Stores an OWS service in mongodb. """ name = namesgenerator.get_sane_name(service.name) if not name: name = namesgenerator.get_random_name() if self.collection.count_documents({'name': name}) > 0: ...
python
{ "resource": "" }
q260727
MongodbServiceStore.list_services
validation
def list_services(self): """ Lists all services in mongodb storage. """ my_services = [] for service in self.collection.find().sort('name', pymongo.ASCENDING): my_services.append(Service(service)) return my_services
python
{ "resource": "" }
q260728
MongodbServiceStore.fetch_by_name
validation
def fetch_by_name(self, name): """ Gets service for given ``name`` from mongodb storage. """ service = self.collection.find_one({'name': name}) if not service: raise ServiceNotFound return Service(service)
python
{ "resource": "" }
q260729
MongodbServiceStore.fetch_by_url
validation
def fetch_by_url(self, url): """ Gets service for given ``url`` from mongodb storage. """ service = self.collection.find_one({'url': url}) if not service: raise ServiceNotFound return Service(service)
python
{ "resource": "" }
q260730
owsproxy_delegate
validation
def owsproxy_delegate(request): """ Delegates owsproxy request to external twitcher service. """ twitcher_url = request.registry.settings.get('twitcher.url') protected_path = request.registry.settings.get('twitcher.ows_proxy_protected_path', '/ows') url = twitcher_url + protected_path + '/proxy'...
python
{ "resource": "" }
q260731
ows_security_tween_factory
validation
def ows_security_tween_factory(handler, registry): """A tween factory which produces a tween which raises an exception if access to OWS service is not allowed.""" security = owssecurity_factory(registry) def ows_security_tween(request): try: security.check_request(request) ...
python
{ "resource": "" }
q260732
includeme
validation
def includeme(config): """ The callable makes it possible to include rpcinterface in a Pyramid application. Calling ``config.include(twitcher.rpcinterface)`` will result in this callable being called. Arguments: * ``config``: the ``pyramid.config.Configurator`` object. """ settings = ...
python
{ "resource": "" }
q260733
MemoryServiceStore.save_service
validation
def save_service(self, service, overwrite=True): """ Store an OWS service in database. """ name = namesgenerator.get_sane_name(service.name) if not name: name = namesgenerator.get_random_name() if name in self.name_index: name = namesgenera...
python
{ "resource": "" }
q260734
MemoryServiceStore.list_services
validation
def list_services(self): """ Lists all services in memory storage. """ my_services = [] for service in self.name_index.values(): my_services.append(Service(service)) return my_services
python
{ "resource": "" }
q260735
MemoryServiceStore.fetch_by_name
validation
def fetch_by_name(self, name): """ Get service for given ``name`` from memory storage. """ service = self.name_index.get(name) if not service: raise ServiceNotFound return Service(service)
python
{ "resource": "" }
q260736
ESGFAccessManager._retrieve_certificate
validation
def _retrieve_certificate(self, access_token, timeout=3): """ Generates a new private key and certificate request, submits the request to be signed by the SLCS CA and returns the certificate. """ logger.debug("Retrieve certificate with token.") # Generate a new key pair ...
python
{ "resource": "" }
q260737
Get._get_param
validation
def _get_param(self, param, allowed_values=None, optional=False): """Get parameter in GET request.""" request_params = self._request_params() if param in request_params: value = request_params[param].lower() if allowed_values is not None: if value in allow...
python
{ "resource": "" }
q260738
Get._get_version
validation
def _get_version(self): """Find requested version in GET request.""" version = self._get_param(param="version", allowed_values=allowed_versions[self.params['service']], optional=True) if version is None and self._get_request_type() != "getcapabilities": ...
python
{ "resource": "" }
q260739
Post._get_service
validation
def _get_service(self): """Check mandatory service name parameter in POST request.""" if "service" in self.document.attrib: value = self.document.attrib["service"].lower() if value in allowed_service_types: self.params["service"] = value else: ...
python
{ "resource": "" }
q260740
Post._get_request_type
validation
def _get_request_type(self): """Find requested request type in POST request.""" value = self.document.tag.lower() if value in allowed_request_types[self.params['service']]: self.params["request"] = value else: raise OWSInvalidParameterValue("Request type %s is not...
python
{ "resource": "" }
q260741
Post._get_version
validation
def _get_version(self): """Find requested version in POST request.""" if "version" in self.document.attrib: value = self.document.attrib["version"].lower() if value in allowed_versions[self.params['service']]: self.params["version"] = value else: ...
python
{ "resource": "" }
q260742
localize_datetime
validation
def localize_datetime(dt, tz_name='UTC'): """Provide a timzeone-aware object for a given datetime and timezone name """ tz_aware_dt = dt if dt.tzinfo is None: utc = pytz.timezone('UTC') aware = utc.localize(dt) timezone = pytz.timezone(tz_name) tz_aware_dt = aware.astimez...
python
{ "resource": "" }
q260743
baseurl
validation
def baseurl(url): """ return baseurl of given url """ parsed_url = urlparse.urlparse(url) if not parsed_url.netloc or parsed_url.scheme not in ("http", "https"): raise ValueError('bad url') service_url = "%s://%s%s" % (parsed_url.scheme, parsed_url.netloc, parsed_url.path.strip()) re...
python
{ "resource": "" }
q260744
Service.verify
validation
def verify(self): """Verify ssl service certificate.""" value = self.get('verify', 'true') if isinstance(value, bool): verify = value elif value.lower() == 'true': verify = True elif value.lower() == 'false': verify = False else: ...
python
{ "resource": "" }
q260745
get_egg_info
validation
def get_egg_info(cfg, verbose=False): """Call 'setup egg_info' and return the parsed meta-data.""" result = Bunch() setup_py = cfg.rootjoin('setup.py') if not os.path.exists(setup_py): return result egg_info = shell.capture("python {} egg_info".format(setup_py), echo=True if verbose else No...
python
{ "resource": "" }
q260746
bump
validation
def bump(ctx, verbose=False, pypi=False): """Bump a development version.""" cfg = config.load() scm = scm_provider(cfg.project_root, commit=False, ctx=ctx) # Check for uncommitted changes if not scm.workdir_is_clean(): notify.warning("You have uncommitted changes, will create a time-stamped...
python
{ "resource": "" }
q260747
dist
validation
def dist(ctx, devpi=False, egg=False, wheel=False, auto=True): """Distribute the project.""" config.load() cmd = ["python", "setup.py", "sdist"] # Automatically create wheels if possible if auto: egg = sys.version_info.major == 2 try: import wheel as _ wheel ...
python
{ "resource": "" }
q260748
prep
validation
def prep(ctx, commit=True): """Prepare for a release.""" cfg = config.load() scm = scm_provider(cfg.project_root, commit=commit, ctx=ctx) # Check for uncommitted changes if not scm.workdir_is_clean(): notify.failure("You have uncommitted changes, please commit or stash them!") # TODO C...
python
{ "resource": "" }
q260749
pylint
validation
def pylint(ctx, skip_tests=False, skip_root=False, reports=False): """Perform source code checks via pylint.""" cfg = config.load() add_dir2pypath(cfg.project_root) if not os.path.exists(cfg.testjoin('__init__.py')): add_dir2pypath(cfg.testjoin()) namelist = set() for package in cfg.pro...
python
{ "resource": "" }
q260750
GitProvider.workdir_is_clean
validation
def workdir_is_clean(self, quiet=False): """ Check for uncommitted changes, return `True` if everything is clean. Inspired by http://stackoverflow.com/questions/3878624/. """ # Update the index self.run('git update-index -q --ignore-submodules --refresh', **RUN_KWARGS) ...
python
{ "resource": "" }
q260751
description
validation
def description(_dummy_ctx, markdown=False): """Dump project metadata for Jenkins Description Setter Plugin.""" cfg = config.load() markup = 'md' if markdown else 'html' description_file = cfg.rootjoin("build/project.{}".format(markup)) notify.banner("Creating {} file for Jenkins...".format(descript...
python
{ "resource": "" }
q260752
capture
validation
def capture(cmd, **kw): """Run a command and return its stripped captured output.""" kw = kw.copy() kw['hide'] = 'out' if not kw.get('echo', False): kw['echo'] = False ignore_failures = kw.pop('ignore_failures', False) try: return invoke_run(cmd, **kw).stdout.strip() except e...
python
{ "resource": "" }
q260753
run
validation
def run(cmd, **kw): """Run a command and flush its output.""" kw = kw.copy() kw.setdefault('warn', False) # make extra sure errors don't get silenced report_error = kw.pop('report_error', True) runner = kw.pop('runner', invoke_run) try: return runner(cmd, **kw) except exceptions.F...
python
{ "resource": "" }
q260754
auto_detect
validation
def auto_detect(workdir): """ Return string signifying the SCM used in the given directory. Currently, 'git' is supported. Anything else returns 'unknown'. """ # Any additions here also need a change to `SCM_PROVIDERS`! if os.path.isdir(os.path.join(workdir, '.git')) and os.path.isfile(os.path....
python
{ "resource": "" }
q260755
provider
validation
def provider(workdir, commit=True, **kwargs): """Factory for the correct SCM provider in `workdir`.""" return SCM_PROVIDER[auto_detect(workdir)](workdir, commit=commit, **kwargs)
python
{ "resource": "" }
q260756
fail
validation
def fail(message, exitcode=1): """Exit with error code and message.""" sys.stderr.write('ERROR: {}\n'.format(message)) sys.stderr.flush() sys.exit(exitcode)
python
{ "resource": "" }
q260757
get_pypi_auth
validation
def get_pypi_auth(configfile='~/.pypirc'): """Read auth from pip config.""" pypi_cfg = ConfigParser() if pypi_cfg.read(os.path.expanduser(configfile)): try: user = pypi_cfg.get('pypi', 'username') pwd = pypi_cfg.get('pypi', 'password') return user, pwd exc...
python
{ "resource": "" }
q260758
confluence
validation
def confluence(ctx, no_publish=False, clean=False, opts=''): """Build Sphinx docs and publish to Confluence.""" cfg = config.load() if clean: ctx.run("invoke clean --docs") cmd = ['sphinx-build', '-b', 'confluence'] cmd.extend(['-E', '-a']) # force a full rebuild if opts: cmd....
python
{ "resource": "" }
q260759
DocsUploader._zipped
validation
def _zipped(self, docs_base): """ Provide a zipped stream of the docs tree.""" with pushd(docs_base): with tempfile.NamedTemporaryFile(prefix='pythonhosted-', delete=False) as ziphandle: pass zip_name = shutil.make_archive(ziphandle.name, 'zip') notify.in...
python
{ "resource": "" }
q260760
DocsUploader._to_pypi
validation
def _to_pypi(self, docs_base, release): """Upload to PyPI.""" url = None with self._zipped(docs_base) as handle: reply = requests.post(self.params['url'], auth=get_pypi_auth(), allow_redirects=False, files=dict(content=(self.cfg.project.name + '.zip'...
python
{ "resource": "" }
q260761
DocsUploader._to_webdav
validation
def _to_webdav(self, docs_base, release): """Upload to WebDAV store.""" try: git_path = subprocess.check_output('git remote get-url origin 2>/dev/null', shell=True) except subprocess.CalledProcessError: git_path = '' else: git_path = git_path.decode('a...
python
{ "resource": "" }
q260762
DocsUploader.upload
validation
def upload(self, docs_base, release): """Upload docs in ``docs_base`` to the target of this uploader.""" return getattr(self, '_to_' + self.target)(docs_base, release)
python
{ "resource": "" }
q260763
search_file_upwards
validation
def search_file_upwards(name, base=None): """ Search for a file named `name` from cwd or given directory to root. Return None if nothing's found. """ base = base or os.getcwd() while base != os.path.dirname(base): if os.path.exists(os.path.join(base, name)): return base ...
python
{ "resource": "" }
q260764
pushd
validation
def pushd(path): """ A context that enters a given directory and restores the old state on exit. The original directory is returned as the context variable. """ saved = os.getcwd() os.chdir(path) try: yield saved finally: os.chdir(saved)
python
{ "resource": "" }
q260765
url_as_file
validation
def url_as_file(url, ext=None): """ Context manager that GETs a given `url` and provides it as a local file. The file is in a closed state upon entering the context, and removed when leaving it, if still there. To give the file name a specific extension, use `ext`; the exte...
python
{ "resource": "" }
q260766
ProviderBase.run
validation
def run(self, cmd, *args, **kwargs): """Run a command.""" runner = self.ctx.run if self.ctx else None return run(cmd, runner=runner, *args, **kwargs)
python
{ "resource": "" }
q260767
ProviderBase.run_elective
validation
def run_elective(self, cmd, *args, **kwargs): """Run a command, or just echo it, depending on `commit`.""" if self._commit: return self.run(cmd, *args, **kwargs) else: notify.warning("WOULD RUN: {}".format(cmd)) kwargs = kwargs.copy() kwargs['echo'...
python
{ "resource": "" }
q260768
info
validation
def info(msg): """Emit a normal message.""" _flush() sys.stdout.write(msg + '\n') sys.stdout.flush()
python
{ "resource": "" }
q260769
warning
validation
def warning(msg): """Emit a warning message.""" _flush() sys.stderr.write("\033[1;7;33;40mWARNING: {}\033[0m\n".format(msg)) sys.stderr.flush()
python
{ "resource": "" }
q260770
error
validation
def error(msg): """Emit an error message to stderr.""" _flush() sys.stderr.write("\033[1;37;41mERROR: {}\033[0m\n".format(msg)) sys.stderr.flush()
python
{ "resource": "" }
q260771
get_devpi_url
validation
def get_devpi_url(ctx): """Get currently used 'devpi' base URL.""" cmd = 'devpi use --urls' lines = ctx.run(cmd, hide='out', echo=False).stdout.splitlines() for line in lines: try: line, base_url = line.split(':', 1) except ValueError: notify.warning('Ignoring "{}...
python
{ "resource": "" }
q260772
get_project_root
validation
def get_project_root(): """ Determine location of `tasks.py`.""" try: tasks_py = sys.modules['tasks'] except KeyError: return None else: return os.path.abspath(os.path.dirname(tasks_py.__file__))
python
{ "resource": "" }
q260773
load
validation
def load(): """ Load and return configuration as a ``Bunch``. Values are based on ``DEFAULTS``, and metadata from ``setup.py``. """ cfg = Bunch(DEFAULTS) # TODO: override with contents of [rituals] section in setup.cfg cfg.project_root = get_project_root() if not cfg.project_root: ...
python
{ "resource": "" }
q260774
glob2re
validation
def glob2re(part): """Convert a path part to regex syntax.""" return "[^/]*".join( re.escape(bit).replace(r'\[\^', '[^').replace(r'\[', '[').replace(r'\]', ']') for bit in part.split("*") )
python
{ "resource": "" }
q260775
parse_glob
validation
def parse_glob(pattern): """Generate parts of regex transformed from glob pattern.""" if not pattern: return bits = pattern.split("/") dirs, filename = bits[:-1], bits[-1] for dirname in dirs: if dirname == "**": yield "(|.+/)" else: yield glob2re(d...
python
{ "resource": "" }
q260776
compile_glob
validation
def compile_glob(spec): """Convert the given glob `spec` to a compiled regex.""" parsed = "".join(parse_glob(spec)) regex = "^{0}$".format(parsed) return re.compile(regex)
python
{ "resource": "" }
q260777
FileSet.included
validation
def included(self, path, is_dir=False): """Check patterns in order, last match that includes or excludes `path` wins. Return `None` on undecided.""" inclusive = None for pattern in self.patterns: if pattern.is_dir == is_dir and pattern.matches(path): inclusive = patte...
python
{ "resource": "" }
q260778
FileSet.walk
validation
def walk(self, **kwargs): """ Like `os.walk` and taking the same keyword arguments, but generating paths relative to the root. Starts in the fileset's root and filters based on its patterns. If ``with_root=True`` is passed in, the generated paths include the root...
python
{ "resource": "" }
q260779
build
validation
def build(ctx, dput='', opts=''): """Build a DEB package.""" # Get package metadata with io.open('debian/changelog', encoding='utf-8') as changes: metadata = re.match(r'^([^ ]+) \(([^)]+)\) ([^;]+); urgency=(.+)$', changes.readline().rstrip()) if not metadata: notify.failure('Bad...
python
{ "resource": "" }
q260780
clean
validation
def clean(_dummy_ctx, docs=False, backups=False, bytecode=False, dist=False, # pylint: disable=redefined-outer-name all=False, venv=False, tox=False, extra=''): # pylint: disable=redefined-builtin """Perform house-keeping.""" cfg = config.load() notify.banner("Cleaning up project files") # Add ...
python
{ "resource": "" }
q260781
build
validation
def build(ctx, docs=False): """Build the project.""" cfg = config.load() ctx.run("python setup.py build") if docs: for doc_path in ('docs', 'doc'): if os.path.exists(cfg.rootjoin(doc_path, 'conf.py')): break else: doc_path = None if doc_p...
python
{ "resource": "" }
q260782
freeze
validation
def freeze(ctx, local=False): """Freeze currently installed requirements.""" cmd = 'pip --disable-pip-version-check freeze{}'.format(' --local' if local else '') frozen = ctx.run(cmd, hide='out').stdout.replace('\x1b', '#') with io.open('frozen-requirements.txt', 'w', encoding='ascii') as out: o...
python
{ "resource": "" }
q260783
isodate
validation
def isodate(datestamp=None, microseconds=False): """Return current or given time formatted according to ISO-8601.""" datestamp = datestamp or datetime.datetime.now() if not microseconds: usecs = datetime.timedelta(microseconds=datestamp.microsecond) datestamp = datestamp - usecs return d...
python
{ "resource": "" }
q260784
_get_registered_executable
validation
def _get_registered_executable(exe_name): """Windows allow application paths to be registered in the registry.""" registered = None if sys.platform.startswith('win'): if os.path.splitext(exe_name)[1].lower() != '.exe': exe_name += '.exe' import _winreg # pylint: disable=import-er...
python
{ "resource": "" }
q260785
whichgen
validation
def whichgen(command, path=None, verbose=0, exts=None): # pylint: disable=too-many-branches, too-many-statements """Return a generator of full paths to the given command. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to ...
python
{ "resource": "" }
q260786
which
validation
def which(command, path=None, verbose=0, exts=None): """Return the full path to the first match of the given command on the path. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to use the PATH environment variable. ...
python
{ "resource": "" }
q260787
SymmetricKeyRatchet.step
validation
def step(self, key, chain): """ Perform a rachted step, replacing one of the internally managed chains with a new one. :param key: A bytes-like object encoding the key to initialize the replacement chain with. :param chain: The chain to replace. This parameter must b...
python
{ "resource": "" }
q260788
DoubleRatchet.decryptMessage
validation
def decryptMessage(self, ciphertext, header, ad = None): """ Decrypt a message using this double ratchet session. :param ciphertext: A bytes-like object encoding the message to decrypt. :param header: An instance of the Header class. This should have been sent together with ...
python
{ "resource": "" }
q260789
DoubleRatchet.encryptMessage
validation
def encryptMessage(self, message, ad = None): """ Encrypt a message using this double ratchet session. :param message: A bytes-like object encoding the message to encrypt. :param ad: A bytes-like object encoding the associated data to use for message authentication. Pass Non...
python
{ "resource": "" }
q260790
DHRatchet.step
validation
def step(self, other_pub): """ Perform a rachted step, calculating a new shared secret from the public key and deriving new chain keys from this secret. New Diffie-Hellman calculations are only performed if the public key is different from the previous one. :param other...
python
{ "resource": "" }
q260791
KDFChain.next
validation
def next(self, data): """ Derive a new set of internal and output data from given input data and the data stored internally. Use the key derivation function to derive new data. The kdf gets supplied with the current key and the data passed to this method. :param data: A...
python
{ "resource": "" }
q260792
Mesh.connect_to
validation
def connect_to(self, other_mesh): """Create a connection to an other mesh. .. warning:: Both meshes need to be disconnected and one needs to be a consumed and the other a produced mesh. You can check if a connection is possible using :meth:`can_connect_to`. .. seealso:: :me...
python
{ "resource": "" }
q260793
Mesh.can_connect_to
validation
def can_connect_to(self, other): """Whether a connection can be established between those two meshes.""" assert other.is_mesh() disconnected = not other.is_connected() and not self.is_connected() types_differ = self._is_consumed_mesh() != other._is_consumed_mesh() return disconne...
python
{ "resource": "" }
q260794
new_knitting_pattern_set_loader
validation
def new_knitting_pattern_set_loader(specification=DefaultSpecification()): """Create a loader for a knitting pattern set. :param specification: a :class:`specification <knittingpattern.ParsingSpecification.ParsingSpecification>` for the knitting pattern set, default :class:`DefaultSpecificati...
python
{ "resource": "" }
q260795
walk
validation
def walk(knitting_pattern): """Walk the knitting pattern in a right-to-left fashion. :return: an iterable to walk the rows :rtype: list :param knittingpattern.KnittingPattern.KnittingPattern knitting_pattern: a knitting pattern to take the rows from """ rows_before = {} # key consumes fr...
python
{ "resource": "" }
q260796
ContentDumper.file
validation
def file(self, file=None): """Saves the dump in a file-like object in text mode. :param file: :obj:`None` or a file-like object. :return: a file-like object If :paramref:`file` is :obj:`None`, a new :class:`io.StringIO` is returned. If :paramref:`file` is not :obj:`None...
python
{ "resource": "" }
q260797
ContentDumper._file
validation
def _file(self, file): """Dump the content to a `file`. """ if not self.__text_is_expected: file = BytesWrapper(file, self.__encoding) self.__dump_to_file(file)
python
{ "resource": "" }
q260798
ContentDumper._binary_file
validation
def _binary_file(self, file): """Dump the ocntent into the `file` in binary mode. """ if self.__text_is_expected: file = TextWrapper(file, self.__encoding) self.__dump_to_file(file)
python
{ "resource": "" }
q260799
ContentDumper._path
validation
def _path(self, path): """Saves the dump in a file named `path`.""" mode, encoding = self._mode_and_encoding_for_open() with open(path, mode, encoding=encoding) as file: self.__dump_to_file(file)
python
{ "resource": "" }