docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Returns a generator that yields the frames from start to stop, inclusive. In other words it adds or subtracts a frame, as necessary, to return the stop value as well, if the stepped range would touch that value. Args: start (int): stop (int): step (int): Note that the sign will be i...
def xfrange(start, stop, step=1, maxSize=-1): if start <= stop: stop, step = stop + 1, abs(step) else: stop, step = stop - 1, -abs(step) if maxSize >= 0: size = lenRange(start, stop, step) if size > maxSize: raise exceptions.MaxSizeException( ...
415,520
Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used. Args: seen (set): either an empty set, or the set of things already seen *iterables: one or more iterable lists to chain together Returns: ...
def unique(seen, *iterables): _add = seen.add # return a generator of the unique items and the set of the seen items # the seen set will mutate when the generator is iterated over return (i for i in chain(*iterables) if i not in seen and not _add(i))
415,521
Set a new directory name for the sequence. Args: dirname (str): the new directory name
def setDirname(self, dirname): # Make sure the dirname always ends in # a path separator character sep = utils._getPathSep(dirname) if not dirname.endswith(sep): dirname += sep self._dir = utils.asString(dirname)
415,527
Set new padding characters for the sequence. i.e. "#" or "@@@" or '%04d', or an empty string to disable range formatting. Args: padding (str): sequence padding to set
def setPadding(self, padding): self._pad = padding self._zfill = self.__class__.getPaddingNum(self._pad)
415,528
Set a new file extension for the sequence. Note: A leading period will be added if none is provided. Args: ext (str): the new file extension
def setExtension(self, ext): if ext[0] != ".": ext = "." + ext self._ext = utils.asString(ext)
415,529
Deprecated: use :meth:`setExtension`. Args: ext (str):
def setExtention(self, ext): import warnings msg = "the setExtention method is deprecated, please use setExtension" warnings.warn(msg) self.setExtension(ext)
415,530
Return a path go the given frame in the sequence. Integer or string digits are treated as a frame number and padding is applied, all other values are passed though. Examples: >>> seq.frame(1) /foo/bar.0001.exr >>> seq.frame("#") /foo/bar.#.exr ...
def frame(self, frame): try: zframe = str(int(frame)).zfill(self._zfill) except ValueError: zframe = frame # There may have been no placeholder for frame IDs in # the sequence, in which case we don't want to insert # a frame ID if self._...
415,531
Yield the discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes you already know that. Args: paths (list[str]): a list of paths Yields: :obj:`FileSequence`:
def yield_sequences_in_list(paths): seqs = {} _check = DISK_RE.match for match in ifilter(None, imap(_check, imap(utils.asString, paths))): dirname, basename, frame, ext = match.groups() if not basename and not ext: continue key = (di...
415,535
Yield only path elements from iterable which have a frame padding that matches the given target padding number Args: iterable (collections.Iterable): num (int): Yields: str:
def _filterByPaddingNum(cls, iterable, num): _check = DISK_RE.match for item in iterable: # Add a filter for paths that don't match the frame # padding of a given number matches = _check(item) if not matches: if num <= 0: ...
415,538
Given a supported group of padding characters, return the amount of padding. Args: chars (str): a supported group of padding characters Returns: int: Raises: ValueError: if unsupported padding character is detected
def getPaddingNum(chars): match = PRINTF_SYNTAX_PADDING_RE.match(chars) if match: return int(match.group(1)) try: return sum([PAD_MAP[char] for char in chars]) except KeyError: msg = "Detected an unsupported padding character: \"{}\"." ...
415,539
Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' '%04d' -> '#' Args: char...
def conformPadding(cls, chars): pad = chars if pad and pad[0] not in PAD_MAP: pad = cls.getPaddingChars(cls.getPaddingNum(pad)) return pad
415,540
Initialize the :class:`FrameSet` object. Args: frange (str or :class:`FrameSet`): the frame range as a string (ie "1-100x5") Raises: :class:`.ParseException`: if the frame range (or a portion of it) could not be parsed. :class:`fileseq.exceptions.Max...
def __new__(cls, *args, **kwargs): self = super(cls, FrameSet).__new__(cls, *args, **kwargs) return self
415,541
Build a :class:`FrameSet` from an iterable of frames. Args: frames (collections.Iterable): an iterable object containing frames as integers sort (bool): True to sort frames before creation, default is False Returns: :class:`FrameSet`:
def from_iterable(cls, frames, sort=False): return FrameSet(sorted(frames) if sort else frames)
415,543
Private method to simplify comparison operations. Args: other (:class:`FrameSet` or set or frozenset or or iterable): item to be compared Returns: :class:`FrameSet` Raises: :class:`NotImplemented`: if a comparison is impossible
def _cast_to_frameset(cls, other): if isinstance(other, FrameSet): return other try: return FrameSet(other) except Exception: return NotImplemented
415,544
Allows for de-serialization from a pickled :class:`FrameSet`. Args: state (tuple or str or dict): A string/dict can be used for backwards compatibility Raises: ValueError: if state is not an appropriate type
def __setstate__(self, state): if isinstance(state, tuple): # this is to allow unpickling of "3rd generation" FrameSets, # which are immutable and may be empty. self.__init__(state[0]) elif isinstance(state, basestring): # this is to allow unpickl...
415,547
Check if `self` <= `other` via a comparison of the contents. If `other` is not a :class:`FrameSet`, but is a set, frozenset, or is iterable, it will be cast to a :class:`FrameSet`. Args: other (:class:`FrameSet`): Also accepts an object that can be cast to a :class:`FrameSet` ...
def __le__(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented return self.items <= other.items
415,550
Check if `self` == `other` via a comparison of the hash of their contents. If `other` is not a :class:`FrameSet`, but is a set, frozenset, or is iterable, it will be cast to a :class:`FrameSet`. Args: other (:class:`FrameSet`): Also accepts an object that can be cast to a :c...
def __eq__(self, other): if not isinstance(other, FrameSet): if not hasattr(other, '__iter__'): return NotImplemented other = self.from_iterable(other) this = hash(self.items) | hash(self.order) that = hash(other.items) | hash(other.order) ...
415,551
Check if `self` != `other` via a comparison of the hash of their contents. If `other` is not a :class:`FrameSet`, but is a set, frozenset, or is iterable, it will be cast to a :class:`FrameSet`. Args: other (:class:`FrameSet`): Also accepts an object that can be cast to a :c...
def __ne__(self, other): is_equals = self == other if is_equals != NotImplemented: return not is_equals return is_equals
415,552
Check if `self` >= `other` via a comparison of the contents. If `other` is not a :class:`FrameSet`, but is a set, frozenset, or is iterable, it will be cast to a :class:`FrameSet`. Args: other (:class:`FrameSet`): Also accepts an object that can be cast to a :class:`FrameSet` ...
def __ge__(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented return self.items >= other.items
415,553
Overloads the ``&`` operator. Returns a new :class:`FrameSet` that holds only the frames `self` and `other` have in common. Note: The order of operations is irrelevant: ``(self & other) == (other & self)`` Args: other (:class:`FrameSet`): R...
def __and__(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented return self.from_iterable(self.items & other.items, sort=True)
415,555
Check if the contents of :class:self has no common intersection with the contents of :class:other. Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`
def isdisjoint(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented return self.items.isdisjoint(other.items)
415,556
Check if the contents of `self` is a subset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`
def issubset(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented return self.items <= other.items
415,557
Check if the contents of `self` is a superset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`
def issuperset(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented return self.items >= other.items
415,558
Returns a new :class:`FrameSet` with elements in `self` but not in `other`. Args: other (:class:`FrameSet`): or objects that can cast to :class:`FrameSet` Returns: :class:`FrameSet`:
def difference(self, *other): from_frozenset = self.items.difference(*map(set, other)) return self.from_iterable(from_frozenset, sort=True)
415,559
Returns a new :class:`FrameSet` that contains all the elements in either `self` or `other`, but not both. Args: other (:class:`FrameSet`): Returns: :class:`FrameSet`:
def symmetric_difference(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented from_frozenset = self.items.symmetric_difference(other.items) return self.from_iterable(from_frozenset, sort=True)
415,560
Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE Args: obj (numbers.Number or collection): Raises: :class:`fileseq.exceptions.MaxSizeException`:
def _maxSizeCheck(cls, obj): fail = False size = 0 if isinstance(obj, numbers.Number): if obj > constants.MAX_FRAME_SIZE: fail = True size = obj elif hasattr(obj, '__len__'): size = len(obj) fail = size > cons...
415,561
Return True if the given string is a frame range. Any padding characters, such as '#' and '@' are ignored. Args: frange (str): a frame range to test Returns: bool:
def isFrameRange(frange): # we're willing to trim padding characters from consideration # this translation is orders of magnitude faster than prior method frange = str(frange).translate(None, ''.join(PAD_MAP.keys())) if not frange: return True for part in fra...
415,562
Return the zero-padded version of the frame range string. Args: frange (str): a frame range to test zfill (int): Returns: str:
def padFrameRange(frange, zfill): def _do_pad(match): result = list(match.groups()) result[1] = pad(result[1], zfill) if result[4]: result[4] = pad(result[4], zfill) return ''.join((i for i in result if i)) return PAD_...
415,563
Internal method: parse a discrete frame range part. Args: frange (str): single part of a frame range as a string (ie "1-100x5") Returns: tuple: (start, end, modifier, chunk) Raises: :class:`.ParseException`: if the frame range can ...
def _parse_frange_part(frange): match = FRANGE_RE.match(frange) if not match: msg = 'Could not parse "{0}": did not match {1}' raise ParseException(msg.format(frange, FRANGE_RE.pattern)) start, end, modifier, chunk = match.groups() start = int(start) ...
415,564
Private method: builds a proper and padded frame range string. Args: start (int): first frame stop (int or None): last frame stride (int or None): increment zfill (int): width for zero padding Returns: str:
def _build_frange_part(start, stop, stride, zfill=0): if stop is None: return '' pad_start = pad(start, zfill) pad_stop = pad(stop, zfill) if stride is None or start == stop: return '{0}'.format(pad_start) elif abs(stride) == 1: return...
415,565
Converts a sequence of frames to a series of padded frame range strings. Args: frames (collections.Iterable): sequence of frames to process zfill (int): width for zero padding Yields: str:
def framesToFrameRanges(frames, zfill=0): _build = FrameSet._build_frange_part curr_start = None curr_stride = None curr_frame = None last_frame = None curr_count = 0 for curr_frame in frames: if curr_start is None: curr_start ...
415,566
Converts an iterator of frames into a frame range string. Args: frames (collections.Iterable): sequence of frames to process sort (bool): sort the sequence before processing zfill (int): width for zero padding compress (bool): remove any duplicates before...
def framesToFrameRange(frames, sort=True, zfill=0, compress=False): if compress: frames = unique(set(), frames) frames = list(frames) if not frames: return '' if len(frames) == 1: return pad(frames[0], zfill) if sort: frame...
415,567
Constructs a factory for building datastore emulator instances. Args: working_directory: path to a directory where temporary files will be stored emulator_zip: path to the emulator zip file java: path to a java executable
def __init__(self, working_directory, emulator_zip, java=None): self._working_directory = working_directory self._emulators = {} # Extract the emulator. zipped_file = zipfile.ZipFile(emulator_zip) if not os.path.isdir(self._working_directory): os.mkdir(self._working_directory) zippe...
416,302
Returns an existing emulator instance for the provided project_id. If an emulator instance doesn't yet exist, it creates one. Args: project_id: project ID Returns: a DatastoreEmulator
def Get(self, project_id): if project_id in self._emulators: return self._emulators[project_id] emulator = self.Create(project_id) self._emulators[project_id] = emulator return emulator
416,303
Creates an emulator instance. This method will wait for up to 'deadline' seconds for the emulator to start. Args: project_id: project ID start_options: a list of additional command-line options to pass to the emulator 'start' command deadline: number of seconds to wait for the ...
def Create(self, project_id, start_options=None, deadline=10): return DatastoreEmulator(self._emulator_cmd, self._working_directory, project_id, deadline, start_options)
416,304
Waits for the emulator to start. Args: deadline: deadline in seconds Returns: True if the emulator responds within the deadline, False otherwise.
def _WaitForStartup(self, deadline): start = time.time() sleep = 0.05 def Elapsed(): return time.time() - start while True: try: response, _ = self._http.request(self._host) if response.status == 200: logging.info('emulator responded after %f seconds', Elapse...
416,306
_call_method call the given RPC method over HTTP. It uses the given protobuf message request as the payload and returns the deserialized protobuf message response. Args: method: RPC method name to be called. req: protobuf message for the RPC request. resp_class: protobuf message class fo...
def _call_method(self, method, req, resp_class): payload = req.SerializeToString() headers = { 'Content-Type': 'application/x-protobuf', 'Content-Length': str(len(payload)), 'X-Goog-Api-Format-Version': '2' } response, content = self._http.request( '%s:%s' % (sel...
416,311
Get Datastore project endpoint from environment variables. Args: project_id: The Cloud project, defaults to the environment variable DATASTORE_PROJECT_ID. host: The Cloud Datastore API host to use. Returns: the endpoint to use, for example https://datastore.googleapis.com/v1/projects/my-pr...
def get_project_endpoint_from_env(project_id=None, host=None): project_id = project_id or os.getenv(_DATASTORE_PROJECT_ID_ENV) if not project_id: raise ValueError('project_id was not provided. Either pass it in ' 'directly or set DATASTORE_PROJECT_ID.') # DATASTORE_HOST is deprecated. ...
416,315
Set property value in the given datastore.Property proto message. Args: property_map: a string->datastore.Value protobuf map. name: name of the property. value: python object or datastore.Value. exclude_from_indexes: if the value should be exclude from indexes. None leaves indexing as is (def...
def set_property(property_map, name, value, exclude_from_indexes=None): set_value(property_map[name], value, exclude_from_indexes)
416,318
Gets the python object equivalent for the given value proto. Args: value_proto: datastore.Value proto message. Returns: the corresponding python object value. timestamps are converted to datetime, and datastore.Value is returned for blob_key_value.
def get_value(value_proto): field = value_proto.WhichOneof('value_type') if field in __native_value_types: return getattr(value_proto, field) if field == 'timestamp_value': return from_timestamp(value_proto.timestamp_value) if field == 'array_value': return [get_value(sub_value) for...
416,320
Convert datastore.Entity to a dict of property name -> datastore.Value. Args: entity_proto: datastore.Entity proto message. Usage: >>> get_property_dict(entity_proto) {'foo': {string_value='a'}, 'bar': {integer_value=2}} Returns: dict of entity properties.
def get_property_dict(entity_proto): return dict((p.key, p.value) for p in entity_proto.property)
416,321
Add ordering constraint for the given datastore.Query proto message. Args: query_proto: datastore.Query proto message. orders: list of propertype name string, default to ascending order and set descending if prefixed by '-'. Usage: >>> add_property_orders(query_proto, 'foo') # sort by foo asc ...
def add_property_orders(query_proto, *orders): for order in orders: proto = query_proto.order.add() if order[0] == '-': order = order[1:] proto.direction = query_pb2.PropertyOrder.DESCENDING else: proto.direction = query_pb2.PropertyOrder.ASCENDING proto.property.name = order
416,323
Set property filter contraint in the given datastore.Filter proto message. Args: filter_proto: datastore.Filter proto message name: property name op: datastore.PropertyFilter.Operation value: property value Returns: the same datastore.Filter. Usage: >>> set_property_filter(filter_proto,...
def set_property_filter(filter_proto, name, op, value): filter_proto.Clear() pf = filter_proto.property_filter pf.property.name = name pf.op = op set_value(pf.value, value) return filter_proto
416,325
Set composite filter contraint in the given datastore.Filter proto message. Args: filter_proto: datastore.Filter proto message op: datastore.CompositeFilter.Operation filters: vararg list of datastore.Filter Returns: the same datastore.Filter. Usage: >>> set_composite_filter(filter_proto, da...
def set_composite_filter(filter_proto, op, *filters): filter_proto.Clear() cf = filter_proto.composite_filter cf.op = op for f in filters: cf.filters.add().CopyFrom(f) return filter_proto
416,326
Convert microseconds from utc epoch to google.protobuf.timestamp. Args: micros: a long, number of microseconds since utc epoch. timestamp: a google.protobuf.timestamp.Timestamp to populate.
def micros_to_timestamp(micros, timestamp): seconds = long(micros / _MICROS_PER_SECOND) micro_remainder = micros % _MICROS_PER_SECOND timestamp.seconds = seconds timestamp.nanos = micro_remainder * _NANOS_PER_MICRO
416,327
Convert datetime to google.protobuf.Timestamp. Args: dt: a timezone naive datetime. timestamp: a google.protobuf.Timestamp to populate. Raises: TypeError: if a timezone aware datetime was provided.
def to_timestamp(dt, timestamp): if dt.tzinfo: # this is an "aware" datetime with an explicit timezone. Throw an error. raise TypeError('Cannot store a timezone aware datetime. ' 'Convert to UTC and store the naive datetime.') timestamp.seconds = calendar.timegm(dt.timetuple()) time...
416,328
Set new hyperparameters. Only the specified hyperparameters are modified, so any other hyperparameter keeps the value that had been previously given. If necessary, a new instance of the primitive is created. Args: hyperparameters (dict): Dictionary containing as keys the n...
def set_hyperparameters(self, hyperparameters): self._hyperparameters.update(hyperparameters) if self._class: LOGGER.debug('Creating a new primitive instance for %s', self.name) self.instance = self.primitive(**self._hyperparameters)
416,334
Set new hyperparameter values for some blocks. Args: hyperparameters (dict): A dictionary containing the block names as keys and the new hyperparameters dictionary as values.
def set_hyperparameters(self, hyperparameters): for block_name, block_hyperparams in hyperparameters.items(): self.blocks[block_name].set_hyperparameters(block_hyperparams)
416,340
Save the specification of this MLPipeline in a JSON file. The content of the JSON file is the dict returned by the `to_dict` method. Args: path (str): Path to the JSON file to write.
def save(self, path): with open(path, 'w') as out_file: json.dump(self.to_dict(), out_file, indent=4)
416,346
Create a new MLPipeline from a dict specification. The dict structure is the same as the one created by the `to_dict` method. Args: metadata (dict): Dictionary containing the pipeline specification. Returns: MLPipeline: A new MLPipeline instance with th...
def from_dict(cls, metadata): hyperparameters = metadata.get('hyperparameters') tunable = metadata.get('tunable_hyperparameters') pipeline = cls( metadata['primitives'], metadata.get('init_params'), metadata.get('input_names'), metadata.g...
416,347
Create a new MLPipeline from a JSON specification. The JSON file format is the same as the one created by the `to_dict` method. Args: path (str): Path of the JSON file to load. Returns: MLPipeline: A new MLPipeline instance with the specification found ...
def load(cls, path): with open(path, 'r') as in_file: metadata = json.load(in_file) return cls.from_dict(metadata)
416,348
Add a new path to look for primitives. The new path will be inserted in the first place of the list, so any primitive found in this new folder will take precedence over any other primitive with the same name that existed in the system before. Args: path (str): path to add Raises: ...
def add_primitives_path(path): if path not in _PRIMITIVES_PATHS: if not os.path.isdir(path): raise ValueError('Invalid path: {}'.format(path)) LOGGER.debug('Adding new primitives path %s', path) _PRIMITIVES_PATHS.insert(0, os.path.abspath(path))
416,349
Create a new MenuBorderStyle instance based on the given border style type. Args: border_style_type (int): an integer value from :obj:`MenuBorderStyleType`. Returns: :obj:`MenuBorderStyle`: a new MenuBorderStyle instance of the specified style.
def create_border(self, border_style_type): if border_style_type == MenuBorderStyleType.ASCII_BORDER: return self.create_ascii_border() elif border_style_type == MenuBorderStyleType.LIGHT_BORDER: return self.create_light_border() elif border_style_type == MenuBor...
420,557
Add an item to the end of the menu before the exit item. Note that Multi-Select Menus will not allow a SubmenuItem to be added, as multi-select menus are expected to be used only for executing multiple actions. Args: item (:obj:`MenuItem`): The item to be added Raises: ...
def append_item(self, item): if isinstance(item, SubmenuItem): raise TypeError("SubmenuItems cannot be added to a MultiSelectMenu") super(MultiSelectMenu, self).append_item(item)
420,581
Add an item to the end of the menu before the exit item. Args: item (MenuItem): The item to be added.
def append_item(self, item): did_remove = self.remove_exit() item.menu = self self.items.append(item) if did_remove: self.add_exit()
420,592
Remove the specified item from the menu. Args: item (MenuItem): the item to be removed. Returns: bool: True if the item was removed; False otherwise.
def remove_item(self, item): for idx, _item in enumerate(self.items): if item == _item: del self.items[idx] return True return False
420,593
Start the menu in a new thread and allow the user to interact with it. The thread is a daemon, so :meth:`join()<consolemenu.ConsoleMenu.join>` should be called if there's a possibility that the main thread will exit before the menu is done Args: show_exit_option (bool): Specify whet...
def start(self, show_exit_option=None): self.previous_active_menu = ConsoleMenu.currently_active_menu ConsoleMenu.currently_active_menu = None self.should_exit = False if show_exit_option is None: show_exit_option = self.show_exit_option if show_exit_optio...
420,596
Constructs a local symbol table. Args: imports (Optional[SymbolTable]): Shared symbol tables to import. symbols (Optional[Iterable[Unicode]]): Initial local symbols to add. Returns: SymbolTable: A mutable local symbol table with the seeded local symbols.
def local_symbol_table(imports=None, symbols=()): return SymbolTable( table_type=LOCAL_TABLE_TYPE, symbols=symbols, imports=imports )
420,870
Constructs a shared symbol table. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol table. symbols (Iterable[unicode]): The symbols to associate with the table. imports (Optional[Iterable[SymbolTable]): The shared symbol table...
def shared_symbol_table(name, version, symbols, imports=None): return SymbolTable( table_type=SHARED_TABLE_TYPE, symbols=symbols, name=name, version=version, imports=imports )
420,871
Constructs a shared symbol table that consists symbols that all have no known text. This is generally used for cases where a shared symbol table is not available by the application. Args: name (unicode): The name of the shared symbol table. version (int): The version of the shared symbol t...
def placeholder_symbol_table(name, version, max_id): if version <= 0: raise ValueError('Version must be grater than or equal to 1: %s' % version) if max_id < 0: raise ValueError('Max ID must be zero or positive: %s' % max_id) return SymbolTable( table_type=SHARED_TABLE_TYPE, ...
420,872
Interns the given Unicode sequence into the symbol table. Note: This operation is only valid on local symbol tables. Args: text (unicode): The target to intern. Returns: SymbolToken: The mapped symbol token which may already exist in the table.
def intern(self, text): if self.table_type.is_shared: raise TypeError('Cannot intern on shared symbol table') if not isinstance(text, six.text_type): raise TypeError('Cannot intern non-Unicode sequence into symbol table: %r' % text) token = self.get(text) ...
420,880
Returns a token by text or local ID. Args: key (unicode | int): The text or ID to lookup. Returns: SymbolToken: The token associated with the key. Raises: KeyError: If the key is not in the table. See Also: :meth:`get()`
def __getitem__(self, key): token = self.get(key) if token is None: raise KeyError('No symbol for: %s' % key) return token
420,882
Adds a shared table to the catalog. Args: table (SymbolTable): A non-system, shared symbol table.
def register(self, table): if table.table_type.is_system: raise ValueError('Cannot add system table to catalog') if not table.table_type.is_shared: raise ValueError('Cannot add local table to catalog') if table.is_substitute: raise ValueError('Cannot ...
420,884
Add a node containing the container's header to the current subtree. This node will be added as the leftmost leaf of the subtree that was started by the matching call to start_container. Args: header_buf (bytearray): bytearray containing the container header.
def end_container(self, header_buf): if not self.__container_nodes: raise ValueError("Attempted to end container with none active.") # Header needs to be the first node visited on this subtree. self.__container_node.add_leaf(_Node(header_buf)) self.__container_node =...
420,906
Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value.
def add_scalar_value(self, value_buf): self.__container_node.add_child(_Node(value_buf)) self.current_container_length += len(value_buf)
420,907
Creates a handler function that creates a co-routine that can yield once with the given positional arguments to the delegate as a transition. Args: delegate (Coroutine): The co-routine to delegate to. Returns: A :class:`callable` handler that returns a co-routine that ignores the data it r...
def _create_delegate_handler(delegate): @coroutine def handler(*args): yield yield delegate.send(Transition(args, delegate)) return handler
420,923
Creates a co-routine for retrieving data up to a requested size. Args: length (int): The minimum length requested. whence (Coroutine): The co-routine to return to after the data is satisfied. ctx (_HandlerContext): The context for the read. skip (Optional[bool]): Whether the request...
def _read_data_handler(length, whence, ctx, skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT): trans = None queue = ctx.queue if length > ctx.remaining: raise IonException('Length overrun: %d bytes, %d remaining' % (length, ctx.remaining)) # Make sure to check the queue first. que...
420,924
Handler for the body of a container (or the top-level stream). Args: ion_type (Optional[IonType]): The type of the container or ``None`` for the top-level. ctx (_HandlerContext): The context for the container.
def _container_handler(ion_type, ctx): transition = None first = True at_top = ctx.depth == 0 while True: data_event, self = (yield transition) if data_event is not None and data_event.type is ReadEventType.SKIP: yield ctx.read_data_transition(ctx.remaining, self, skip=T...
420,934
Binds a set of handlers with the given factory. Args: tids (Sequence[int]): The Type IDs to bind to. user_handler (Callable): A function that takes as its parameters :class:`IonType`, ``length``, and the ``ctx`` context returning a co-routine. lns (Sequence[int]): Th...
def _bind_length_handlers(tids, user_handler, lns): for tid in tids: for ln in lns: type_octet = _gen_type_octet(tid, ln) ion_type = _TID_VALUE_TYPE_TABLE[tid] if ln == 1 and ion_type is IonType.STRUCT: handler = partial(_ordered_struct_start_handler,...
420,942
Binds a set of scalar handlers for an inclusive range of low-nibble values. Args: tids (Sequence[int]): The Type IDs to bind to. scalar_factory (Callable): The factory for the scalar parsing function. This function can itself return a function representing a thunk to defer the ...
def _bind_length_scalar_handlers(tids, scalar_factory, lns=_NON_ZERO_LENGTH_LNS): handler = partial(_length_scalar_handler, scalar_factory) return _bind_length_handlers(tids, handler, lns)
420,943
Provides an implementation of using the reader co-routine with a file-like object. Args: reader(Coroutine): A reader co-routine. input(BaseIO): The file-like object to read from. buffer_size(Optional[int]): The optional buffer size to use.
def blocking_reader(reader, input, buffer_size=_DEFAULT_BUFFER_SIZE): ion_event = None while True: read_event = (yield ion_event) ion_event = reader.send(read_event) while ion_event is not None and ion_event.event_type.is_stream_signal: data = input.read(buffer_size) ...
420,961
Managed reader wrapping another reader. Args: reader (Coroutine): The underlying non-blocking reader co-routine. catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports. Yields: Events from the underlying reader delegating to symbol table processing as needed. ...
def managed_reader(reader, catalog=None): if catalog is None: catalog = SymbolTableCatalog() ctx = _ManagedContext(catalog) symbol_trans = Transition(None, None) ion_event = None while True: if symbol_trans.delegate is not None \ and ion_event is not None \ ...
420,975
Raises an IonException upon encountering the given illegal character in the given context. Args: c (int|None): Ordinal of the illegal character. ctx (_HandlerContext): Context in which the illegal character was encountered. message (Optional[str]): Additional information, as necessary.
def _illegal_character(c, ctx, message=''): container_type = ctx.container.ion_type is None and 'top-level' or ctx.container.ion_type.name value_type = ctx.ion_type is None and 'unknown' or ctx.ion_type.name if c is None: header = 'Illegal token' else: c = 'EOF' if BufferQueue.is_eo...
420,981
Generates a handler co-routine which tokenizes a integer of a particular radix. Args: radix_indicators (sequence): The set of ordinals of characters that indicate the radix of this int. charset (sequence): Set of ordinals of legal characters for this radix. parse_func (callable): Called upo...
def _radix_int_handler_factory(radix_indicators, charset, parse_func): def assertion(c, ctx): return c in radix_indicators and \ ((len(ctx.value) == 1 and ctx.value[0] == _ZERO) or (len(ctx.value) == 2 and ctx.value[0] == _MINUS and ctx.value[1] == _ZERO)) and \ ...
420,993
Generates handler co-routines for values that may be `+inf` or `-inf`. Args: c_start (int): The ordinal of the character that starts this token (either `+` or `-`). is_delegate (bool): True if a different handler began processing this token; otherwise, False. This will only be true for ...
def _inf_or_operator_handler_factory(c_start, is_delegate=True): @coroutine def inf_or_operator_handler(c, ctx): next_ctx = None if not is_delegate: ctx.value.append(c_start) c, self = yield else: assert ctx.value[0] == c_start assert ...
421,004
Generates handlers for tokens that begin with container start characters. Args: ion_type (IonType): The type of this container. before_yield (Optional[callable]): Called at initialization. Accepts the first character's ordinal and the current context; performs any necessary initializati...
def _container_start_handler_factory(ion_type, before_yield=lambda c, ctx: None): assert ion_type.is_container @coroutine def container_start_handler(c, ctx): before_yield(c, ctx) yield yield ctx.event_transition(IonEvent, IonEventType.CONTAINER_START, ion_type, value=None) ...
421,019
Creates a transition to a co-routine for retrieving data as bytes. Args: whence (Coroutine): The co-routine to return to after the data is satisfied. complete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or available; False if INCOMPLETE sh...
def read_data_event(self, whence, complete=False, can_flush=False): return Transition(None, _read_data_handler(whence, self, complete, can_flush))
421,028
Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``. Args: func (Callable): The function constructing a generator to decorate. Returns: Callable: The decorated generator.
def coroutine(func): def wrapper(*args, **kwargs): gen = func(*args, **kwargs) val = next(gen) if val != None: raise TypeError('Unexpected value from start of coroutine') return gen wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ return wr...
421,049
Derives a new event from this one setting the ``field_name`` attribute. Args: field_name (Union[amazon.ion.symbols.SymbolToken, unicode]): The field name to set. Returns: IonEvent: The newly generated event.
def derive_field_name(self, field_name): cls = type(self) # We use ordinals to avoid thunk materialization. return cls( self[0], self[1], self[2], field_name, self[4], self[5] )
421,056
Derives a new event from this one setting the ``annotations`` attribute. Args: annotations: (Sequence[Union[amazon.ion.symbols.SymbolToken, unicode]]): The annotations associated with the derived event. Returns: IonEvent: The newly generated event.
def derive_annotations(self, annotations): cls = type(self) # We use ordinals to avoid thunk materialization. return cls( self[0], self[1], self[2], self[3], annotations, self[5] )
421,057
Derives a new event from this one setting the ``value`` attribute. Args: value: (any): The value associated with the derived event. Returns: IonEvent: The newly generated non-thunk event.
def derive_value(self, value): return IonEvent( self.event_type, self.ion_type, value, self.field_name, self.annotations, self.depth )
421,058
Derives a new event from this one setting the ``depth`` attribute. Args: depth: (int): The annotations associated with the derived event. Returns: IonEvent: The newly generated event.
def derive_depth(self, depth): cls = type(self) # We use ordinals to avoid thunk materialization. return cls( self[0], self[1], self[2], self[3], self[4], depth )
421,059
Builds functions that leverage Python ``str()`` or similar functionality. Args: type_name (str): The name of the Ion type. types (Union[Sequence[type],type]): The Python types to validate for. str_func (Optional[Callable]): The function to convert the value with, defaults to ``str``. R...
def _serialize_scalar_from_string_representation_factory(type_name, types, str_func=str): def serialize(ion_event): value = ion_event.value validate_scalar_value(value, types) return six.b(str_func(value)) serialize.__name__ = '_serialize_' + type_name return serialize
421,074
Returns a function that serializes container start/end. Args: suffix (str): The suffix to name the function with. container_map (Dictionary[core.IonType, bytes]): The Returns: function: The closure for serialization.
def _serialize_container_factory(suffix, container_map): def serialize(ion_event): if not ion_event.ion_type.is_container: raise TypeError('Expected container type') return container_map[ion_event.ion_type] serialize.__name__ = '_serialize_container_' + suffix return seriali...
421,085
Drain the writer of its pending write events. Args: writer (Coroutine): A writer co-routine. ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer. Yields: DataEvent: Yields each pending data event.
def _drain(writer, ion_event): result_event = _WRITE_EVENT_HAS_PENDING_EMPTY while result_event.type is WriteEventType.HAS_PENDING: result_event = writer.send(ion_event) ion_event = None yield result_event
421,092
Provides an implementation of using the writer co-routine with a file-like object. Args: writer (Coroutine): A writer co-routine. output (BaseIO): The file-like object to pipe events to. Yields: WriteEventType: Yields when no events are pending. Receives :class:`amazon.ion.cor...
def blocking_writer(writer, output): result_type = None while True: ion_event = (yield result_type) for result_event in _drain(writer, ion_event): output.write(result_event.data) result_type = result_event.type
421,093
Constructs the given native extension from the properties of an event. Args: ion_event (IonEvent): The event to construct the native value from.
def from_event(cls, ion_event): if ion_event.value is not None: args, kwargs = cls._to_constructor_args(ion_event.value) else: # if value is None (i.e. this is a container event), args must be empty or initialization of the # underlying container will fail. ...
421,097
Constructs a value as a copy with an associated Ion type and annotations. Args: ion_type (IonType): The associated Ion type. value (Any): The value to construct from, generally of type ``cls``. annotations (Sequence[unicode]): The sequence Unicode strings decorating this va...
def from_value(cls, ion_type, value, annotations=()): if value is None: value = IonPyNull() else: args, kwargs = cls._to_constructor_args(value) value = cls(*args, **kwargs) value.ion_event = None value.ion_type = ion_type value.ion_an...
421,098
Constructs an IonEvent from this _IonNature value. Args: event_type (IonEventType): The type of the resulting event. field_name (Optional[text]): The field name associated with this value, if any. depth (Optional[int]): The depth of this value. Returns: ...
def to_event(self, event_type, field_name=None, depth=None): if self.ion_event is None: value = self if isinstance(self, IonPyNull): value = None self.ion_event = IonEvent(event_type, ion_type=self.ion_type, value=value, field_name=field_name, ...
421,099
Create tabular data package with resources. It will also infer the tabular resources' schemas. Args: resource_paths (List[str]): Paths to the data package resources. Returns: datapackage.Package: The data package.
def init_datapackage(resource_paths): dp = datapackage.Package({ 'name': 'change-me', 'schema': 'tabular-data-package', }) for path in resource_paths: dp.infer(path) return dp
421,679
Build crs table of all equivalent format variations by scraping spatialreference.org. Saves table as tab-delimited text file. NOTE: Might take a while. Arguments: - *savepath*: The absolute or relative filepath to which to save the crs table, including the ".txt" extension.
def build_crs_table(savepath): # create table outfile = open(savepath, "wb") # create fields fields = ["codetype", "code", "proj4", "ogcwkt", "esriwkt"] outfile.write("\t".join(fields) + "\n") # make table from url requests for codetype in ("epsg", "esri", "sr-org"): p...
421,712
Lookup crscode on spatialreference.org and return in specified format. Arguments: - *codetype*: "epsg", "esri", or "sr-org". - *code*: The code. - *format*: The crs format of the returned string. One of "ogcwkt", "esriwkt", or "proj4", but also several others... Returns: - Crs string in the ...
def crscode_to_string(codetype, code, format): link = 'http://spatialreference.org/ref/%s/%s/%s/' %(codetype,code,format) result = urllib2.urlopen(link).read() if not isinstance(result, str): result = result.decode() return result
421,713
A Datum defines the shape of the earth. Arguments: - **name**: A pycrs.datums.DatumName instance with the name given by each supported format. - **ellipsoid**: A pycrs.elements.ellipsoids.Ellipsoid instance. - **datumshift** (optional): A pycrs.elements.parameters.DatumShift instance...
def __init__(self, **kwargs): self.name = kwargs.get('name', self.name) self.ellips = kwargs.get('ellipsoid', self.ellips) self.datumshift = kwargs.get('datumshift', self.datumshift)
421,714
Returns the CS as a proj4 formatted string or dict. Arguments: - **as_dict** (optional): If True, returns the proj4 string as a dict (defaults to False). - **toplevel** (optional): If True, treats this CS as the final toplevel CS and adds the necessary proj4 elements (defaults to True).
def to_proj4(self, as_dict=False, toplevel=True): # dont parse axis to proj4, because in proj4, axis only applies to the cs, ie the projcs (not the geogcs, where wkt can specify with axis) # also proj4 cannot specify angular units if toplevel: string = "+proj=longlat %s %s +...
421,719
Returns the CS as a proj4 formatted string or dict. Arguments: - **as_dict** (optional): If True, returns the proj4 string as a dict (defaults to False).
def to_proj4(self, as_dict=False): string = "%s" % self.proj.to_proj4() string += " %s" % self.geogcs.to_proj4(toplevel=False) string += " " + " ".join(param.to_proj4() for param in self.params) string += " %s" % self.unit.to_proj4() string += " +axis=" + self.twin_ax[0]...
421,723
Search for a ellipsoid name located in this module. Arguments: - **ellipsname**: The ellipsoid name to search for. - **crstype**: Which CRS naming convention to search (different CRS formats have different names for the same ellipsoid). - **strict** (optional): If False, ignores minor name mis...
def find(ellipsname, crstype, strict=False): if not strict: ellipsname = ellipsname.lower().replace(" ","_") for itemname,item in globals().items(): if itemname.startswith("_") or itemname == 'Ellipsoid': continue try: if hasattr(item.name, crstype): ...
421,726
Returns the crs object from a string interpreted as a specified format, located at a given url site. Arguments: - *url*: The url where the crs string is to be read from. - *format* (optional): Which format to parse the crs string as. One of "ogc wkt", "esri wkt", or "proj4". If None, tries to aut...
def from_url(url, format=None): # first get string from url string = urllib2.urlopen(url).read() if PY3 is True: # decode str into string string = string.decode('utf-8') # then determine parser if format: # user specified format format = format.lower().repl...
421,733
Returns the crs object from a file, with the format determined from the filename extension. Arguments: - *filepath*: filepath to be loaded, including extension.
def from_file(filepath): if filepath.endswith(".prj"): string = open(filepath, "r").read() return parse.from_unknown_wkt(string) elif filepath.endswith((".geojson",".json")): raw = open(filepath).read() geoj = json.loads(raw) if "crs" in geoj: crsinf...
421,734
Load crs object from epsg code, via spatialreference.org. Parses based on the proj4 representation. Arguments: - *code*: The EPSG code as an integer. Returns: - A CS instance of the indicated type.
def from_epsg_code(code): # must go online (or look up local table) to get crs details code = str(code) proj4 = utils.crscode_to_string("epsg", code, "proj4") crs = from_proj4(proj4) return crs
421,735
Load crs object from esri code, via spatialreference.org. Parses based on the proj4 representation. Arguments: - *code*: The ESRI code as an integer. Returns: - A CS instance of the indicated type.
def from_esri_code(code): # must go online (or look up local table) to get crs details code = str(code) proj4 = utils.crscode_to_string("esri", code, "proj4") crs = from_proj4(proj4) return crs
421,736