sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def security(): """View for security page.""" sessions = SessionActivity.query_by_user( user_id=current_user.get_id() ).all() master_session = None for index, session in enumerate(sessions): if SessionActivity.is_current(session.sid_s): master_session = session ...
View for security page.
entailment
def revoke_session(): """Revoke a session.""" form = RevokeForm(request.form) if not form.validate_on_submit(): abort(403) sid_s = form.data['sid_s'] if SessionActivity.query.filter_by( user_id=current_user.get_id(), sid_s=sid_s).count() == 1: delete_session(sid_s=sid_s)...
Revoke a session.
entailment
def upgrade(): """Upgrade database.""" with op.batch_alter_table('accounts_user_session_activity') as batch_op: batch_op.add_column(sa.Column('browser', sa.String(80), nullable=True)) batch_op.add_column( sa.Column('browser_version', sa.String(30), nullable=True)) batch_op.ad...
Upgrade database.
entailment
def query_by_expired(cls): """Query to select all expired sessions.""" lifetime = current_app.permanent_session_lifetime expired_moment = datetime.utcnow() - lifetime return cls.query.filter(cls.created < expired_moment)
Query to select all expired sessions.
entailment
def monkey_patch_flask_security(): """Monkey-patch Flask-Security.""" if utils.get_hmac != get_hmac: utils.get_hmac = get_hmac if utils.hash_password != hash_password: utils.hash_password = hash_password changeable.hash_password = hash_password rec...
Monkey-patch Flask-Security.
entailment
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. The following actions are executed: #. Initialize the configuration. #. Monkey-patch Flask-Security. #. Create the user datastore. #. Create the sessionstore. ...
Flask application initialization. The following actions are executed: #. Initialize the configuration. #. Monkey-patch Flask-Security. #. Create the user datastore. #. Create the sessionstore. #. Initialize the extension, the forms to register users and c...
entailment
def init_config(self, app): """Initialize configuration. :param app: The Flask application. """ try: pkg_resources.get_distribution('celery') app.config.setdefault( "ACCOUNTS_USE_CELERY", not (app.debug or app.testing)) except pkg_resource...
Initialize configuration. :param app: The Flask application.
entailment
def _enable_session_activity(self, app): """Enable session activity.""" user_logged_in.connect(login_listener, app) user_logged_out.connect(logout_listener, app) from .views.settings import blueprint from .views.security import security, revoke_session blueprint.route('/s...
Enable session activity.
entailment
def init_app(self, app, sessionstore=None, register_blueprint=False): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``)...
Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) :param register_blueprint: If ``True``, the application registers the ...
entailment
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) ...
Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) :param register_blueprint: If ``True``, the application registers the ...
entailment
def deactivate_user(self, user): """Deactivate a user. :param user: A :class:`invenio_accounts.models.User` instance. :returns: The datastore instance. """ res = super(SessionAwareSQLAlchemyUserDatastore, self).deactivate_user( user) if res: dele...
Deactivate a user. :param user: A :class:`invenio_accounts.models.User` instance. :returns: The datastore instance.
entailment
def _initialize_attributes(model_class, name, bases, attrs): """Initialize the attributes of the model.""" model_class._attributes = {} for k, v in attrs.iteritems(): if isinstance(v, Attribute): model_class._attributes[k] = v v.name = v.name or k
Initialize the attributes of the model.
entailment
def _initialize_referenced(model_class, attribute): """Adds a property to the target of a reference field that returns the list of associated objects. """ # this should be a descriptor def _related_objects(self): return (model_class.objects .filter(**{attribute.attname: self....
Adds a property to the target of a reference field that returns the list of associated objects.
entailment
def _initialize_lists(model_class, name, bases, attrs): """Stores the list fields descriptors of a model.""" model_class._lists = {} for k, v in attrs.iteritems(): if isinstance(v, ListField): model_class._lists[k] = v v.name = v.name or k
Stores the list fields descriptors of a model.
entailment
def _initialize_references(model_class, name, bases, attrs): """Stores the list of reference field descriptors of a model.""" model_class._references = {} h = {} deferred = [] for k, v in attrs.iteritems(): if isinstance(v, ReferenceField): model_class._references[k] = v ...
Stores the list of reference field descriptors of a model.
entailment
def _initialize_indices(model_class, name, bases, attrs): """Stores the list of indexed attributes.""" model_class._indices = [] for k, v in attrs.iteritems(): if isinstance(v, (Attribute, ListField)) and v.indexed: model_class._indices.append(k) if model_class._meta['indices']: ...
Stores the list of indexed attributes.
entailment
def _initialize_counters(model_class, name, bases, attrs): """Stores the list of counter fields.""" model_class._counters = [] for k, v in attrs.iteritems(): if isinstance(v, Counter): model_class._counters.append(k)
Stores the list of counter fields.
entailment
def get_model_from_key(key): """Gets the model from a given key.""" _known_models = {} model_name = key.split(':', 2)[0] # populate for klass in Model.__subclasses__(): _known_models[klass.__name__] = klass return _known_models.get(model_name, None)
Gets the model from a given key.
entailment
def from_key(key): """Returns the model instance based on the key. Raises BadKeyError if the key is not recognized by redisco or no defined model can be found. Returns None if the key could not be found. """ model = get_model_from_key(key) if model is None: raise BadKeyError try...
Returns the model instance based on the key. Raises BadKeyError if the key is not recognized by redisco or no defined model can be found. Returns None if the key could not be found.
entailment
def is_valid(self): """Returns True if all the fields are valid. It first validates the fields (required, unique, etc.) and then calls the validate method. """ self._errors = [] for field in self.fields: try: field.validate(self) e...
Returns True if all the fields are valid. It first validates the fields (required, unique, etc.) and then calls the validate method.
entailment
def update_attributes(self, **kwargs): """Updates the attributes of the model.""" attrs = self.attributes.values() + self.lists.values() \ + self.references.values() for att in attrs: if att.name in kwargs: att.__set__(self, kwargs[att.name])
Updates the attributes of the model.
entailment
def save(self): """Saves the instance to the datastore.""" if not self.is_valid(): return self._errors _new = self.is_new() if _new: self._initialize_id() with Mutex(self): self._write(_new) return True
Saves the instance to the datastore.
entailment
def key(self, att=None): """Returns the Redis key where the values are stored.""" if att is not None: return self._key[self.id][att] else: return self._key[self.id]
Returns the Redis key where the values are stored.
entailment
def delete(self): """Deletes the object from the datastore.""" pipeline = self.db.pipeline() self._delete_from_indices(pipeline) self._delete_membership(pipeline) pipeline.delete(self.key()) pipeline.execute()
Deletes the object from the datastore.
entailment
def incr(self, att, val=1): """Increments a counter.""" if att not in self.counters: raise ValueError("%s is not a counter.") self.db.hincrby(self.key(), att, val)
Increments a counter.
entailment
def attributes_dict(self): """Returns the mapping of the model attributes and their values. """ h = {} for k in self.attributes.keys(): h[k] = getattr(self, k) for k in self.lists.keys(): h[k] = getattr(self, k) for k in self.references.key...
Returns the mapping of the model attributes and their values.
entailment
def fields(self): """Returns the list of field names of the model.""" return (self.attributes.values() + self.lists.values() + self.references.values())
Returns the list of field names of the model.
entailment
def exists(cls, id): """Checks if the model with id exists.""" return bool(redisco.get_client().exists(cls._key[str(id)]) or redisco.get_client().sismember(cls._key['all'], str(id)))
Checks if the model with id exists.
entailment
def _initialize_id(self): """Initializes the id of the instance.""" self.id = str(self.db.incr(self._key['id']))
Initializes the id of the instance.
entailment
def _write(self, _new=False): """Writes the values of the attributes to the datastore. This method also creates the indices and saves the lists associated to the object. """ pipeline = self.db.pipeline() self._create_membership(pipeline) self._update_indices(pipe...
Writes the values of the attributes to the datastore. This method also creates the indices and saves the lists associated to the object.
entailment
def _create_membership(self, pipeline=None): """Adds the id of the object to the set of all objects of the same class. """ Set(self._key['all'], pipeline=pipeline).add(self.id)
Adds the id of the object to the set of all objects of the same class.
entailment
def _delete_membership(self, pipeline=None): """Removes the id of the object to the set of all objects of the same class. """ Set(self._key['all'], pipeline=pipeline).remove(self.id)
Removes the id of the object to the set of all objects of the same class.
entailment
def _add_to_indices(self, pipeline): """Adds the base64 encoded values of the indices.""" for att in self.indices: self._add_to_index(att, pipeline=pipeline)
Adds the base64 encoded values of the indices.
entailment
def _add_to_index(self, att, val=None, pipeline=None): """ Adds the id to the index. This also adds to the _indices set of the object. """ index = self._index_key_for(att) if index is None: return t, index = index if t == 'attribute': ...
Adds the id to the index. This also adds to the _indices set of the object.
entailment
def _delete_from_indices(self, pipeline): """Deletes the object's id from the sets(indices) it has been added to and removes its list of indices (used for housekeeping). """ s = Set(self.key()['_indices']) z = Set(self.key()['_zindices']) for index in s.members: ...
Deletes the object's id from the sets(indices) it has been added to and removes its list of indices (used for housekeeping).
entailment
def _index_key_for(self, att, value=None): """Returns a key based on the attribute and its value. The key is used for indexing. """ if value is None: value = getattr(self, att) if callable(value): value = value() if value is None: ...
Returns a key based on the attribute and its value. The key is used for indexing.
entailment
def isdisjoint(self, other): """Return True if the set has no elements in common with other.""" return not bool(self.db.sinter([self.key, other.key]))
Return True if the set has no elements in common with other.
entailment
def union(self, key, *others): """Return a new set with elements from the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sunionstore(key, [self.key] + [o.key for o in others]) return Set(key)
Return a new set with elements from the set and all others.
entailment
def intersection(self, key, *others): """Return a new set with elements common to the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sinterstore(key, [self.key] + [o.key for o in others]) return Set(key)
Return a new set with elements common to the set and all others.
entailment
def difference(self, key, *others): """Return a new set with elements in the set that are not in the others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sdiffstore(key, [self.key] + [o.key for o in others]) return Set(key)
Return a new set with elements in the set that are not in the others.
entailment
def update(self, *others): """Update the set, adding elements from all others.""" self.db.sunionstore(self.key, [self.key] + [o.key for o in others])
Update the set, adding elements from all others.
entailment
def intersection_update(self, *others): """Update the set, keeping only elements found in it and all others.""" self.db.sinterstore(self.key, [o.key for o in [self.key] + others])
Update the set, keeping only elements found in it and all others.
entailment
def difference_update(self, *others): """Update the set, removing elements found in others.""" self.db.sdiffstore(self.key, [o.key for o in [self.key] + others])
Update the set, removing elements found in others.
entailment
def copy(self, key): """Copy the set to another key and return the new Set. WARNING: If the key exists, it overwrites it. """ copy = Set(key=key, db=self.db) copy.clear() copy |= self return copy
Copy the set to another key and return the new Set. WARNING: If the key exists, it overwrites it.
entailment
def sinter(self, *other_sets): """Performs an intersection between Sets. Returns a set of common members. Uses Redis.sinter. """ return self.db.sinter([self.key] + [s.key for s in other_sets])
Performs an intersection between Sets. Returns a set of common members. Uses Redis.sinter.
entailment
def sunion(self, *other_sets): """Union between Sets. Returns a set of common members. Uses Redis.sunion. """ return self.db.sunion([self.key] + [s.key for s in other_sets])
Union between Sets. Returns a set of common members. Uses Redis.sunion.
entailment
def sdiff(self, *other_sets): """Union between Sets. Returns a set of common members. Uses Redis.sdiff. """ return self.db.sdiff([self.key] + [s.key for s in other_sets])
Union between Sets. Returns a set of common members. Uses Redis.sdiff.
entailment
def reverse(self): """Reverse in place.""" r = self[:] r.reverse() self.clear() self.extend(r)
Reverse in place.
entailment
def copy(self, key): """Copy the list to a new list. WARNING: If key exists, it clears it before copying. """ copy = List(key, self.db) copy.clear() copy.extend(self) return copy
Copy the list to a new list. WARNING: If key exists, it clears it before copying.
entailment
def lt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores less than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(self._min_score, "(%f" % v, start=offset, num=limit)
Returns the list of the members of the set that have scores less than v.
entailment
def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=lim...
Returns the list of the members of the set that have scores greater than v.
entailment
def between(self, min, max, limit=None, offset=None): """Returns the list of the members of the set that have scores between min and max. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(min, max, start=offset, num=limi...
Returns the list of the members of the set that have scores between min and max.
entailment
def hex_to_bytes(s): """ convert hex string to bytes """ if len(s) % 2: s = b'0' + s ia = [int(s[i:i+2], 16) for i in range(0, len(s), 2)] # int array return bs(ia) if PYTHON_MAJOR_VER == 3 else b''.join([chr(c) for c in ia])
convert hex string to bytes
entailment
def client_seed(a=random.randrange(0, 1 << SRP_KEY_SIZE)): """ A: Client public key a: Client private key """ if DEBUG: a = DEBUG_PRIVATE_KEY N, g, k = get_prime() A = pow(g, a, N) if DEBUG_PRINT: print('a=', binascii.b2a_hex(long2bytes(a)), end='\n') prin...
A: Client public key a: Client private key
entailment
def server_seed(v, b=random.randrange(0, 1 << SRP_KEY_SIZE)): """ B: Server public key b: Server private key """ N, g, k = get_prime() if DEBUG: b = DEBUG_PRIVATE_KEY gb = pow(g, b, N) kv = (k * v) % N B = (kv + gb) % N if DEBUG_PRINT: print("v", binascii....
B: Server public key b: Server private key
entailment
def client_session(user, password, salt, A, B, a): """ Client session secret Both: u = H(A, B) User: x = H(s, p) (user enters password) User: S = (B - kg^x) ^ (a + ux) (computes session key) User: K = H(S) """ N, g, k = get_prime() u = get_scram...
Client session secret Both: u = H(A, B) User: x = H(s, p) (user enters password) User: S = (B - kg^x) ^ (a + ux) (computes session key) User: K = H(S)
entailment
def server_session(user, password, salt, A, B, b): """ Server session secret Both: u = H(A, B) Host: S = (Av^u) ^ b (computes session key) Host: K = H(S) """ N, g, k = get_prime() u = get_scramble(A, B) v = get_verifier(user, password, salt) vu = pow(...
Server session secret Both: u = H(A, B) Host: S = (Av^u) ^ b (computes session key) Host: K = H(S)
entailment
def client_proof(user, password, salt, A, B, a, hash_algo): """ M = H(H(N) xor H(g), H(I), s, A, B, K) """ N, g, k = get_prime() K = client_session(user, password, salt, A, B, a) n1 = bytes2long(hash_digest(hashlib.sha1, N)) n2 = bytes2long(hash_digest(hashlib.sha1, g)) if DEBUG_PRINT: ...
M = H(H(N) xor H(g), H(I), s, A, B, K)
entailment
def dpd_to_int(dpd): """ Convert DPD encodined value to int (0-999) dpd: DPD encoded value. 10bit unsigned int """ b = [None] * 10 b[9] = 1 if dpd & 0b1000000000 else 0 b[8] = 1 if dpd & 0b0100000000 else 0 b[7] = 1 if dpd & 0b0010000000 else 0 b[6] = 1 if dpd & 0b0001000000 else 0 ...
Convert DPD encodined value to int (0-999) dpd: DPD encoded value. 10bit unsigned int
entailment
def calc_significand(prefix, dpd_bits, num_bits): """ prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits """ # https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field num_segments = num_bits // 10 se...
prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits
entailment
def decimal128_to_decimal(b): "decimal128 bytes to Decimal" v = decimal128_to_sign_digits_exponent(b) if isinstance(v, Decimal): return v sign, digits, exponent = v return Decimal((sign, Decimal(digits).as_tuple()[1], exponent))
decimal128 bytes to Decimal
entailment
def error_response(response): """ Raises errors matching the response code """ if response.status_code >= 500: raise exceptions.GeocodioServerError elif response.status_code == 403: raise exceptions.GeocodioAuthError elif response.status_code == 422: raise exceptions.Ge...
Raises errors matching the response code
entailment
def _req(self, method="get", verb=None, headers={}, params={}, data={}): """ Method to wrap all request building :return: a Response object based on the specified method and request values. """ url = self.BASE_URL.format(verb=verb) request_headers = {"content-type": "app...
Method to wrap all request building :return: a Response object based on the specified method and request values.
entailment
def parse(self, address): """ Returns an Address dictionary with the components of the queried address. >>> client = GeocodioClient('some_api_key') >>> client.parse("1600 Pennsylvania Ave, Washington DC") { "address_components": { "number": "1...
Returns an Address dictionary with the components of the queried address. >>> client = GeocodioClient('some_api_key') >>> client.parse("1600 Pennsylvania Ave, Washington DC") { "address_components": { "number": "1600", "street": "Pennsylvania"...
entailment
def batch_geocode(self, addresses, **kwargs): """ Returns an Address dictionary with the components of the queried address. """ fields = ",".join(kwargs.pop("fields", [])) response = self._req( "post", verb="geocode", params={"fields": ...
Returns an Address dictionary with the components of the queried address.
entailment
def geocode_address(self, address, **kwargs): """ Returns a Location dictionary with the components of the queried address and the geocoded location. >>> client = GeocodioClient('some_api_key') >>> client.geocode("1600 Pennsylvania Ave, Washington DC") { "input":...
Returns a Location dictionary with the components of the queried address and the geocoded location. >>> client = GeocodioClient('some_api_key') >>> client.geocode("1600 Pennsylvania Ave, Washington DC") { "input": { "address_components": { "number": "...
entailment
def geocode(self, address_data, **kwargs): """ Returns geocoding data for either a list of addresses or a single address represented as a string. Provides a single point of access for end users. """ if isinstance(address_data, list): return self.batch_geocode...
Returns geocoding data for either a list of addresses or a single address represented as a string. Provides a single point of access for end users.
entailment
def reverse_point(self, latitude, longitude, **kwargs): """ Method for identifying an address from a geographic point """ fields = ",".join(kwargs.pop("fields", [])) point_param = "{0},{1}".format(latitude, longitude) response = self._req( verb="reverse", para...
Method for identifying an address from a geographic point
entailment
def batch_reverse(self, points, **kwargs): """ Method for identifying the addresses from a list of lat/lng tuples """ fields = ",".join(kwargs.pop("fields", [])) response = self._req( "post", verb="reverse", params={"fields": fields}, data=json_points(points) ...
Method for identifying the addresses from a list of lat/lng tuples
entailment
def reverse(self, points, **kwargs): """ General method for reversing addresses, either a single address or multiple. *args should either be a longitude/latitude pair or a list of such pairs:: >>> multiple_locations = reverse([(40, -19), (43, 112)]) >>> single_l...
General method for reversing addresses, either a single address or multiple. *args should either be a longitude/latitude pair or a list of such pairs:: >>> multiple_locations = reverse([(40, -19), (43, 112)]) >>> single_location = reverse((40, -19))
entailment
def str_to_bytes(self, s): "convert str to bytes" if (PYTHON_MAJOR_VER == 3 or (PYTHON_MAJOR_VER == 2 and type(s) == unicode)): return s.encode(charset_map.get(self.charset, self.charset)) return s
convert str to bytes
entailment
def bytes_to_str(self, b): "convert bytes array to raw string" if PYTHON_MAJOR_VER == 3: return b.decode(charset_map.get(self.charset, self.charset)) return b
convert bytes array to raw string
entailment
def bytes_to_ustr(self, b): "convert bytes array to unicode string" return b.decode(charset_map.get(self.charset, self.charset))
convert bytes array to unicode string
entailment
def params_to_blr(self, trans_handle, params): "Convert parameter array to BLR and values format." ln = len(params) * 2 blr = bs([5, 2, 4, 0, ln & 255, ln >> 8]) if self.accept_version < PROTOCOL_VERSION13: values = bs([]) else: # start with null indicator...
Convert parameter array to BLR and values format.
entailment
def coords(self): """ Returns a tuple representing the location of the address in a GIS coords format, i.e. (longitude, latitude). """ x, y = ("lat", "lng") if self.order == "lat" else ("lng", "lat") try: return (self["location"][x], self["location"][y]) ...
Returns a tuple representing the location of the address in a GIS coords format, i.e. (longitude, latitude).
entailment
def get(self, key): """ Returns an individual Location by query lookup, e.g. address or point. """ if isinstance(key, tuple): # TODO handle different ordering try: x, y = float(key[0]), float(key[1]) except IndexError: ...
Returns an individual Location by query lookup, e.g. address or point.
entailment
def calc_blr(xsqlda): "Calculate BLR from XSQLVAR array." ln = len(xsqlda) * 2 blr = [5, 2, 4, 0, ln & 255, ln >> 8] for x in xsqlda: sqltype = x.sqltype if sqltype == SQL_TYPE_VARYING: blr += [37, x.sqllen & 255, x.sqllen >> 8] elif sqltype == SQL_TYPE_TEXT: ...
Calculate BLR from XSQLVAR array.
entailment
def _parse_date(self, raw_value): "Convert raw data to datetime.date" nday = bytes_to_bint(raw_value) + 678882 century = (4 * nday - 1) // 146097 nday = 4 * nday - 1 - 146097 * century day = nday // 4 nday = (4 * day + 3) // 1461 day = 4 * day + 3 - 1461 * nday ...
Convert raw data to datetime.date
entailment
def _parse_time(self, raw_value): "Convert raw data to datetime.time" n = bytes_to_bint(raw_value) s = n // 10000 m = s // 60 h = m // 60 m = m % 60 s = s % 60 return (h, m, s, (n % 10000) * 100)
Convert raw data to datetime.time
entailment
def execute_update(args): """Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'. """ provider_class = getattr(dnsupdater, dnsupdater.AVAILABLE_PLUGINS.get(args.p...
Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'.
entailment
def update_dns(self, new_ip): """Call No-IP API based on dict login_info and return the status code. """ headers = None if self.auth_type == 'T': api_call_url = self._base_url.format(hostname=self.hostname, token=self.auth.tok...
Call No-IP API based on dict login_info and return the status code.
entailment
def status_message(self): """Return friendly response from API based on response code. """ msg = None if self.last_ddns_response in response_messages.keys(): return response_messages.get(self.last_ddns_response) if 'good' in self.last_ddns_response: ip = re.sear...
Return friendly response from API based on response code.
entailment
def get_ip(): """Return machine's origin IP address. """ try: r = requests.get(HTTPBIN_URL) ip, _ = r.json()['origin'].split(',') return ip if r.status_code == 200 else None except requests.exceptions.ConnectionError: return None
Return machine's origin IP address.
entailment
def store(auth, provider, config_location=DEFAULT_CONFIG_DIR): """Store auth info in file for specified provider """ auth_file = None try: # only for custom locations _create_config_dir(config_location, "Creating custom config directory [%s]... ") config_...
Store auth info in file for specified provider
entailment
def load(provider, config_location=DEFAULT_CONFIG_DIR): """Load provider specific auth info from file """ auth = None auth_file = None try: config_dir = os.path.join(config_location, NOIPY_CONFIG) print("Loading stored auth info [%s]... " % config_dir, end="") auth_file = os.pat...
Load provider specific auth info from file
entailment
def exists(provider, config_location=DEFAULT_CONFIG_DIR): """Check whether provider info is already stored """ config_dir = os.path.join(config_location, NOIPY_CONFIG) auth_file = os.path.join(config_dir, provider) return os.path.exists(auth_file)
Check whether provider info is already stored
entailment
def get_instance(cls, encoded_key): """Return an ApiAuth instance from an encoded key """ login_str = base64.b64decode(encoded_key).decode('utf-8') usertoken, password = login_str.strip().split(':', 1) instance = cls(usertoken, password) return instance
Return an ApiAuth instance from an encoded key
entailment
def update_index(model_items, model_name, action='index', bulk_size=100, num_docs=-1, start_date=None, end_date=None, refresh=True): ''' Updates the index for the provided model_items. :param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or d...
Updates the index for the provided model_items. :param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or deleted. If action is 'index', the model_items must be serializable objects. If action is 'delete', the model_items must be primary keys c...
entailment
def delete_index_item(item, model_name, refresh=True): ''' Deletes an item from the index. :param item: must be a serializable object. :param model_name: doctype, which must also be the model name. :param refresh: a boolean that determines whether to refresh the index, making all operations performe...
Deletes an item from the index. :param item: must be a serializable object. :param model_name: doctype, which must also be the model name. :param refresh: a boolean that determines whether to refresh the index, making all operations performed since the last refresh immediately available for search, inst...
entailment
def create_indexed_document(index_instance, model_items, action): ''' Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete. ''' data = [] if action == 'delete': ...
Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete.
entailment
def filter_model_items(index_instance, model_items, model_name, start_date, end_date): ''' Filters the model items queryset based on start and end date.''' if index_instance.updated_field is None: logger.warning("No updated date field found for {} - not restricting with start and end date".format(model_...
Filters the model items queryset based on start and end date.
entailment
def extract_version(txt): """This function tries to extract the version from the help text of any program.""" words = txt.replace(',', ' ').split() version = None for x in reversed(words): if len(x) > 2: if x[0].lower() == 'v': x = x[1:] if '.' in x an...
This function tries to extract the version from the help text of any program.
entailment
def check(self, return_code=0): """Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: self """ ...
Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: self
entailment
def call(self, timeout=None): """Run command with arguments. Wait for command to complete. same as: 1. :meth:`start` 2. :meth:`wait` 3. :meth:`stop` :rtype: self """ self.start().wait(timeout=timeout) if self.is_alive(): self.stop...
Run command with arguments. Wait for command to complete. same as: 1. :meth:`start` 2. :meth:`wait` 3. :meth:`stop` :rtype: self
entailment
def start(self): """start command in background and does not wait for it. :rtype: self """ if self.is_started: raise EasyProcessError(self, 'process was started twice!') if self.use_temp_files: self._stdout_file = tempfile.TemporaryFile(prefix='stdout_'...
start command in background and does not wait for it. :rtype: self
entailment
def wait(self, timeout=None): """Wait for command to complete. Timeout: - discussion: http://stackoverflow.com/questions/1191374/subprocess-with-timeout - implementation: threading :rtype: self """ if timeout is not None: if not self._thread: ...
Wait for command to complete. Timeout: - discussion: http://stackoverflow.com/questions/1191374/subprocess-with-timeout - implementation: threading :rtype: self
entailment
def sendstop(self): ''' Kill process (:meth:`subprocess.Popen.terminate`). Do not wait for command to complete. :rtype: self ''' if not self.is_started: raise EasyProcessError(self, 'process was not started!') log.debug('stopping process (pid=%s cmd=...
Kill process (:meth:`subprocess.Popen.terminate`). Do not wait for command to complete. :rtype: self
entailment
def wrap(self, func, delay=0): ''' returns a function which: 1. start process 2. call func, save result 3. stop process 4. returns result similar to :keyword:`with` statement :rtype: ''' def wrapped(): self.start() ...
returns a function which: 1. start process 2. call func, save result 3. stop process 4. returns result similar to :keyword:`with` statement :rtype:
entailment
def send_message(self, message, room_id, **kwargs): """ Send a message to a given room """ return SendMessage(settings=self.settings, **kwargs).call( message=message, room_id=room_id, **kwargs )
Send a message to a given room
entailment
def get_private_rooms(self, **kwargs): """ Get a listing of all private rooms with their names and IDs """ return GetPrivateRooms(settings=self.settings, **kwargs).call(**kwargs)
Get a listing of all private rooms with their names and IDs
entailment