code stringlengths 1 18.2k |
|---|
Run field-specific validation regex record, hist = self._val_fs_regex(record=record, hist=hist) # Run user-defined functions for beforeNormLookup record, hist = self._apply_udfs(record=record, hist=hist, udf_type='beforeNormLookup') # Run normalization lookup record, hist = self._norm_lookup(record=record, hist=hist) #... |
def _get_field_error_dict(self, field): '''Returns the dict containing the field errors information''' return { 'name': field.html_name, 'id': 'id_{}'.format(field.html_name), # This may be a problem 'errors': field.errors, } |
def get_hidden_fields_errors(self, form): '''Returns a dict to add in response when something is wrong with hidden fields''' if not self.include_hidden_fields or form.is_valid(): return {} response = {self.hidden_field_error_key:{}} for field in form.hidden_fields(): if field.errors: response[self.hidden_field_error_ke... |
def form_invalid(self, form): '''Builds the JSON for the errors''' response = {self.errors_key: {}} response[self.non_field_errors_key] = form.non_field_errors() response.update(self.get_hidden_fields_errors(form)) for field in form.visible_fields(): if field.errors: response[self.errors_key][field.html_name] = self._g... |
def upgrade(): """Upgrade database.""" op.create_table( 'collection', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('dbquery', sa.Text(), nullable=True), sa.Column('rgt', sa.Integer(), nullable=False), sa.Column('lft', sa.Integer(), nullable=False), s... |
def do_env(self, line): """ env {environment-name} """ if not line: print "use: env {environment-name}" else: if not set_environment(line): print "no configuration for environment %s" % line else: self.do_login('') |
def do_schema(self, line): """ schema schema --clear schema filed_name field_type """ args = self.getargs(line) if not args: for k in sorted(self.schema): print "%s\t%s" % (k, self.schema[k]) elif args[0] == "--clear": self.schema.clear() else: fname = args[0] ftype = args[1] if not ftype in VALID_TYPES: print "invalid... |
def do_login(self, line): "login aws-acces-key aws-secret" if line: args = self.getargs(line) self.conn = boto.connect_dynamodb( aws_access_key_id=args[0], aws_secret_access_key=args[1]) else: self.conn = boto.connect_dynamodb() self.do_tables('') |
def do_describe(self, line): "describe [-c] {tablename}..." args = self.getargs(line) if '-c' in args: create_info = True args.remove('-c') else: create_info = False if not args: if self.table: args = [self.table.name] else: args = self.tables for table in args: desc = self.conn.describe_table(table) if create_info: in... |
def do_use(self, line): "use {tablename}" self.table = self.conn.get_table(line) self.pprint(self.conn.describe_table(self.table.name)) self.prompt = "%s> " % self.table.name |
def do_create(self, line): "create {tablename} [-c rc,wc] {hkey}[:{type} {rkey}:{type}]" args = self.getargs(line) rc = wc = 5 name = args.pop(0) # tablename if args[0] == "-c": # capacity args.pop(0) # skyp -c capacity = args.pop(0).strip() rc, _, wc = capacity.partition(",") rc = int(rc) wc = int(wc) if wc != "" else... |
def do_drop(self, line): "drop {tablename}" self.conn.delete_table(self.conn.get_table(line)) |
def do_refresh(self, line): "refresh {table_name}" table = self.get_table(line) table.refresh(True) self.pprint(self.conn.describe_table(table.name)) |
def do_capacity(self, line): "capacity {tablename} {read_units} {write_units}" args = self.getargs(line) table = self.get_table(args[0]) read_units = int(args[1]) write_units = int(args[2]) desc = self.conn.describe_table(table.name) prov = desc['Table']['ProvisionedThroughput'] current_read, current_write = prov['Read... |
write units" % (table.name, current_read, current_write) table.update_throughput(current_read, current_write) print "" self.do_refresh(table.name) print "" |
def do_rm(self, line): "rm [:tablename] [!fieldname:expectedvalue] [-v] {haskkey [rangekey]}" table, line = self.get_table_params(line) expected, line = self.get_expected(line) args = self.getargs(line) if "-v" in args: ret = "ALL_OLD" args.remove("-v") else: ret = None hkey = self.get_typed_key_value(table, args[0], T... |
def do_scan(self, line): """ scan [:tablename] [--batch=#] [-{max}] [--count|-c] [--array|-a] [+filter_attribute:filter_value] [attributes,...] if filter_value contains '=' it's interpreted as {conditional}={value} where condtional is: eq (equal value) ne {value} (not equal value) le (less or equal then value) lt (less... |
filter_value.startswith("begin="): filter_cond = BEGINS_WITH(self.get_typed_value(filter_name, filter_value[6:])) elif filter_value.startswith("eq="): filter_cond = EQ(self.get_typed_value(filter_name, filter_value[3:])) elif filter_value.startswith("ne="): filter_cond = NE(self.get_typed_value(filter_name, filter_valu... |
args.pop(0) count = True elif arg[0] == '-' and arg[1:].isdigit(): args.pop(0) max_size = int(arg[1:]) elif arg == '--': args.pop(0) break elif arg.startswith('-'): args.pop(0) print "invalid argument: %s" % arg break else: break attr_keys = args[0].split(",") if args else None attrs = list(set(attr_keys)) if attr_keys... |
def do_query(self, line): """ query [:tablename] [-r] [--count|-c] [--array|-a] [-{max}] [{rkey-condition}] hkey [attributes,...] where rkey-condition: --eq={key} (equal key) --ne={key} (not equal key) --le={key} (less or equal than key) --lt={key} (less than key) --ge={key} (greater or equal than key) --gt={key} (grea... |
int(arg[6:]) elif arg in ['--count', '-c']: count = True args.pop(0) elif arg in ['--array', '-a']: as_array = True args.pop(0) elif args[0].startswith('--batch='): arg = args.pop(0) batch_size = int(arg[8:]) elif args[0].startswith('--start='): arg = args.pop(0) start = (arg[8:], ) elif args[0] == '--next': arg = args... |
= CONTAINS(self.get_typed_key_value(table, arg[11:], False)) args.pop(0) elif arg.startswith("--between="): parts = arg[10:].split(",", 1) condition = BETWEEN(self.get_typed_key_value(table, parts[0], True), self.get_typed_key_value(table, parts[1], False)) args.pop(0) else: break hkey = self.get_typed_key_value(table,... |
def do_rmall(self, line): "remove [tablename...] yes" args = self.getargs(line) if args and args[-1] == "yes": args.pop() if not args: args = [self.table.name] while args: table = self.conn.get_table(args.pop(0)) print "from table " + table.name for item in table.scan(attributes_to_get=[], request_limit=10): print " re... |
def getAll(self): '''Return a dictionary with all variables''' if not bool(len(self.ATTRIBUTES)): self.load_attributes() return eval(str(self.ATTRIBUTES)) |
def set(self, name, default=0, editable=True, description=""): '''Define a variable in DB and in memory''' var, created = ConfigurationVariable.objects.get_or_create(name=name) if created: var.value = default if not editable: var.value = default var.editable = editable var.description = description var.save(reload=Fals... |
def load_attributes(self): '''Read the variables from the VARS_MODULE_PATH''' try: vars_path = settings.VARS_MODULE_PATH except Exception: # logger.warning("*" * 55) logger.warning( " [WARNING] Using default VARS_MODULE_PATH = '{}'".format( VARS_MODULE_PATH_DEFAULT)) vars_path = VARS_MODULE_PATH_DEFAULT try: __import__... |
def compile_expression(source): """ THIS FUNCTION IS ON ITS OWN FOR MINIMAL GLOBAL NAMESPACE :param source: PYTHON SOURCE CODE :return: PYTHON FUNCTION """ # FORCE MODULES TO BE IN NAMESPACE _ = coalesce _ = listwrap _ = Date _ = convert _ = Log _ = Data _ = EMPTY_DICT _ = re _ = wrap_leaves _ = is_data fake_locals = {... |
def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised. """ #: return constant's name instead of constant itself value = self.to_python(value).name self.validate(value, mod... |
def _get_choices(self): """ Redefine standard method. """ if not self._choices: self._choices = tuple( (x.name, getattr(x, 'verbose_name', x.name) or x.name) for x in self.choices_class.constants() ) return self._choices |
def _get_flatchoices(self): """ Redefine standard method. Return constants themselves instead of their names for right rendering in admin's 'change_list' view, if field is present in 'list_display' attribute of model's admin. """ return [ (self.to_python(choice), value) for choice, value in self._choices ] |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text, } if self.has_default(): if callable(self.default): defaults['initia... |
'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = choices_form_class or ChoicesFormField return form_class(**defaults) |
def get_bundle(self, current_bundle, url_kwargs, context_kwargs): """ Returns the bundle to get the alias view from. If 'self.bundle_attr' is set, that bundle that it points to will be returned, otherwise the current_bundle will be returned. """ if self.bundle_attr: if self.bundle_attr == PARENT: return current_bundle.... |
def get_view_name(self, requested): """ Returns the name of the view to lookup. If `requested` is equal to 'self.bundle_attr' then 'main' will be returned. Otherwise if `self.alias_to` is set the it's value will be returned. Otherwise the `requested` itself will be returned. """ value = self.alias_to and self.alias_to ... |
def get_object_header_view(self, request, url_kwargs, parent_only=False, render_type='object_header'): """ An object header is the title block of a CMS page. Actions to linked to in the header are based on this views bundle. This returns a view instance and view name of the view that should be rendered as an object hea... |
to 'object_header'. """ if parent_only and self.object_view != self.parent_attr: return None, None if self.object_view == self.parent_attr and self.parent: return self.parent.get_object_header_view(request, url_kwargs, render_type=render_type) elif self.object_view: view, name = self.get_initialized_view_and_name(self.... |
def get_string_from_view(self, request, view_name, url_kwargs, render_type='string'): """ Returns a string that is a rendering of the view given a request, view_name, and the original url_kwargs. Makes the following changes the view before rendering: * Sets can_submit to False. * Adds action_url to the context. This is... |
part of a normal match \ for that view. This is done by calling the `get_url_kwargs` \ method on the view. :param render_type: The render type to use. Defaults to \ 'string'. """ response = "" try: view, name = self.get_initialized_view_and_name(view_name, render_type=render_type, can_submit=False, base_template='cms/p... |
def get_view_url(self, view_name, user, url_kwargs=None, context_kwargs=None, follow_parent=True, check_permissions=True): """ Returns the url for a given view_name. If the view isn't found or the user does not have permission None is returned. A NoReverseMatch error may be raised if the view was unable to find the cor... |
that will be passed \ to the view for consideration in the final keyword arguments \ for reverse. :param follow_parent: If we encounter a parent reference should \ we follow it. Defaults to True. :param check_permisions: Run permissions checks. Defaults to True. """ view, url_name = self.get_initialized_view_and_name(v... |
def get_initialized_view_and_name(self, view_name, follow_parent=True, **extra_kwargs): """ Creates and returns a new instance of a CMSView \ and it's url_name. :param view_name: The name of the view to return. :param follow_parent: If we encounter a parent reference should \ we follow it. Defaults to True. :param extr... |
def get_title(self, plural=True): """ Get's the title of the bundle. Titles can be singular or plural. """ value = self.title if value == self.parent_attr: return self.parent.get_title(plural=plural) if not value and self._meta.model: value = helpers.model_name(self._meta.model, self._meta.custom_model_name, self._meta... |
def get_view_and_name(self, attname): """ Gets a view or bundle and returns it and it's url_name. """ view = getattr(self, attname, None) if attname in self._children: view = self._get_bundle_from_promise(attname) if view: if attname in self._children: return view, view.name elif isinstance(view, ViewAlias): view_name ... |
def get_urls(self): """ Returns urls handling bundles and views. This processes the 'item view' first in order and then adds any non item views at the end. """ parts = [] seen = set() # Process item views in order for v in list(self._meta.item_views)+list(self._meta.action_views): if not v in seen: view, name = self.ge... |
def get_navigation(self, request, **kwargs): """ Generates a list of tuples based on the values in `self.navigation` that are the side navigation links for this bundle. The tuple format is (url, title). """ if self.navigation == self.parent_attr: if self.parent: return self.parent.get_navigation(request, **kwargs) retu... |
def as_subbundle(cls, name=None, title=None, title_plural=None): """ Wraps the given bundle so that it can be lazily instantiated. :param name: The slug for this bundle. :param title: The verbose name for this bundle. """ return PromiseBundle(cls, name=name, title=title, title_plural=title_plural) |
def _thumbnail_resize(self, image, thumb_size, crop=None, bg=None): """Performs the actual image cropping operation with PIL.""" if crop == 'fit': img = ImageOps.fit(image, thumb_size, Image.ANTIALIAS) else: img = image.copy() img.thumbnail(thumb_size, Image.ANTIALIAS) if bg: img = self._bg_square(img, bg) return img |
def _thumbnail_local(self, original_filename, thumb_filename, thumb_size, thumb_url, crop=None, bg=None, quality=85): """Finds or creates a thumbnail for the specified image on the local filesystem.""" # create folders self._get_path(thumb_filename) thumb_url_full = url_for('static', filename=thumb_url) # Return the th... |
def _thumbnail_s3(self, original_filename, thumb_filename, thumb_size, thumb_url, bucket_name, crop=None, bg=None, quality=85): """Finds or creates a thumbnail for the specified image on Amazon S3.""" scheme = self.app.config.get('THUMBNAIL_S3_USE_HTTPS') and 'https' or 'http' thumb_url_full = url_for_s3( 'static', buc... |
conn.get_bucket(self.app.config.get('THUMBNAIL_S3_BUCKET_NAME')) path = self._get_s3_path(thumb_filename) k = bucket.new_key(path) try: k.set_contents_from_string(temp_file.getvalue()) k.set_acl(self.app.config.get('THUMBNAIL_S3_ACL', 'public-read')) except S3ResponseError: return '' return thumb_url_full |
def thumbnail(self, img_url, size, crop=None, bg=None, quality=85, storage_type=None, bucket_name=None): """ :param img_url: url img - '/assets/media/summer.jpg' :param size: size return thumb - '100x100' :param crop: crop return thumb - 'fit' or None :param bg: tuple color or None - (255, 255, 255, 0) :param quality: ... |
invalid, the only supported storage type (apart from default local storage) is s3.' % storage_type) return self._thumbnail_s3(original_filename, thumb_filename, thumb_size, thumb_url, bucket_name, crop=crop, bg=bg, quality=quality) |
def update_kwargs(self, request, **kwargs): """ Hook for adding data to the context before rendering a template. :param kwargs: The current context keyword arguments. :param request: The current request object. """ if not 'base' in kwargs: kwargs['base'] = self.base if request.is_ajax() or request.GET.get('json'): kwar... |
def render(self, request, redirect_url=None, **kwargs): """ Uses `self.template` to render a response. :param request: The current request object. :param redirect_url: If given this will return the \ redirect method instead of rendering the normal template. \ Renders providing this argument are referred to as a \ 'rend... |
def update_kwargs(self, request, **kwargs): """ Adds variables to the context that are expected by the base cms templates. * **navigation** - The side navigation for this bundle and user. * **dashboard** - The list of dashboard links for this user. * **object_header** - If no 'object_header' was passed in the \ current... |
= super(CMSRender, self).update_kwargs(request, **kwargs) # Check if we need to to include a separate object # bundle for the title bundle = kwargs.get('bundle') url_kwargs = kwargs.get('url_params') view = None if bundle: view, name = bundle.get_object_header_view(request, url_kwargs, parent_only=True) kwargs['dashboa... |
def get_different_page(self, request, page): """ Returns a url that preserves the current querystring while changing the page requested to `page`. """ if page: qs = request.GET.copy() qs['page'] = page return "%s?%s" % (request.path_info, qs.urlencode()) return None |
def render(self, request, **kwargs): """ Returns a JSON representation of a objects list page. The json has the following attributes: * **is_paginated** - Is the list paginated. * **results** - A list of objects, where each object has an \ attribute/value for each field in the list. An 'id' attribute \ is always includ... |
is paginated, how many objects \ total are there. * **page** - Current page number. * **next** - The full link to the next page. * **previous** - The full link to the previous page. If the list can be filtered the following attribute is included: * **params** - An object who's properties are the filter options. \ Each ... |
"next": "", "params": {"name": {"value": null}}, "is_paginated": true, "page": 1, "previous": ""} """ data = { 'is_paginated': kwargs.get('is_paginated') } if data.get('is_paginated'): page = kwargs['page_obj'] next_p = '' previous = '' if page.has_next(): next_p = self.get_different_page(request, page.number + 1) if p... |
def get_kwargs_for_view(self, name): """ Returns the full list of keyword arguments for the given view name as a dictionary. First the default_kwargs dictionary is copied. Then it is updated with the any of the 'view values' that can be specified directly on this instance. IE: models. Then that dictionary is updated wi... |
def get(url): """ USE json.net CONVENTIONS TO LINK TO INLINE OTHER JSON """ url = text_type(url) if url.find("://") == -1: Log.error("{{url}} must have a prototcol (eg http://) declared", url=url) base = URL("") if url.startswith("file://") and url[7] != "/": if os.sep=="\\": base = URL("file:///" + os.getcwd().replace... |
def expand(doc, doc_url="param://", params=None): """ ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE EXPANDING FEATURE USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY :param doc: THE DATA STRUCTURE FROM JSON SOURCE :param doc_url: THE URL THIS doc CAME FROM (DEFAULT USES params... |
def safe_size(source): """ READ THE source UP TO SOME LIMIT, THEN COPY TO A FILE IF TOO BIG RETURN A str() OR A FileString() """ if source is None: return None total_bytes = 0 bytes = [] b = source.read(MIN_READ_SIZE) while b: total_bytes += len(b) bytes.append(b) if total_bytes > MAX_STRING_SIZE: try: data = FileStrin... |
def compressed_bytes2ibytes(compressed, size): """ CONVERT AN ARRAY OF BYTES TO A BYTE-BLOCK GENERATOR USEFUL IN THE CASE WHEN WE WANT TO LIMIT HOW MUCH WE FEED ANOTHER GENERATOR (LIKE A DECOMPRESSOR) """ decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS) for i in range(0, mo_math.ceiling(len(compressed), size), si... |
def ibytes2ilines(generator, encoding="utf8", flexible=False, closer=None): """ CONVERT A GENERATOR OF (ARBITRARY-SIZED) byte BLOCKS TO A LINE (CR-DELIMITED) GENERATOR :param generator: :param encoding: None TO DO NO DECODING :param closer: OPTIONAL FUNCTION TO RUN WHEN DONE ITERATING :return: """ decode = get_decoder(... |
def icompressed2ibytes(source): """ :param source: GENERATOR OF COMPRESSED BYTES :return: GENERATOR OF BYTES """ decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS) last_bytes_count = 0 # Track the last byte count, so we do not show too many debug lines bytes_count = 0 for bytes_ in source: try: data = decompressor.... |
def scompressed2ibytes(stream): """ :param stream: SOMETHING WITH read() METHOD TO GET MORE BYTES :return: GENERATOR OF UNCOMPRESSED BYTES """ def more(): try: while True: bytes_ = stream.read(4096) if not bytes_: return yield bytes_ except Exception as e: Log.error("Problem iterating through stream", cause=e) finally:... |
def sbytes2ilines(stream, encoding="utf8", closer=None): """ CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS TO A LINE (CR-DELIMITED) GENERATOR """ def read(): try: while True: bytes_ = stream.read(4096) if not bytes_: return yield bytes_ except Exception as e: Log.error("Problem iterating throug... |
def get_decoder(encoding, flexible=False): """ RETURN FUNCTION TO PERFORM DECODE :param encoding: STRING OF THE ENCODING :param flexible: True IF YOU WISH TO TRY OUR BEST, AND KEEP GOING :return: FUNCTION """ if encoding == None: def no_decode(v): return v return no_decode elif flexible: def do_decode1(v): return v.dec... |
def setup_app(command, conf, vars): """Place any commands to setup tg2raptorized here""" load_environment(conf.global_conf, conf.local_conf) setup_schema(command, conf, vars) bootstrap.bootstrap(command, conf, vars) |
def visit_Identifier(self, node): """Mangle names.""" if not self._is_mangle_candidate(node): return name = node.value symbol = node.scope.resolve(node.value) if symbol is None: self.free_variables.add(name) |
def from_name(cls, name, all_fallback=True): """Gets a vocation filter from a vocation's name. Parameters ---------- name: :class:`str` The name of the vocation. all_fallback: :class:`bool` Whether to return :py:attr:`ALL` if no match is found. Otherwise, ``None`` will be returned. Returns ------- VocationFilter, optio... |
def connect(*args, **kwargs): """Connect to the database. Passes arguments along to ``pymongo.connection.Connection`` unmodified. The Connection returned by this proxy method will be used by micromongo for all of its queries. Micromongo will alter the behavior of this conneciton object in some subtle ways; if you want ... |
def new(cls, *args, **kwargs): """Create a new instance of this model based on its spec and either a map or the provided kwargs.""" new = cls(make_default(getattr(cls, 'spec', {}))) new.update(args[0] if args and not kwargs else kwargs) return new |
def find_one(cls, *args, **kwargs): """Run a find_one on this model's collection. The arguments to ``Model.find_one`` are the same as to ``pymongo.Collection.find_one``.""" database, collection = cls._collection_key.split('.') return current()[database][collection].find_one(*args, **kwargs) |
def save(self): """Save this object to the database. Behaves very similarly to whatever collection.save(document) would, ie. does upserts on _id presence. If methods ``pre_save`` or ``post_save`` are defined, those are called. If there is a spec document, then the document is validated against it after the ``pre_save``... |
def write(self, msg): """ 接收消息 :param msg: :return: """ self.app.events.before_response(self, msg) for bp in self.app.blueprints: bp.events.before_app_response(self, msg) try: self.child_output.put_nowait(msg) result = True except: logger.error('exc occur. msg: %r', msg, exc_info=True) result = False for bp in self.app... |
def _handle_request(self, request): """ 出现任何异常的时候,服务器不再主动关闭连接 """ if not request.is_valid: return False if not request.view_func: logger.error('cmd invalid. request: %s' % request) request.write(dict(ret=constants.RET_INVALID_CMD)) return False if not self.app.got_first_request: self.app.got_first_request = True self.a... |
def _handle_signals(self): """ 因为主进程的reactor重新处理了SIGINT,会导致子进程也会响应,改为SIG_IGN之后,就可以保证父进程先退出,之后再由父进程term所有的子进程 :return: """ signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.signal(signal.SIGINT, signal.SIG_IGN) |
def apply(query, collection=None): """Enhance the query restricting not permitted collections. Get the permitted restricted collection for the current user from the user_info object and all the restriced collections from the restricted_collection_cache. """ if not collection: return query result_tree = create_collectio... |
def __remove_args_first_item(self): """ # Todo: finding a better solution This is a dirty solution Because the first argument of inspectors' args will be itself For current implementation, it should be ignore """ if len(self.args) > 0: new_args_list = [] for item in self.args: if len(item) > 0 and self.obj == item[0]._... |
def lastCall(self): #pylint: disable=invalid-name """ Return: SpyCall object for this spy's most recent call """ last_index = len(super(SinonSpy, self)._get_wrapper().call_list) - 1 return self.getCall(last_index) |
def calledBefore(self, spy): #pylint: disable=invalid-name """ Compares the order in which two spies were called E.g. spy_a() spy_b() spy_a.calledBefore(spy_b) # True spy_b.calledBefore(spy_a) # False spy_a() spy_b.calledBefore(spy_a) # True Args: a Spy to compare with Return: Boolean True if this spy's first call was ... |
def calledWith(self, *args, **kwargs): #pylint: disable=invalid-name """ Determining whether args/kwargs are called previously Eg. f(1, 2, 3) spy.calledWith(1, 2) will return True, because they are called partially f(a=1, b=2, c=3) spy.calledWith(a=1, b=3) will return True, because they are called partially Return: Boo... |
def alwaysCalledWith(self, *args, **kwargs): #pylint: disable=invalid-name """ Determining whether args/kwargs are the ONLY args/kwargs called previously Eg. f(1, 2, 3) f(1, 2, 3) spy.alwaysCalledWith(1, 2) will return True, because they are the ONLY called args f(1, 3) spy.alwaysCalledWith(1) will return True, because... |
def calledWithExactly(self, *args, **kwargs): #pylint: disable=invalid-name """ Determining whether args/kwargs are fully matched args/kwargs called previously Eg. f(1, 2, 3) spy.alwaysCalledWith(1, 2) will return False, because they are not fully matched spy.alwaysCalledWith(1, 2, 3) will return True, because they are... |
def alwaysCalledWithExactly(self, *args, **kwargs): #pylint: disable=invalid-name """ Determining whether args/kwargs are the ONLY fully matched args/kwargs called previously Eg. f(1, 2, 3) spy.alwaysCalledWith(1, 2, 3) will return True, because they are fully matched f(1, 2, 4) spy.alwaysCalledWith(1, 2, 4) will retur... |
def calledWithMatch(self, *args, **kwargs): #pylint: disable=invalid-name """ Determining whether args/kwargs are matched args/kwargs called previously Handle each arg/kwarg as a SinonMatcher Eg. f(1, 2, 3) spy.alwaysCalledWith(1, 2, 3) will return True, because they are fully matched spy.alwaysCalledWith(int) will ret... |
self.__remove_args_first_item() if args and kwargs: return (uch.tuple_partial_cmp(args, self.args, self.__get_func) and uch.dict_partial_cmp(kwargs, self.kwargs, self.__get_func)) elif args: return uch.tuple_partial_cmp(args, self.args, self.__get_func) elif kwargs: return uch.dict_partial_cmp(kwargs, self.kwargs, self... |
def alwaysCalledWithMatch(self, *args, **kwargs): #pylint: disable=invalid-name """ Determining whether args/kwargs are the ONLY matched args/kwargs called previously Handle each arg/kwarg as a SinonMatcher Return: Boolean """ self.__remove_args_first_item() alist, klist, gfunc = self.args, self.kwargs, self.__get_func... |
def threw(self, error_type=None): """ Determining whether the exception is thrown Args: error_type: None: checking without specified exception Specified Exception Return: Boolean """ if not error_type: return True if len(self.exceptions) > 0 else False else: return uch.obj_in_list(self.exceptions, error_type) |
def alwaysThrew(self, error_type=None): #pylint: disable=invalid-name """ Determining whether the specified exception is the ONLY thrown exception Args: error_type: None: checking without specified exception Specified Exception Return: Boolean """ if self.callCount == 0: return False if not error_type: return True if l... |
def reset(self): """ Reseting wrapped function """ super(SinonSpy, self).unwrap() super(SinonSpy, self).wrap2spy() |
def getCall(self, n): #pylint: disable=invalid-name """ Args: n: integer (index of function call) Return: SpyCall object (or None if the index is not valid) """ call_list = super(SinonSpy, self)._get_wrapper().call_list if n >= 0 and n < len(call_list): call = call_list[n] call.proxy = weakref.proxy(self) return call e... |
def b64decode(foo, *args): 'Only here for consistency with the above.' if isinstance(foo, str): foo = foo.encode('utf8') return base64.b64decode(foo, *args) |
def assert_type_and_length(varname, var, T, L = None, minL = None, maxL = None): 'Facilitates simultaneous or one-line type/length checks.' if not isinstance(var, T): raise TypeError("Variable '{}' is supposed to be type '{}' but is '{}'".format(varname, T, type(var))) if isinstance(L, int): if not L == len(var): raise... |
def from_passphrase(cls, email, passphrase): """ This performs key derivation from an email address and passphrase according to the miniLock specification. Specifically, the passphrase is digested with a standard blake2s 32-bit digest, then it is passed through scrypt with the email address as salt value using N = 217,... |
def from_id(cls, id): """ This decodes an ID to a public key and verifies the checksum byte. ID structure in miniLock is the base58 encoded form of the public key appended with a single-byte digest from blake2s of the public key, as a simple check-sum. """ decoded = cls.ensure_bytes(base58.b58decode(id)) assert_type_an... |
def ephemeral(cls): """ Creates a new ephemeral key constructed using a raw 32-byte string from urandom. Ephemeral keys are used once for each encryption task and are then discarded; they are not intended for long-term or repeat use. """ private_key = nacl.public.PrivateKey(os.urandom(32)) return cls(private_key.public... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.