_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 if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- y : array, shape (n_samples,) """ # Check is fit had been called check_is_fitted(self, ['tree']) # Check data X = check_array(X) return self.tree.query(X)[0].flatten()
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. y : array-like, shape = [n_samples] or [n_samples, n_outputs] The target values (real numbers in regression). Returns ------- self : object """ # Check that X have correct shape X = check_array(X) self.inverse_influence_matrix = self.__make_inverse_matrix(X) if self.threshold == 'auto': self.threshold_value = 3 * (1 + X.shape[1]) / X.shape[0] elif self.threshold == 'cv': if y is None: raise ValueError("Y must be specified to find the optimal threshold.") y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None) self.threshold_value = 0 score = 0 Y_pred, Y_true, AD = [], [], [] cv = KFold(n_splits=5, random_state=1, shuffle=True) for train_index, test_index in cv.split(X): x_train = safe_indexing(X, train_index) x_test = safe_indexing(X, test_index) y_train = safe_indexing(y, train_index) y_test = safe_indexing(y, test_index) if self.reg_model is None: reg_model = RandomForestRegressor(n_estimators=500, random_state=1).fit(x_train, y_train) else: reg_model = clone(self.reg_model).fit(x_train, y_train) Y_pred.append(reg_model.predict(x_test)) Y_true.append(y_test) ad_model = self.__make_inverse_matrix(x_train) AD.append(self.__find_leverages(x_test, ad_model)) AD_ = unique(hstack(AD)) for z in AD_: AD_new = hstack(AD) <= z if self.score == 'ba_ad': val = balanced_accuracy_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new) elif self.score == 'rmse_ad': val = rmse_score_with_ad(Y_true=hstack(Y_true), Y_pred=hstack(Y_pred), AD=AD_new) if val >= score: score = val self.threshold_value = z else: self.threshold_value = self.threshold return self
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 sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- leverages: array of shape = [n_samples] The objects distances to center of the training set. """ # Check is fit had been called check_is_fitted(self, ['inverse_influence_matrix']) # Check that X have correct shape X = check_array(X) return self.__find_leverages(X, self.inverse_influence_matrix)
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 to a sparse ``csr_matrix``. Returns ------- ad : array of shape = [n_samples] Array contains True (reaction in AD) and False (reaction residing outside AD). """ # Check is fit had been called check_is_fitted(self, ['inverse_influence_matrix']) # Check that X have correct shape X = check_array(X) return self.__find_leverages(X, self.inverse_influence_matrix) <= self.threshold_value
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. Returns ------- self : object """ # Check that X have correct shape X = check_array(X) self._x_min = X.min(axis=0) # axis=0 will find the minimum values ​​by columns (for each feature) self._x_max = X.max(axis=0) # axis=0 will find the minimum values ​​by columns (for each feature) return self
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) return self
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 fitted') elif not self.__head_dict: raise NotFittedError(f'{self.__class__.__name__} instance is not fitted yet') else: if self.remove_rare_ratio: self.__clean_head(*self.__head_rare) self.__prepare_header() self.__head_rare = None self.__head_generate = False
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.__prepare(x) return self
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) self._train_signatures = {self.__get_signature(x) for x in X} return self
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 f in opts.concrete_fields: if f.attname in self.morango_fields_not_to_serialize: continue if f.attname in self._morango_internal_fields_not_to_serialize: continue # case if model is morango mptt if f.attname in getattr(self, '_internal_mptt_fields_not_to_serialize', '_internal_fields_not_to_serialize'): continue if hasattr(f, 'value_from_object_json_compatible'): data[f.attname] = f.value_from_object_json_compatible(self) else: data[f.attname] = f.value_from_object(self) return data
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 default if isinstance(self.default, uuid.UUID): return self.default.hex return self.default return None
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 must define either a 'uuid_input_fields' attribute (with a tuple of field names) or override the 'calculate_uuid' method, on models that inherit from UUIDModelMixin. If you want a fully random UUID, you can set 'uuid_input_fields' to the string 'RANDOM'.""") # if the UUID has been set to be random, return a random UUID if self.uuid_input_fields == "RANDOM": return uuid.uuid4().hex # if we got this far, uuid_input_fields should be a tuple assert isinstance(self.uuid_input_fields, tuple), "'uuid_input_fields' must either be a tuple or the string 'RANDOM'" # calculate the input to the UUID function hashable_input_vals = [] for field in self.uuid_input_fields: new_value = getattr(self, field) if new_value: hashable_input_vals.append(str(new_value)) hashable_input = ":".join(hashable_input_vals) # if all the values were falsey, just return a random UUID, to avoid collisions if not hashable_input: return uuid.uuid4().hex # compute the UUID as a function of the input values return sha2_uuid(hashable_input)
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_deleted_models()
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: return APIWrapper._parse_resp(r, response_format) except (ValueError, SyntaxError) as ex: log.error(ex) r.parsed = None return r if isinstance(error, requests.HTTPError): if resp.status_code == 400: # It means that request parameters were rejected by the server, # so we need to enrich standard error message # with 'ValidationErrors' # from the response resp = safe_parse(resp) if resp.parsed is not None: parsed_resp = resp.parsed messages = [] if response_format == 'xml' and\ parsed_resp.find('./ValidationErrors') is not None: messages = [e.find('./Message').text for e in parsed_resp.findall('./ValidationErrors/ValidationErrorDto')] elif response_format == 'json' and 'ValidationErrors' in parsed_resp: messages = [e['Message'] for e in parsed_resp['ValidationErrors']] error = requests.HTTPError( '%s: %s' % (error, '\n\t'.join(messages)), response=resp) elif resp.status_code == 429: error = requests.HTTPError('%sToo many requests in the last minute.' % error, response=resp) if STRICT == mode: raise error elif GRACEFUL == mode: if isinstance(error, EmptyResponse): # Empty response is returned by the API occasionally, # in this case it makes sense to ignore it and retry. log.warning(error) resp.parsed = None return resp elif isinstance(error, requests.HTTPError): # Ignoring 'Too many requests' error, # since subsequent retries will come after a delay. if resp.status_code == 429: # Too many requests log.warning(error) return safe_parse(resp) else: raise error else: raise error else: # ignore everything, just log it and return whatever response we # have log.error(error) return safe_parse(resp)
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, 'COMPLETE'] status = None if self.response_format == 'xml': status = poll_resp.parsed.find('./Status').text elif self.response_format == 'json': status = poll_resp.parsed.get( 'Status', poll_resp.parsed.get('status')) if status is None: raise RuntimeError('Unable to get poll response status.') return status in success_list
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 (instance_id, counter) pairs :return ``dict`` of fsics to be used in queueing the correct records to the buffer """ return {instance: fsic2.get(instance, 0) for instance, counter in six.iteritems(fsic1) if fsic2.get(instance, 0) < counter}
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] excluded_list = [] # iterate through classes which are in foreign key dependency order for model_name, klass_model in six.iteritems(syncable_dict): # handle cases where a class has a single FK reference to itself self_ref_fk = _self_referential_fk(klass_model) query = Q(model_name=klass_model.morango_model_name) for klass in klass_model.morango_model_dependencies: query |= Q(model_name=klass.morango_model_name) if self_ref_fk: clean_parents = Store.objects.filter(dirty_bit=False, profile=profile).filter(query).char_ids_list() dirty_children = Store.objects.filter(dirty_bit=True, profile=profile) \ .filter(Q(_self_ref_fk__in=clean_parents) | Q(_self_ref_fk='')).filter(query) # keep iterating until size of dirty_children is 0 while len(dirty_children) > 0: for store_model in dirty_children: try: app_model = store_model._deserialize_store_model(fk_cache) if app_model: with mute_signals(signals.pre_save, signals.post_save): app_model.save(update_dirty_bit_to=False) # we update a store model after we have deserialized it to be able to mark it as a clean parent store_model.dirty_bit = False store_model.save(update_fields=['dirty_bit']) except exceptions.ValidationError: # if the app model did not validate, we leave the store dirty bit set excluded_list.append(store_model.id) # update lists with new clean parents and dirty children clean_parents = Store.objects.filter(dirty_bit=False, profile=profile).filter(query).char_ids_list() dirty_children = Store.objects.filter(dirty_bit=True, profile=profile, _self_ref_fk__in=clean_parents).filter(query) else: # array for holding db values from the fields of each model for this class db_values = [] fields = klass_model._meta.fields for store_model in Store.objects.filter(model_name=model_name, profile=profile, dirty_bit=True): try: app_model = store_model._deserialize_store_model(fk_cache) # if the model was not deleted add its field values to the list if app_model: for f in fields: value = getattr(app_model, f.attname) db_value = f.get_db_prep_value(value, connection) db_values.append(db_value) except exceptions.ValidationError: # if the app model did not validate, we leave the store dirty bit set excluded_list.append(store_model.id) if db_values: # number of rows to update num_of_rows = len(db_values) // len(fields) # create '%s' placeholders for a single row placeholder_tuple = tuple(['%s' for _ in range(len(fields))]) # create list of the '%s' tuple placeholders based on number of rows to update placeholder_list = [str(placeholder_tuple) for _ in range(num_of_rows)] with connection.cursor() as cursor: DBBackend._bulk_insert_into_app_models(cursor, klass_model._meta.db_table, fields, db_values, placeholder_list) # clear dirty bit for all store models for this profile except for models that did not validate Store.objects.exclude(id__in=excluded_list).filter(profile=profile, dirty_bit=True).update(dirty_bit=False)
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, transfersession.id) current_id = InstanceIDModel.get_current_instance_and_increment_counter() DBBackend._dequeuing_merge_conflict_buffer(cursor, current_id, transfersession.id) DBBackend._dequeuing_merge_conflict_rmcb(cursor, transfersession.id) DBBackend._dequeuing_update_rmcs_last_saved_by(cursor, current_id, transfersession.id) DBBackend._dequeuing_delete_mc_rmcb(cursor, transfersession.id) DBBackend._dequeuing_delete_mc_buffer(cursor, transfersession.id) DBBackend._dequeuing_insert_remaining_buffer(cursor, transfersession.id) DBBackend._dequeuing_insert_remaining_rmcb(cursor, transfersession.id) DBBackend._dequeuing_delete_remaining_rmcb(cursor, transfersession.id) DBBackend._dequeuing_delete_remaining_buffer(cursor, transfersession.id) if getattr(settings, 'MORANGO_DESERIALIZE_AFTER_DEQUEUING', True): _deserialize_from_store(transfersession.sync_session.profile)
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 value to chunk our SQL bulk insert statements when deserializing from the store to the app layer. """ if os.path.isfile(SQLITE_VARIABLE_FILE_CACHE): return conn = sqlite3.connect(':memory:') low = 1 high = 1000 # hard limit for SQLITE_MAX_VARIABLE_NUMBER <http://www.sqlite.org/limits.html> conn.execute('CREATE TABLE T1 (id C1)') while low < high - 1: guess = (low + high) // 2 try: statement = 'select * from T1 where id in (%s)' % ','.join(['?' for _ in range(guess)]) values = [i for i in range(guess)] conn.execute(statement, values) except sqlite3.DatabaseError as ex: if 'too many SQL variables' in str(ex): high = guess else: raise else: low = guess conn.close() with open(SQLITE_VARIABLE_FILE_CACHE, 'w') as file: file.write(str(low))
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': password } if "=" not in userargs: # if it doesn't seem to be in querystring format, just use it as the username credentials[get_user_model().USERNAME_FIELD] = userargs else: # parse out the user args from querystring format into the credentials dict for arg in userargs.split("&"): key, val = arg.split("=") credentials[key] = val # authenticate the user via Django's auth backends user = authenticate(**credentials) if user is None: raise exceptions.AuthenticationFailed('Invalid credentials.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return (user, None)
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_fk.append(class_model) return False
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 SyncableModelManager from morango.query import SyncableModelQuerySet model_list = [] for model_class in django.apps.apps.get_models(): # several validation checks to assert models will be syncing correctly if issubclass(model_class, SyncableModel): name = model_class.__name__ if _multiple_self_ref_fk_check(model_class): raise InvalidMorangoModelConfiguration("Syncing models with more than 1 self referential ForeignKey is not supported.") try: from mptt import models from morango.utils.morango_mptt import MorangoMPTTModel, MorangoMPTTTreeManager, MorangoTreeQuerySet # mptt syncable model checks if issubclass(model_class, models.MPTTModel): if not issubclass(model_class, MorangoMPTTModel): raise InvalidMorangoModelConfiguration("{} that inherits from MPTTModel, should instead inherit from MorangoMPTTModel.".format(name)) if not isinstance(model_class.objects, MorangoMPTTTreeManager): raise InvalidMPTTManager("Manager for {} must inherit from MorangoMPTTTreeManager.".format(name)) if not isinstance(model_class.objects.none(), MorangoTreeQuerySet): raise InvalidMPTTQuerySet("Queryset for {} model must inherit from MorangoTreeQuerySet.".format(name)) except ImportError: pass # syncable model checks if not isinstance(model_class.objects, SyncableModelManager): raise InvalidSyncableManager("Manager for {} must inherit from SyncableModelManager.".format(name)) if not isinstance(model_class.objects.none(), SyncableModelQuerySet): raise InvalidSyncableQueryset("Queryset for {} model must inherit from SyncableModelQuerySet.".format(name)) if model_class._meta.many_to_many: raise UnsupportedFieldType("{} model with a ManyToManyField is not supported in morango.") if not hasattr(model_class, 'morango_model_name'): raise InvalidMorangoModelConfiguration("{} model must define a morango_model_name attribute".format(name)) if not hasattr(model_class, 'morango_profile'): raise InvalidMorangoModelConfiguration("{} model must define a morango_profile attribute".format(name)) # create empty list to hold model classes for profile if not yet created profile = model_class.morango_profile _profile_models[profile] = _profile_models.get(profile, []) # don't sync models where morango_model_name is None if model_class.morango_model_name is not None: _insert_model_into_profile_dict(model_class, profile) # for each profile, create a dict mapping from morango model names to model class for profile, model_list in iteritems(_profile_models): syncable_models_dict = OrderedDict() for model_class in model_list: syncable_models_dict[model_class.morango_model_name] = model_class _profile_models[profile] = syncable_models_dict
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 for request :param lookup: the pk value for the specific object we are querying :param data: dict that will be form-encoded in request :param params: dict to be sent as part of URL's query string :param userargs: Authorization credentials :param password: :return: ``Response`` object from request """ # convert user arguments into query str for passing to auth layer if isinstance(userargs, dict): userargs = "&".join(["{}={}".format(key, val) for (key, val) in iteritems(userargs)]) # build up url and send request if lookup: lookup = lookup + '/' url = urljoin(urljoin(self.base_url, endpoint), lookup) auth = (userargs, password) if userargs else None resp = requests.request(method, url, json=data, params=params, auth=auth) resp.raise_for_status() return resp
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_at=expires_at(hours=valid_in_hours), data=data) return token
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: name = namesgenerator.get_random_name(retry=True) # check if service is already registered if self.collection.count_documents({'name': name}) > 0: if overwrite: self.collection.delete_one({'name': name}) else: raise Exception("service name already registered.") self.collection.insert_one(Service( name=name, url=baseurl(service.url), type=service.type, purl=service.purl, public=service.public, auth=service.auth, verify=service.verify)) return self.fetch_by_name(name=name)
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' if request.matchdict.get('service_name'): url += '/' + request.matchdict.get('service_name') if request.matchdict.get('access_token'): url += '/' + request.matchdict.get('service_name') url += '?' + urlparse.urlencode(request.params) LOGGER.debug("delegate to owsproxy: %s", url) # forward request to target (without Host Header) # h = dict(request.headers) # h.pop("Host", h) resp = requests.request(method=request.method.upper(), url=url, data=request.body, headers=request.headers, verify=False) return Response(resp.content, status=resp.status_code, headers=resp.headers)
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) return handler(request) except OWSException as err: logger.exception("security check failed.") return err except Exception as err: logger.exception("unknown error") return OWSNoApplicableCode("{}".format(err)) return ows_security_tween
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 = config.registry.settings if asbool(settings.get('twitcher.rpcinterface', True)): LOGGER.debug('Twitcher XML-RPC Interface enabled.') # include twitcher config config.include('twitcher.config') # using basic auth config.include('twitcher.basicauth') # pyramid xml-rpc # http://docs.pylonsproject.org/projects/pyramid-rpc/en/latest/xmlrpc.html config.include('pyramid_rpc.xmlrpc') config.include('twitcher.db') config.add_xmlrpc_endpoint('api', '/RPC2') # register xmlrpc methods config.add_xmlrpc_method(RPCInterface, attr='generate_token', endpoint='api', method='generate_token') config.add_xmlrpc_method(RPCInterface, attr='revoke_token', endpoint='api', method='revoke_token') config.add_xmlrpc_method(RPCInterface, attr='revoke_all_tokens', endpoint='api', method='revoke_all_tokens') config.add_xmlrpc_method(RPCInterface, attr='register_service', endpoint='api', method='register_service') config.add_xmlrpc_method(RPCInterface, attr='unregister_service', endpoint='api', method='unregister_service') config.add_xmlrpc_method(RPCInterface, attr='get_service_by_name', endpoint='api', method='get_service_by_name') config.add_xmlrpc_method(RPCInterface, attr='get_service_by_url', endpoint='api', method='get_service_by_url') config.add_xmlrpc_method(RPCInterface, attr='clear_services', endpoint='api', method='clear_services') config.add_xmlrpc_method(RPCInterface, attr='list_services', endpoint='api', method='list_services')
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 = namesgenerator.get_random_name(retry=True) # check if service is already registered if name in self.name_index: if overwrite: self._delete(name=name) else: raise Exception("service name already registered.") self._insert(Service( name=name, url=baseurl(service.url), type=service.type, purl=service.purl, public=service.public, auth=service.auth, verify=service.verify)) return self.fetch_by_name(name=name)
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 key_pair = crypto.PKey() key_pair.generate_key(crypto.TYPE_RSA, 2048) private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key_pair).decode("utf-8") # Generate a certificate request using that key-pair cert_request = crypto.X509Req() # Create public key object cert_request.set_pubkey(key_pair) # Add the public key to the request cert_request.sign(key_pair, 'md5') der_cert_req = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, cert_request) encoded_cert_req = base64.b64encode(der_cert_req) # Build the OAuth session object token = {'access_token': access_token, 'token_type': 'Bearer'} client = OAuth2Session(token=token) response = client.post( self.certificate_url, data={'certificate_request': encoded_cert_req}, verify=False, timeout=timeout, ) if response.ok: content = "{} {}".format(response.text, private_key) with open(self.esgf_credentials, 'w') as fh: fh.write(content) logger.debug('Fetched certificate successfully.') else: msg = "Could not get certificate: {} {}".format(response.status_code, response.reason) raise Exception(msg) return True
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 allowed_values: self.params[param] = value else: raise OWSInvalidParameterValue("%s %s is not supported" % (param, value), value=param) elif optional: self.params[param] = None else: raise OWSMissingParameterValue('Parameter "%s" is missing' % param, value=param) return self.params[param]
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": raise OWSMissingParameterValue('Parameter "version" is missing', value="version") else: return version
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: raise OWSInvalidParameterValue("Service %s is not supported" % value, value="service") else: raise OWSMissingParameterValue('Parameter "service" is missing', value="service") return self.params["service"]
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 supported" % value, value="request") return self.params["request"]
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: raise OWSInvalidParameterValue("Version %s is not supported" % value, value="version") elif self._get_request_type() == "getcapabilities": self.params["version"] = None else: raise OWSMissingParameterValue('Parameter "version" is missing', value="version") return self.params["version"]
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.astimezone(timezone) else: logger.warn('tzinfo already set') return tz_aware_dt
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()) return service_url
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: verify = value return verify
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 None) for info_line in egg_info.splitlines(): if info_line.endswith('PKG-INFO'): pkg_info_file = info_line.split(None, 1)[1] result['__file__'] = pkg_info_file with io.open(pkg_info_file, encoding='utf-8') as handle: lastkey = None for line in handle: if line.lstrip() != line: assert lastkey, "Bad continuation in PKG-INFO file '{}': {}".format(pkg_info_file, line) result[lastkey] += '\n' + line else: lastkey, value = line.split(':', 1) lastkey = lastkey.strip().lower().replace('-', '_') value = value.strip() if lastkey in result: try: result[lastkey].append(value) except AttributeError: result[lastkey] = [result[lastkey], value] else: result[lastkey] = value for multikey in PKG_INFO_MULTIKEYS: if not isinstance(result.get(multikey, []), list): result[multikey] = [result[multikey]] return result
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 version!") pep440 = scm.pep440_dev_version(verbose=verbose, non_local=pypi) # Rewrite 'setup.cfg' TODO: refactor to helper, see also release-prep # with util.rewrite_file(cfg.rootjoin('setup.cfg')) as lines: # ... setup_cfg = cfg.rootjoin('setup.cfg') if not pep440: notify.info("Working directory contains a release version!") elif os.path.exists(setup_cfg): with io.open(setup_cfg, encoding='utf-8') as handle: data = handle.readlines() changed = False for i, line in enumerate(data): if re.match(r"#? *tag_build *= *.*", line): verb, _ = data[i].split('=', 1) data[i] = '{}= {}\n'.format(verb, pep440) changed = True if changed: notify.info("Rewriting 'setup.cfg'...") with io.open(setup_cfg, 'w', encoding='utf-8') as handle: handle.write(''.join(data)) else: notify.warning("No 'tag_build' setting found in 'setup.cfg'!") else: notify.warning("Cannot rewrite 'setup.cfg', none found!") if os.path.exists(setup_cfg): # Update metadata and print version egg_info = shell.capture("python setup.py egg_info", echo=True if verbose else None) for line in egg_info.splitlines(): if line.endswith('PKG-INFO'): pkg_info_file = line.split(None, 1)[1] with io.open(pkg_info_file, encoding='utf-8') as handle: notify.info('\n'.join(i for i in handle.readlines() if i.startswith('Version:')).strip()) ctx.run("python setup.py -q develop", echo=True if verbose else None)
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 = True except ImportError: wheel = False if egg: cmd.append("bdist_egg") if wheel: cmd.append("bdist_wheel") ctx.run("invoke clean --all build --docs test check") ctx.run(' '.join(cmd)) if devpi: ctx.run("devpi upload dist/*")
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 Check that changelog entry carries the current date # Rewrite 'setup.cfg' setup_cfg = cfg.rootjoin('setup.cfg') if os.path.exists(setup_cfg): with io.open(setup_cfg, encoding='utf-8') as handle: data = handle.readlines() changed = False for i, line in enumerate(data): if any(line.startswith(i) for i in ('tag_build', 'tag_date')): data[i] = '#' + data[i] changed = True if changed and commit: notify.info("Rewriting 'setup.cfg'...") with io.open(setup_cfg, 'w', encoding='utf-8') as handle: handle.write(''.join(data)) scm.add_file('setup.cfg') elif changed: notify.warning("WOULD rewrite 'setup.cfg', but --no-commit was passed") else: notify.warning("Cannot rewrite 'setup.cfg', none found!") # Update metadata and command stubs ctx.run('python setup.py -q develop -U') # Build a clean dist and check version number version = capture('python setup.py --version') ctx.run('invoke clean --all build --docs release.dist') for distfile in os.listdir('dist'): trailer = distfile.split('-' + version)[1] trailer, _ = os.path.splitext(trailer) if trailer and trailer[0] not in '.-': notify.failure("The version found in 'dist' seems to be" " a pre-release one! [{}{}]".format(version, trailer)) # Commit changes and tag the release scm.commit(ctx.rituals.release.commit.message.format(version=version)) scm.tag(ctx.rituals.release.tag.name.format(version=version), ctx.rituals.release.tag.message.format(version=version))
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.project.get('packages', []): if '.' not in package: namelist.add(cfg.srcjoin(package)) for module in cfg.project.get('py_modules', []): namelist.add(module + '.py') if not skip_tests: test_py = antglob.FileSet(cfg.testdir, '**/*.py') test_py = [cfg.testjoin(i) for i in test_py] if test_py: namelist |= set(test_py) if not skip_root: root_py = antglob.FileSet('.', '*.py') if root_py: namelist |= set(root_py) namelist = set([i[len(os.getcwd())+1:] if i.startswith(os.getcwd() + os.sep) else i for i in namelist]) cmd = 'pylint' cmd += ' "{}"'.format('" "'.join(sorted(namelist))) cmd += ' --reports={0}'.format('y' if reports else 'n') for cfgfile in ('.pylintrc', 'pylint.rc', 'pylint.cfg', 'project.d/pylint.cfg'): if os.path.exists(cfgfile): cmd += ' --rcfile={0}'.format(cfgfile) break try: shell.run(cmd, report_error=False, runner=ctx.run) notify.info("OK - No problems found by pylint.") except exceptions.Failure as exc: # Check bit flags within pylint return code if exc.result.return_code & 32: # Usage error (internal error in this code) notify.error("Usage error, bad arguments in {}?!".format(repr(cmd))) raise else: bits = { 1: "fatal", 2: "error", 4: "warning", 8: "refactor", 16: "convention", } notify.warning("Some messages of type {} issued by pylint.".format( ", ".join([text for bit, text in bits.items() if exc.result.return_code & bit]) )) if exc.result.return_code & 3: notify.error("Exiting due to fatal / error message.") raise
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) unchanged = True # Disallow unstaged changes in the working tree try: self.run('git diff-files --quiet --ignore-submodules --', report_error=False, **RUN_KWARGS) except exceptions.Failure: unchanged = False if not quiet: notify.warning('You have unstaged changes!') self.run('git diff-files --name-status -r --ignore-submodules -- >&2', **RUN_KWARGS) # Disallow uncommitted changes in the index try: self.run('git diff-index --cached --quiet HEAD --ignore-submodules --', report_error=False, **RUN_KWARGS) except exceptions.Failure: unchanged = False if not quiet: notify.warning('Your index contains uncommitted changes!') self.run('git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2', **RUN_KWARGS) return unchanged
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(description_file)) long_description = cfg.project.long_description long_description = long_description.replace('\n\n', '</p>\n<p>') long_description = re.sub(r'(\W)``([^`]+)``(\W)', r'\1<tt>\2</tt>\3', long_description) text = DESCRIPTION_TEMPLATES[markup].format( keywords=', '.join(cfg.project.keywords), classifiers='\n'.join(cfg.project.classifiers), classifiers_indented=' ' + '\n '.join(cfg.project.classifiers), packages=', '.join(cfg.project.packages), long_description_html='<p>{}</p>'.format(long_description), ##data='\n'.join(["%s=%r" % i for i in cfg.project.iteritems()]), **cfg) with io.open(description_file, 'w', encoding='utf-8') as handle: handle.write(text)
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 exceptions.Failure as exc: if not ignore_failures: notify.error("Command `{}` failed with RC={}!".format(cmd, exc.result.return_code,)) raise
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.Failure as exc: sys.stdout.flush() sys.stderr.flush() if report_error: notify.error("Command `{}` failed with RC={}!".format(cmd, exc.result.return_code,)) raise finally: sys.stdout.flush() sys.stderr.flush()
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.join(workdir, '.git', 'HEAD')): return 'git' return 'unknown'
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 except ConfigError: notify.warning("No PyPI credentials in '{}'," " will fall back to '~/.netrc'...".format(configfile)) return None
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.append(opts) cmd.extend(['.', ctx.rituals.docs.build + '_cf']) if no_publish: cmd.extend(['-Dconfluence_publish=False']) # Build docs notify.info("Starting Sphinx build...") with pushd(ctx.rituals.docs.sources): ctx.run(' '.join(cmd), pty=True)
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.info("Uploading {:.1f} MiB from '{}' to '{}'..." .format(os.path.getsize(zip_name) / 1024.0, zip_name, self.target)) with io.open(zip_name, 'rb') as zipread: try: yield zipread finally: os.remove(ziphandle.name) os.remove(ziphandle.name + '.zip')
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', handle, 'application/zip')), data={':action': 'doc_upload', 'name': self.cfg.project.name}) if reply.status_code in range(200, 300): notify.info("{status_code} {reason}".format(**vars(reply))) elif reply.status_code == 301: url = reply.headers['location'] else: data = self.cfg.copy() data.update(self.params) data.update(vars(reply)) notify.error("{status_code} {reason} for POST to {url}".format(**data)) return url
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('ascii').strip() git_path = git_path.replace('http://', '').replace('https://', '').replace('ssh://', '') git_path = re.search(r'[^:/]+?[:/](.+)', git_path) git_path = git_path.group(1).replace('.git', '') if git_path else '' url = None with self._zipped(docs_base) as handle: url_ns = dict(name=self.cfg.project.name, version=release, git_path=git_path) reply = requests.put(self.params['url'].format(**url_ns), data=handle.read(), headers={'Accept': 'application/json'}) if reply.status_code in range(200, 300): notify.info("{status_code} {reason}".format(**vars(reply))) try: data = reply.json() except ValueError as exc: notify.warning("Didn't get a JSON response! ({})".format(exc)) else: if 'downloadUri' in data: # Artifactory url = data['downloadUri'] + '!/index.html' elif reply.status_code == 301: url = reply.headers['location'] else: data = self.cfg.copy() data.update(self.params) data.update(vars(reply)) notify.error("{status_code} {reason} for PUT to {url}".format(**data)) if not url: notify.warning("Couldn't get URL from upload response!") return url
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 base = os.path.dirname(base) return None
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 extension can optionally include a separating dot, otherwise it will be added. Parameters: url (str): URL to retrieve. ext (str, optional): Extension for the generated filename. Yields: str: The path to a temporary file with the content of the URL. Raises: requests.RequestException: Base exception of ``requests``, see its docs for more detailed ones. Example: >>> import io, re, json >>> with url_as_file('https://api.github.com/meta', ext='json') as meta: ... meta, json.load(io.open(meta, encoding='ascii'))['hooks'] (u'/tmp/www-api.github.com-Ba5OhD.json', [u'192.30.252.0/22']) """ if ext: ext = '.' + ext.strip('.') # normalize extension url_hint = 'www-{}-'.format(urlparse(url).hostname or 'any') if url.startswith('file://'): url = os.path.abspath(url[len('file://'):]) if os.path.isabs(url): with open(url, 'rb') as handle: content = handle.read() else: content = requests.get(url).content with tempfile.NamedTemporaryFile(suffix=ext or '', prefix=url_hint, delete=False) as handle: handle.write(content) try: yield handle.name finally: if os.path.exists(handle.name): os.remove(handle.name)
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'] = False return self.run('true', *args, **kwargs)
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 "{}"!'.format(line)) else: if line.split()[-1].strip() == 'simpleindex': return base_url.split('\x1b')[0].strip().rstrip('/') raise LookupError("Cannot find simpleindex URL in '{}' output:\n {}".format( cmd, '\n '.join(lines), ))
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: raise RuntimeError("No tasks module is imported, cannot determine project root") cfg.rootjoin = lambda *names: os.path.join(cfg.project_root, *names) cfg.srcjoin = lambda *names: cfg.rootjoin(cfg.srcdir, *names) cfg.testjoin = lambda *names: cfg.rootjoin(cfg.testdir, *names) cfg.cwd = os.getcwd() os.chdir(cfg.project_root) # this assumes an importable setup.py # TODO: maybe call "python setup.py egg_info" for metadata if cfg.project_root not in sys.path: sys.path.append(cfg.project_root) try: from setup import project # pylint: disable=no-name-in-module except ImportError: from setup import setup_args as project # pylint: disable=no-name-in-module cfg.project = Bunch(project) return cfg
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(dirname) + "/" yield glob2re(filename)
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 = pattern.inclusive #print('+++' if inclusive else '---', path, pattern) return inclusive
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 path. """ lead = '' if 'with_root' in kwargs and kwargs.pop('with_root'): lead = self.root.rstrip(os.sep) + os.sep for base, dirs, files in os.walk(self.root, **kwargs): prefix = base[len(self.root):].lstrip(os.sep) bits = prefix.split(os.sep) if prefix else [] for dirname in dirs[:]: path = '/'.join(bits + [dirname]) inclusive = self.included(path, is_dir=True) if inclusive: yield lead + path + '/' elif inclusive is False: dirs.remove(dirname) for filename in files: path = '/'.join(bits + [filename]) if self.included(path): yield lead + path
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('Badly formatted top entry in changelog') name, version, _, _ = metadata.groups() # Build package ctx.run('dpkg-buildpackage {} {}'.format(ctx.rituals.deb.build.opts, opts)) # Move created artifacts into "dist" if not os.path.exists('dist'): os.makedirs('dist') artifact_pattern = '{}?{}*'.format(name, re.sub(r'[^-_.a-zA-Z0-9]', '?', version)) changes_files = [] for debfile in glob.glob('../' + artifact_pattern): shutil.move(debfile, 'dist') if debfile.endswith('.changes'): changes_files.append(os.path.join('dist', os.path.basename(debfile))) ctx.run('ls -l dist/{}'.format(artifact_pattern)) if dput: ctx.run('dput {} {}'.format(dput, ' '.join(changes_files)))
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 patterns based on given parameters venv_dirs = ['bin', 'include', 'lib', 'share', 'local', '.venv'] patterns = ['build/', 'pip-selfcheck.json'] excludes = ['.git/', '.hg/', '.svn/', 'debian/*/'] if docs or all: patterns.extend(['docs/_build/', 'doc/_build/']) if dist or all: patterns.append('dist/') if backups or all: patterns.extend(['**/*~']) if bytecode or all: patterns.extend([ '**/*.py[co]', '**/__pycache__/', '*.egg-info/', cfg.srcjoin('*.egg-info/')[len(cfg.project_root)+1:], ]) if venv: patterns.extend([i + '/' for i in venv_dirs]) if tox: patterns.append('.tox/') else: excludes.append('.tox/') if extra: patterns.extend(shlex.split(extra)) # Build fileset patterns = [antglob.includes(i) for i in patterns] + [antglob.excludes(i) for i in excludes] if not venv: # Do not scan venv dirs when not cleaning them patterns.extend([antglob.excludes(i + '/') for i in venv_dirs]) fileset = antglob.FileSet(cfg.project_root, patterns) # Iterate over matches and remove them for name in fileset: notify.info('rm {0}'.format(name)) if name.endswith('/'): shutil.rmtree(os.path.join(cfg.project_root, name)) else: os.unlink(os.path.join(cfg.project_root, name))
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_path: ctx.run("invoke docs") else: notify.warning("Cannot find either a 'docs' or 'doc' Sphinx directory!")
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: out.write("# Requirements frozen by 'pip freeze' on {}\n".format(isodate())) out.write(frozen) notify.info("Frozen {} requirements.".format(len(frozen.splitlines()),))
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 datestamp.isoformat(b' ' if PY2 else u' ')
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-error try: key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" + exe_name value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key) registered = (value, "from HKLM\\"+key) except _winreg.error: pass if registered and not os.path.exists(registered[0]): registered = None return registered
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 use the PATH environment variable. "verbose", if true, will cause a 2-tuple to be returned for each match. The second element is a textual description of where the match was found. "exts" optionally allows one to specify a list of extensions to use instead of the standard list for this system. This can effectively be used as an optimization to, for example, avoid stat's of "foo.vbs" when searching for "foo" and you know it is not a VisualBasic script but ".vbs" is on PATHEXT. This option is only supported on Windows. This method returns a generator which yields either full paths to the given command or, if verbose, tuples of the form (<path to command>, <where path found>). """ matches = [] if path is None: using_given_path = 0 path = os.environ.get("PATH", "").split(os.pathsep) if sys.platform.startswith("win"): path.insert(0, os.curdir) # implied by Windows shell else: using_given_path = 1 # Windows has the concept of a list of extensions (PATHEXT env var). if sys.platform.startswith("win"): if exts is None: exts = os.environ.get("PATHEXT", "").split(os.pathsep) # If '.exe' is not in exts then obviously this is Win9x and # or a bogus PATHEXT, then use a reasonable default. for ext in exts: if ext.lower() == ".exe": break else: exts = ['.COM', '.EXE', '.BAT'] elif not isinstance(exts, list): raise TypeError("'exts' argument must be a list or None") else: if exts is not None: raise WhichError("'exts' argument is not supported on platform '%s'" % sys.platform) exts = [] # File name cannot have path separators because PATH lookup does not # work that way. if os.sep in command or os.altsep and os.altsep in command: pass else: for i, dir_name in enumerate(path): # On windows the dir_name *could* be quoted, drop the quotes if sys.platform.startswith("win") and len(dir_name) >= 2 and dir_name[0] == '"' and dir_name[-1] == '"': dir_name = dir_name[1:-1] for ext in ['']+exts: abs_name = os.path.abspath(os.path.normpath(os.path.join(dir_name, command+ext))) if os.path.isfile(abs_name): if using_given_path: from_where = "from given path element %d" % i elif not sys.platform.startswith("win"): from_where = "from PATH element %d" % i elif i == 0: from_where = "from current directory" else: from_where = "from PATH element %d" % (i-1) match = _cull((abs_name, from_where), matches, verbose) if match: if verbose: yield match else: yield match[0] match = _get_registered_executable(command) if match is not None: match = _cull(match, matches, verbose) if match: if verbose: yield match else: yield match[0]
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. "verbose", if true, will cause a 2-tuple to be returned. The second element is a textual description of where the match was found. "exts" optionally allows one to specify a list of extensions to use instead of the standard list for this system. This can effectively be used as an optimization to, for example, avoid stat's of "foo.vbs" when searching for "foo" and you know it is not a VisualBasic script but ".vbs" is on PATHEXT. This option is only supported on Windows. If no match is found for the command, a WhichError is raised. """ matched = whichgen(command, path, verbose, exts) try: match = next(matched) except StopIteration: raise WhichError("Could not find '%s' on the path." % command) else: return match
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 be one of the two strings "sending" and "receiving". """ if chain == "sending": self.__previous_sending_chain_length = self.sending_chain_length self.__sending_chain = self.__SendingChain(key) if chain == "receiving": self.__receiving_chain = self.__ReceivingChain(key)
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 the ciphertext. :param ad: A bytes-like object encoding the associated data to use for message authentication. Pass None to use the associated data set during construction. :returns: The plaintext. :raises AuthenticationFailedException: If checking the authentication for this message failed. :raises NotInitializedException: If this double ratchet session is not yet initialized with a key pair, thus not prepared to decrypt an incoming message. :raises TooManySavedMessageKeysException: If more than message_key_store_max have to be stored to decrypt this message. """ if ad == None: ad = self.__ad # Try to decrypt the message using a previously saved message key plaintext = self.__decryptSavedMessage(ciphertext, header, ad) if plaintext: return plaintext # Check, whether the public key will trigger a dh ratchet step if self.triggersStep(header.dh_pub): # Save missed message keys for the current receiving chain self.__saveMessageKeys(header.pn) # Perform the step self.step(header.dh_pub) # Save missed message keys for the current receiving chain self.__saveMessageKeys(header.n) # Finally decrypt the message and return the plaintext return self.__decrypt( ciphertext, self.__skr.nextDecryptionKey(), header, ad )
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 None to use the associated data set during construction. :returns: A dictionary containing the message header and ciphertext. The header is required to synchronize the double ratchet of the receiving party. Send it along with the ciphertext. The returned dictionary consists of two keys: "header", which includes an instance of the Header class and "ciphertext", which includes the encrypted message encoded as a bytes-like object. :raises NotInitializedException: If this double ratchet session is not yet initialized with the other parties public key, thus not ready to encrypt a message to that party. """ if ad == None: ad = self.__ad # Prepare the header for this message header = Header( self.pub, self.__skr.sending_chain_length, self.__skr.previous_sending_chain_length ) # Encrypt the message ciphertext = self.__aead.encrypt( message, self.__skr.nextEncryptionKey(), self._makeAD(header, ad) ) return { "header" : header, "ciphertext" : ciphertext }
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_pub: A bytes-like object encoding the public key of the other Diffie-Hellman ratchet to synchronize with. """ if self.triggersStep(other_pub): self.__wrapOtherPub(other_pub) self.__newRootKey("receiving") self.__newRatchetKey() self.__newRootKey("sending")
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 bytes-like object encoding the data to pass to the key derivation function. :returns: A bytes-like object encoding the output material. """ self.__length += 1 result = self.__kdf.calculate(self.__key, data, 64) self.__key = result[:32] return result[32:]
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:: :meth:`is_consumed`, :meth:`is_produced`, :meth:`can_connect_to` """ other_mesh.disconnect() self.disconnect() self._connect_to(other_mesh)
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 disconnected and types_differ
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:`DefaultSpecification` """ parser = specification.new_parser(specification) loader = specification.new_loader(parser.knitting_pattern_set) return loader
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 from values free_rows = [] walk = [] for row in knitting_pattern.rows: rows_before_ = row.rows_before[:] if rows_before_: rows_before[row] = rows_before_ else: free_rows.append(row) assert free_rows while free_rows: # print("free rows:", free_rows) row = free_rows.pop(0) walk.append(row) assert row not in rows_before for freed_row in reversed(row.rows_after): todo = rows_before[freed_row] # print(" freed:", freed_row, todo) todo.remove(row) if not todo: del rows_before[freed_row] free_rows.insert(0, freed_row) assert not rows_before, "everything is walked" return walk
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` it should be a file-like object. The content is written to the file. After writing, the file's read/write position points behind the dumped content. """ if file is None: file = StringIO() self._file(file) return file
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": "" }