Search is not available for this dataset
text
stringlengths
75
104k
def loadByteArray(self, page, returnError): """Must be overridden. Must return a string with the loaded data.""" returnError.contents.value = self.IllegalStateError raise NotImplementedError("You must override this method.") return ''
def insert(self, obj, coordinates): """Inserts an item into the index with the given coordinates. :param obj: object Any object. :param coordinates: sequence or array This may be an object that satisfies the numpy array protocol, providing the index's dimens...
def intersection(self, coordinates, bbox=False): """Return ids or objects in the index that intersect the given coordinates. :param coordinates: sequence or array This may be an object that satisfies the numpy array protocol, providing the index's dimension * 2 coordinat...
def delete(self, obj, coordinates): """Deletes the item from the container within the specified coordinates. :param obj: object Any object. :param coordinates: sequence or array Dimension * 2 coordinate pairs, representing the min and max coordinates...
def check_return(result, func, cargs): "Error checking for Error calls" if result != 0: s = rt.Error_GetLastErrorMsg().decode() msg = 'LASError in "%s": %s' % \ (func.__name__, s) rt.Error_Reset() raise RTreeError(msg) return True
def check_void(result, func, cargs): "Error checking for void* returns" if not bool(result): s = rt.Error_GetLastErrorMsg().decode() msg = 'Error in "%s": %s' % (func.__name__, s) rt.Error_Reset() raise RTreeError(msg) return result
def check_void_done(result, func, cargs): "Error checking for void* returns that might be empty with no error" if rt.Error_GetErrorCount(): s = rt.Error_GetLastErrorMsg().decode() msg = 'Error in "%s": %s' % (func.__name__, s) rt.Error_Reset() raise RTreeError(msg) return res...
def load(self): """ Attempt an import of the specified application """ if isinstance(self.application, str): return util.import_app(self.application) else: return self.application
def init_app(self, app): """Initializes the Flask application with Common.""" if not hasattr(app, 'extensions'): app.extensions = {} if 'common' in app.extensions: raise RuntimeError("Flask-Common extension already initialized") app.extensions['common'] = self ...
def serve(self, workers=None, **kwargs): """Serves the Flask application.""" if self.app.debug: print(crayons.yellow('Booting Flask development server...')) self.app.run() else: print(crayons.yellow('Booting Gunicorn...')) # Start the web server....
def to_native(self, value): """For djangorestframework <=2.3.14""" context_request = None if self.context: context_request = self.context.get('request', None) return build_versatileimagefield_url_set( value, self.sizes, request=context_requ...
def crop_on_centerpoint(self, image, width, height, ppoi=(0.5, 0.5)): """ Return a PIL Image instance cropped from `image`. Image has an aspect ratio provided by dividing `width` / `height`), sized down to `width`x`height`. Any 'excess pixels' are trimmed away in respect to the ...
def process_image(self, image, image_format, save_kwargs, width, height): """ Return a BytesIO instance of `image` cropped to `width` and `height`. Cropping will first reduce an image down to its longest side and then crop inwards centered on the Primary Point of I...
def process_image(self, image, image_format, save_kwargs, width, height): """ Return a BytesIO instance of `image` that fits in a bounding box. Bounding box dimensions are `width`x`height`. """ imagefile = BytesIO() image.thumbnail( (wid...
def process_image(self, image, image_format, save_kwargs={}): """Return a BytesIO instance of `image` with inverted colors.""" imagefile = BytesIO() inv_image = ImageOps.invert(image) inv_image.save( imagefile, **save_kwargs ) return imagefile
def to_python(self, data): """Ensure data is prepped properly before handing off to ImageField.""" if data is not None: if hasattr(data, 'open'): data.open() return super(VersatileImageFormField, self).to_python(data)
def process_placeholder_image(self): """ Process the field's placeholder image. Ensures the placeholder image has been saved to the same storage class as the field in a top level folder with a name specified by settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name'] ...
def pre_save(self, model_instance, add): """Return field's value just before saving.""" file = super(VersatileImageField, self).pre_save(model_instance, add) self.update_ppoi_field(model_instance) return file
def update_ppoi_field(self, instance, *args, **kwargs): """ Update field's ppoi field, if defined. This method is hooked up this field's pre_save method to update the ppoi immediately before the model instance (`instance`) it is associated with is saved. This field's pp...
def save_form_data(self, instance, data): """ Handle data sent from MultiValueField forms that set ppoi values. `instance`: The model instance that is being altered via a form `data`: The data sent from the form to this field which can be either: * `None`: This is unset data fro...
def formfield(self, **kwargs): """Return a formfield.""" # This is a fairly standard way to set up some defaults # while letting the caller override them. defaults = {} if self.ppoi_field: defaults['form_class'] = SizedImageCenterpointClickDjangoAdminField if ...
def value_to_string(self, obj): """Prepare field for serialization.""" if DJANGO_VERSION > (1, 9): value = self.value_from_object(obj) else: value = self._get_val_from_obj(obj) return self.get_prep_value(value)
def cli_progress_bar(start, end, bar_length=50): """ Prints out a Yum-style progress bar (via sys.stdout.write). `start`: The 'current' value of the progress bar. `end`: The '100%' value of the progress bar. `bar_length`: The size of the overall progress bar. Example output with start=20, end=1...
def _prewarm_versatileimagefield(size_key, versatileimagefieldfile): """ Returns a 2-tuple: 0: bool signifying whether the image was successfully pre-warmed 1: The url of the successfully created image OR the path on storage of the image that was not able to be successfully cr...
def warm(self): """ Returns a 2-tuple: [0]: Number of images successfully pre-warmed [1]: A list of paths on the storage class associated with the VersatileImageField field being processed by `self` of files that could not be successfully seeded. """ ...
def autodiscover(): """ Discover versatileimagefield.py modules. Iterate over django.apps.get_app_configs() and discover versatileimagefield.py modules. """ from importlib import import_module from django.apps import apps from django.utils.module_loading import module_has_submodule ...
def register_sizer(self, attr_name, sizedimage_cls): """ Register a new SizedImage subclass (`sizedimage_cls`). To be used via the attribute (`attr_name`). """ if attr_name.startswith( '_' ) or attr_name in self.unallowed_sizer_names: raise Unallo...
def unregister_sizer(self, attr_name): """ Unregister the SizedImage subclass currently assigned to `attr_name`. If a SizedImage subclass isn't already registered to `attr_name` NotRegistered will raise. """ if attr_name not in self._sizedimage_registry: rais...
def register_filter(self, attr_name, filterimage_cls): """ Register a new FilteredImage subclass (`filterimage_cls`). To be used via the attribute (filters.`attr_name`) """ if attr_name.startswith('_'): raise UnallowedFilterName( '`%s` is an unallowed...
def unregister_filter(self, attr_name): """ Unregister the FilteredImage subclass currently assigned to attr_name. If a FilteredImage subclass isn't already registered to filters. `attr_name` NotRegistered will raise. """ if attr_name not in self._filter_registry: ...
def url(self): """ Return the appropriate URL. URL is constructed based on these field conditions: * If empty (not `self.name`) and a placeholder is defined, the URL to the placeholder is returned. * Otherwise, defaults to vanilla ImageFieldFile behavior. ...
def ppoi(self, value): """Primary Point of Interest (ppoi) setter.""" ppoi = validate_ppoi( value, return_converted_tuple=True ) if ppoi is not False: self._ppoi_value = ppoi self.build_filters_and_sizers(ppoi, self.create_on_demand)
def build_filters_and_sizers(self, ppoi_value, create_on_demand): """Build the filters and sizers for a field.""" name = self.name if not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary( name, ...
def get_filtered_root_folder(self): """Return the location where filtered images are stored.""" folder, filename = os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '')
def get_sized_root_folder(self): """Return the location where sized images are stored.""" folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '')
def get_filtered_sized_root_folder(self): """Return the location where filtered + sized images are stored.""" sized_root_folder = self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME )
def delete_matching_files_from_storage(self, root_folder, regex): """ Delete files in `root_folder` which match `regex` before file ext. Example values: * root_folder = 'foo/' * self.name = 'bar.jpg' * regex = re.compile('-baz') Result: ...
def validate_ppoi_tuple(value): """ Validates that a tuple (`value`)... ...has a len of exactly 2 ...both values are floats/ints that are greater-than-or-equal-to 0 AND less-than-or-equal-to 1 """ valid = True while valid is True: if len(value) == 2 and isinstance(value, tuple...
def validate_ppoi(value, return_converted_tuple=False): """ Converts, validates and optionally returns a string with formatting: '%(x_axis)dx%(y_axis)d' into a two position tuple. If a tuple is passed to `value` it is also validated. Both x_axis and y_axis must be floats or ints greater than 0...
def preprocess(self, image, image_format): """ Preprocess an image. An API hook for image pre-processing. Calls any image format specific pre-processors (if defined). I.E. If `image_format` is 'JPEG', this method will look for a method named `preprocess_JPEG`, if found `...
def preprocess_GIF(self, image, **kwargs): """ Receive a PIL Image instance of a GIF and return 2-tuple. Args: * [0]: Original Image instance (passed to `image`) * [1]: Dict with a transparency key (to GIF transparency layer) """ if 'transparency' in imag...
def preprocess_JPEG(self, image, **kwargs): """ Receive a PIL Image instance of a JPEG and returns 2-tuple. Args: * [0]: Image instance, converted to RGB * [1]: Dict with a quality key (mapped to the value of `QUAL` as defined by the `VERSATILEIMAGEFIE...
def retrieve_image(self, path_to_image): """Return a PIL Image instance stored at `path_to_image`.""" image = self.storage.open(path_to_image, 'rb') file_ext = path_to_image.rsplit('.')[-1] image_format, mime_type = get_image_metadata_from_file_ext(file_ext) return ( ...
def save_image(self, imagefile, save_path, file_ext, mime_type): """ Save an image to self.storage at `save_path`. Arguments: `imagefile`: Raw image data, typically a BytesIO instance. `save_path`: The path within self.storage where the image should ...
def ppoi_as_str(self): """Return PPOI value as a string.""" return "%s__%s" % ( str(self.ppoi[0]).replace('.', '-'), str(self.ppoi[1]).replace('.', '-') )
def create_resized_image(self, path_to_image, save_path_on_storage, width, height): """ Create a resized image. `path_to_image`: The path to the image with the media directory to resize. If `None`, the VERSATILEIMAGE...
def render(self, name, value, attrs=None, renderer=None): """ Render the widget as an HTML string. Overridden here to support Django < 1.11. """ if self.has_template_widget_rendering: return super(ClearableFileInputWithImagePreview, self).render( name...
def get_context(self, name, value, attrs): """Get the context to render this widget with.""" if self.has_template_widget_rendering: context = super(ClearableFileInputWithImagePreview, self).get_context(name, value, attrs) else: # Build the context manually. co...
def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" attrs = base_attrs.copy() if extra_attrs is not None: attrs.update(extra_attrs) return attrs
def get_resized_filename(filename, width, height, filename_key): """ Return the 'resized filename' (according to `width`, `height` and `filename_key`) in the following format: `filename`-`filename_key`-`width`x`height`.ext """ try: image_name, ext = filename.rsplit('.', 1) except Val...
def get_resized_path(path_to_image, width, height, filename_key, storage): """ Return a `path_to_image` location on `storage` as dictated by `width`, `height` and `filename_key` """ containing_folder, filename = os.path.split(path_to_image) resized_filename = get_resized_fi...
def get_filtered_filename(filename, filename_key): """ Return the 'filtered filename' (according to `filename_key`) in the following format: `filename`__`filename_key`__.ext """ try: image_name, ext = filename.rsplit('.', 1) except ValueError: image_name = filename ex...
def get_filtered_path(path_to_image, filename_key, storage): """ Return the 'filtered path' """ containing_folder, filename = os.path.split(path_to_image) filtered_filename = get_filtered_filename(filename, filename_key) path_to_return = os.path.join(*[ containing_folder, VERSAT...
def validate_versatileimagefield_sizekey_list(sizes): """ Validate a list of size keys. `sizes`: An iterable of 2-tuples, both strings. Example: [ ('large', 'url'), ('medium', 'crop__400x400'), ('small', 'thumbnail__100x100') ] """ try: for key, size_key in s...
def get_url_from_image_key(image_instance, image_key): """Build a URL from `image_key`.""" img_key_split = image_key.split('__') if 'x' in img_key_split[-1]: size_key = img_key_split.pop(-1) else: size_key = None img_url = reduce(getattr, img_key_split, image_instance) if size_ke...
def build_versatileimagefield_url_set(image_instance, size_set, request=None): """ Return a dictionary of urls corresponding to size_set - `image_instance`: A VersatileImageFieldFile - `size_set`: An iterable of 2-tuples, both strings. Example: [ ('large', 'url'), ('mediu...
def get_rendition_key_set(key): """ Retrieve a validated and prepped Rendition Key Set from settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS """ try: rendition_key_set = IMAGE_SETS[key] except KeyError: raise ImproperlyConfigured( "No Rendition Key Set exists at " ...
def format_instruction(insn): """ Takes a raw `Instruction` and translates it into a human readable text representation. As of writing, the text representation for WASM is not yet standardized, so we just emit some generic format. """ text = insn.op.mnemonic if not insn.imm: return ...
def format_function( func_body, func_type=None, indent=2, format_locals=True, ): """ Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string representation of the function line by line. The function type is required for formatting function parameter and return value ...
def decode_bytecode(bytecode): """Decodes raw bytecode, yielding `Instruction`s.""" bytecode_wnd = memoryview(bytecode) while bytecode_wnd: opcode_id = byte2int(bytecode_wnd[0]) opcode = OPCODE_MAP[opcode_id] if opcode.imm_struct is not None: offs, imm, _ = opcode.imm_st...
def decode_module(module, decode_name_subsections=False): """Decodes raw WASM modules, yielding `ModuleFragment`s.""" module_wnd = memoryview(module) # Read & yield module header. hdr = ModuleHeader() hdr_len, hdr_data, _ = hdr.from_raw(None, module_wnd) yield ModuleFragment(hdr, hdr_data) ...
def deprecated_func(func): """Deprecates a function, printing a warning on the first usage.""" # We use a mutable container here to work around Py2's lack of # the `nonlocal` keyword. first_usage = [True] @functools.wraps(func) def wrapper(*args, **kwargs): if first_usage[0]: ...
def send_action(self, action, as_list=None, **kwargs): """Send an :class:`~panoramisk.actions.Action` to the server: :param action: an Action or dict with action name and parameters to send :type action: Action or dict or Command :param as_list: If True, the actio...
def send_command(self, command, as_list=False): """Send a :class:`~panoramisk.actions.Command` to the server:: manager = Manager() resp = manager.send_command('http show status') Return a response :class:`~panoramisk.message.Message`. See https://wiki.asterisk.org/wiki/...
def send_agi_command(self, channel, command, as_list=False): """Send a :class:`~panoramisk.actions.Command` to the server: :param channel: Channel name where to launch command. Ex: 'SIP/000000-00000a53' :type channel: String :param command: command to launch. Ex: 'GET VAR...
def connect(self): """connect to the server""" if self.loop is None: # pragma: no cover self.loop = asyncio.get_event_loop() t = asyncio.Task( self.loop.create_connection( self.config['protocol_factory'], self.config['host'], self.config['...
def register_event(self, pattern, callback=None): """register an event. See :class:`~panoramisk.message.Message`: .. code-block:: python >>> def callback(manager, event): ... print(manager, event) >>> manager = Manager() >>> manager.register_event('M...
def close(self): """Close the connection""" if self.pinger: self.pinger.cancel() self.pinger = None if getattr(self, 'protocol', None): self.protocol.close()
def send_command(self, command): """Send a command for FastAGI request: :param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds' :type command: String :Example: :: @asyncio.coroutine def call_waiting(request): ...
def _read_result(self): """Parse read a response from the AGI and parse it. :return dict: The AGI response parsed into a dict. """ response = yield from self.reader.readline() return parse_agi_result(response.decode(self.encoding)[:-1])
def add_route(self, path, endpoint): """Add a route for FastAGI requests: :param path: URI to answer. Ex: 'calls/start' :type path: String :param endpoint: command to launch. Ex: start :type endpoint: callable :Example: :: @asyncio.coroutine ...
def del_route(self, path): """Delete a route for FastAGI requests: :param path: URI to answer. Ex: 'calls/start' :type path: String :Example: :: @asyncio.coroutine def start(request): print('Receive a FastAGI request') p...
def handler(self, reader, writer): """AsyncIO coroutine handler to launch socket listening. :Example: :: @asyncio.coroutine def start(request): print('Receive a FastAGI request') print(['AGI variables:', request.headers]) fa...
def parse_agi_result(line): """Parse AGI results using Regular expression. AGI Result examples:: 100 result=0 Trying... 200 result=0 200 result=-1 200 result=132456 200 result= (timeout) 510 Invalid or unknown command 520-Invalid command syntax. Pr...
def agi_code_check(code=None, response=None, line=None): """ Check the AGI code and return a dict to help on error handling. """ code = int(code) response = response or "" result = {'status_code': code, 'result': ('', ''), 'msg': ''} if code == 100: result['msg'] = line elif code...
def reset(cls, uid=None): """Mostly used for unit testing. Allow to use a static uuid and reset all counter""" for instance in cls.instances: if uid: instance.uid = uid instance.generator = instance.get_generator()
def get_instances(self): """Mostly used for debugging""" return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__, i.prefix, self.uid) for i in self.instances]
def success(self): """return True if a response status is Success or Follows: .. code-block:: python >>> resp = Message({'Response': 'Success'}) >>> print(resp.success) True >>> resp['Response'] = 'Failed' >>> resp.success False ...
def getdict(self, key): """Convert a multi values header to a case-insensitive dict: .. code-block:: python >>> resp = Message({ ... 'Response': 'Success', ... 'ChanVariable': [ ... 'FROM_DID=', 'SIPURI=sip:42@10.10.10.1:4242'], ...
def run_setup(script_name, script_args=None, stop_after="run"): """Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or t...
def get_data(path): """ Returns data from a package directory. 'path' should be an absolute path. """ # Run the imported setup to get the metadata. with FakeContext(path): with SetupMonkey() as sm: try: distro = run_setup('setup.py', stop_after='config') ...
def get_primary_keys(model): """Get primary key properties for a SQLAlchemy model. :param model: SQLAlchemy model class """ mapper = model.__mapper__ return [mapper.get_property_by_column(column) for column in mapper.primary_key]
def _deserialize(self, value, *args, **kwargs): """Deserialize a serialized value to a model instance. If the parent schema is transient, create a new (transient) instance. Otherwise, attempt to find an existing instance in the database. :param value: The value to deserialize. "...
def _get_existing_instance(self, query, value): """Retrieve the related object from an existing instance in the DB. :param query: A SQLAlchemy `Query <sqlalchemy.orm.query.Query>` object. :param value: The serialized value to mapto an existing instance. :raises NoResultFound: if there i...
def _add_column_kwargs(self, kwargs, column): """Add keyword arguments to kwargs (in-place) based on the passed in `Column <sqlalchemy.schema.Column>`. """ if column.nullable: kwargs["allow_none"] = True kwargs["required"] = not column.nullable and not _has_default(co...
def _add_relationship_kwargs(self, kwargs, prop): """Add keyword arguments to kwargs (in-place) based on the passed in relationship `Property`. """ nullable = True for pair in prop.local_remote_pairs: if not pair[0].nullable: if prop.uselist is True: ...
def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls): """Updates declared fields with fields converted from the SQLAlchemy model passed as the `model` class Meta option. """ opts = klass.opts Converter = opts.model_converter converter = Converter(sc...
def get_instance(self, data): """Retrieve an existing record by primary key(s). If the schema instance is transient, return None. :param data: Serialized data to inform lookup. """ if self.transient: return None props = get_primary_keys(self.opts.model) ...
def make_instance(self, data): """Deserialize data to an instance of the model. Update an existing row if specified in `self.instance` or loaded by primary key(s) in the data; else create a new row. :param data: Data to deserialize. """ instance = self.instance or self.g...
def load(self, data, session=None, instance=None, transient=False, *args, **kwargs): """Deserialize data to internal representation. :param session: Optional SQLAlchemy session. :param instance: Optional existing instance to modify. :param transient: Optional switch to allow transient i...
def _split_model_kwargs_association(self, data): """Split serialized attrs to ensure association proxies are passed separately. This is necessary for Python < 3.6.0, as the order in which kwargs are passed is non-deterministic, and associations must be parsed by sqlalchemy after their i...
def gc(): """Deletes old stellar tables that are not used anymore""" def after_delete(database): click.echo("Deleted table %s" % database) app = get_app() upgrade_from_old_version(app) app.delete_orphan_snapshots(after_delete)
def snapshot(name): """Takes a snapshot of the database""" app = get_app() upgrade_from_old_version(app) name = name or app.default_snapshot_name if app.get_snapshot(name): click.echo("Snapshot with name %s already exists" % name) sys.exit(1) else: def before_copy(table_...
def list(): """Returns a list of snapshots""" snapshots = get_app().get_snapshots() click.echo('\n'.join( '%s: %s' % ( s.snapshot_name, humanize.naturaltime(datetime.utcnow() - s.created_at) ) for s in snapshots ))
def restore(name): """Restores the database from a snapshot""" app = get_app() if not name: snapshot = app.get_latest_snapshot() if not snapshot: click.echo( "Couldn't find any snapshots for project %s" % load_config()['project_name'] ...
def remove(name): """Removes a snapshot""" app = get_app() snapshot = app.get_snapshot(name) if not snapshot: click.echo("Couldn't find snapshot %s" % name) sys.exit(1) click.echo("Deleting snapshot %s" % name) app.remove_snapshot(snapshot) click.echo("Deleted")
def rename(old_name, new_name): """Renames a snapshot""" app = get_app() snapshot = app.get_snapshot(old_name) if not snapshot: click.echo("Couldn't find snapshot %s" % old_name) sys.exit(1) new_snapshot = app.get_snapshot(new_name) if new_snapshot: click.echo("Snapshot...
def replace(name): """Replaces a snapshot""" app = get_app() snapshot = app.get_snapshot(name) if not snapshot: click.echo("Couldn't find snapshot %s" % name) sys.exit(1) app.remove_snapshot(snapshot) app.create_snapshot(name) click.echo("Replaced snapshot %s" % name)
def init(): """Initializes Stellar configuration.""" while True: url = click.prompt( "Please enter the url for your database.\n\n" "For example:\n" "PostgreSQL: postgresql://localhost:5432/\n" "MySQL: mysql+pymysql://root@localhost/" ) if u...
def on_epoch_end(self) -> None: 'Updates indexes after each epoch for shuffling' self.indexes = np.arange(self.nrows) if self.shuffle: np.random.shuffle(self.indexes)