text
stringlengths
81
112k
Compute the size (in 512B blocks) of the parameter section. def parameter_blocks(self): '''Compute the size (in 512B blocks) of the parameter section.''' bytes = 4. + sum(g.binary_size() for g in self.groups.values()) return int(np.ceil(bytes / 512))
Iterate over the data frames from our C3D file handle. Parameters ---------- copy : bool If False, the reader returns a reference to the same data buffers for every frame. The default is True, which causes the reader to return a unique data buffer for each fr...
Pad the file with 0s to the end of the next block boundary. def _pad_block(self, handle): '''Pad the file with 0s to the end of the next block boundary.''' extra = handle.tell() % 512 if extra: handle.write(b'\x00' * (512 - extra))
Write metadata to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. def _write_metadata(self, handle): '''Write metadata to a file handle. Parameters ...
Write our frame data to the given file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. def _write_frames(self, handle): '''Write our frame data to the given file han...
Write metadata and point + analog frames to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. def write(self, handle): '''Write metadata and point + analog fram...
Given a time range aggregates bytes per prefix. Args: start_time: A string representing the starting time of the time range end_time: A string representing the ending time of the time range limit: An optional integer. If it's >0 it will limit the amount of pr...
Given a time range aggregates bytes per ASNs. Args: start_time: A string representing the starting time of the time range end_time: A string representing the ending time of the time range Returns: A list of prefixes sorted by sum_bytes. For examp...
Replace vector images with fake ones. def _workaround_no_vector_images(project): """Replace vector images with fake ones.""" RED = (255, 0, 0) PLACEHOLDER = kurt.Image.new((32, 32), RED) for scriptable in [project.stage] + project.sprites: for costume in scriptable.costumes: if cost...
Make Stage-specific variables global (move them to Project). def _workaround_no_stage_specific_variables(project): """Make Stage-specific variables global (move them to Project).""" for (name, var) in project.stage.variables.items(): yield "variable %s" % name for (name, _list) in project.stage.lis...
Register a new :class:`KurtPlugin`. Once registered, the plugin can be used by :class:`Project`, when: * :attr:`Project.load` sees a file with the right extension * :attr:`Project.convert` is called with the format as a parameter def register(cls, plugin): """Register a new :class:`K...
Returns the first format plugin whose attributes match kwargs. For example:: get_plugin(extension="scratch14") Will return the :class:`KurtPlugin` whose :attr:`extension <KurtPlugin.extension>` attribute is ``"scratch14"``. The :attr:`name <KurtPlugin.name>` is used as th...
Return the block with the given :attr:`command`. Returns None if the block is not found. def block_by_command(cls, command): """Return the block with the given :attr:`command`. Returns None if the block is not found. """ for block in cls.blocks: if block.has_comma...
Return a list of blocks matching the given :attr:`text`. Capitalisation and spaces are ignored. def blocks_by_text(cls, text): """Return a list of blocks matching the given :attr:`text`. Capitalisation and spaces are ignored. """ text = kurt.BlockType._strip_text(text) ...
Clean up the given list of scripts in-place so none of the scripts overlap. def clean_up(scripts): """Clean up the given list of scripts in-place so none of the scripts overlap. """ scripts_with_pos = [s for s in scripts if s.pos] scripts_with_pos.sort(key=lambda s: (s.pos[1], s.pos[0])) s...
Return a list of classes in a module that have a 'classID' attribute. def obj_classes_from_module(module): """Return a list of classes in a module that have a 'classID' attribute.""" for name in dir(module): if not name.startswith('_'): cls = getattr(module, name) if getattr(cls...
Return root object from ref-containing obj table entries def decode_network(objects): """Return root object from ref-containing obj table entries""" def resolve_ref(obj, objects=objects): if isinstance(obj, Ref): # first entry is 1 return objects[obj.index - 1] else: ...
Yield ref-containing obj table entries from object network def encode_network(root): """Yield ref-containing obj table entries from object network""" orig_objects = [] objects = [] def get_ref(value, objects=objects): """Returns the index of the given object in the object table, adding...
Yield ref-containing obj table entries from object network def encode_network(root): """Yield ref-containing obj table entries from object network""" def fix_values(obj): if isinstance(obj, Container): obj.update((k, get_ref(v)) for (k, v) in obj.items() ...
Return root of obj table. Converts user-class objects def decode_obj_table(table_entries, plugin): """Return root of obj table. Converts user-class objects""" entries = [] for entry in table_entries: if isinstance(entry, Container): assert not hasattr(entry, '__recursion_lock__') ...
Return list of obj table entries. Converts user-class objects def encode_obj_table(root, plugin): """Return list of obj table entries. Converts user-class objects""" entries = encode_network(root) table_entries = [] for entry in entries: if isinstance(entry, Container): assert not ...
Encodes a class to a lower-level object using the class' own to_construct function. If no such function is defined, returns the object unchanged. def _encode(self, obj, context): """Encodes a class to a lower-level object using the class' own to_construct function. If no such fu...
Initialises a new Python class from a construct using the mapping passed to the adapter. def _decode(self, obj, context): """Initialises a new Python class from a construct using the mapping passed to the adapter. """ cls = self._get_class(obj.classID) return cls.from_co...
Write file contents string into archive. def write_file(self, name, contents): """Write file contents string into archive.""" # TODO: find a way to make ZipFile accept a file object. zi = zipfile.ZipInfo(name) zi.date_time = time.localtime(time.time())[:6] zi.compress_type = zip...
Yield (pitch, start_beat, end_beat) for each note in midi file. def load_midi_file(path): """Yield (pitch, start_beat, end_beat) for each note in midi file.""" midi_notes = [] def register_note(track, channel, pitch, velocity, start, end): midi_notes.append((pitch, start, end)) midi.register_n...
Return (images, sounds) def get_media(self, v14_scriptable): """Return (images, sounds)""" images = [] sounds = [] for media in v14_scriptable.media: if media.class_name == 'SoundMedia': sounds.append(media) elif media.class_name == 'ImageMedia': ...
Decodes a run-length encoded ByteArray and returns a Bitmap. The ByteArray decompresses to a sequence of 32-bit values, which are stored as a byte string. (The specific encoding depends on Form.depth.) def from_byte_array(cls, bytes_): """Decodes a run-length encoded ByteArray and returns a Bit...
Returns a Form with 32-bit RGBA pixels Accepts string containing raw RGBA color values def from_string(cls, width, height, rgba_string): """Returns a Form with 32-bit RGBA pixels Accepts string containing raw RGBA color values """ # Convert RGBA string to ARGB raw = "" ...
Opens Explorer/Finder with given path, depending on platform def open_file(path): """Opens Explorer/Finder with given path, depending on platform""" if sys.platform=='win32': os.startfile(path) #subprocess.Popen(['start', path], shell= True) elif sys.platform=='darwin': subproc...
Update the file_path Entry widget def set_file_path(self, path): """Update the file_path Entry widget""" self.file_path.delete(0, END) self.file_path.insert(0, path)
Load project from file. Use ``format`` to specify the file format to use. Path can be a file-like object, in which case format is required. Otherwise, can guess the appropriate format from the extension. If you pass a file-like object, you're responsible for closing the file. ...
Return a new Project instance, deep-copying all the attributes. def copy(self): """Return a new Project instance, deep-copying all the attributes.""" p = Project() p.name = self.name p.path = self.path p._plugin = self._plugin p.stage = self.stage.copy() p.stage....
Convert the project in-place to a different file format. Returns a list of :class:`UnsupportedFeature` objects, which may give warnings about the conversion. :param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``. :raises: :class:`ValueError` if the format doesn't exist. def ...
Save project to file. :param path: Path or file pointer. If you pass a file pointer, you're responsible for closing it. If path is not given, the :attr:`path` attribute is used, usually the original path given to :attr:`load(...
Convert the project to a standardised form for the current plugin. Called after loading, before saving, and when converting to a new format. Yields UnsupportedFeature instances. def _normalize(self): """Convert the project to a standardised form for the current plugin. Called...
Return a new instance, deep-copying all the attributes. def copy(self, o=None): """Return a new instance, deep-copying all the attributes.""" if o is None: o = self.__class__(self.project) o.scripts = [s.copy() for s in self.scripts] o.variables = dict((n, v.copy()) for (n, v) in self.v...
Parse the given code and add it to :attr:`scripts`. The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for reference. def parse(self, text): """Parse the given code and add it to :attr:`scripts`. The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for ...
Return a new instance, deep-copying all the attributes. def copy(self): """Return a new instance, deep-copying all the attributes.""" o = self.__class__(self.project, self.name) Scriptable.copy(self, o) o.position = tuple(self.position) o.direction = self.direction o.rot...
Return a new instance with the same attributes. def copy(self): """Return a new instance with the same attributes.""" o = self.__class__(self.target, self.block.copy(), self.style, self.is_visible, self.pos) o.slider_min = self.sli...
The type of value to watch, based on :attr:`block`. One of ``variable``, ``list``, or ``block``. ``block`` watchers watch the value of a reporter block. def kind(self): """The type of value to watch, based on :attr:`block`. One of ``variable``, ``list``, or ``block``. ``bloc...
Return the :class:`Variable` or :class:`List` to watch. Returns ``None`` if it's a block watcher. def value(self): """Return the :class:`Variable` or :class:`List` to watch. Returns ``None`` if it's a block watcher. """ if self.kind == 'variable': return self.targ...
Returns the color value in hexcode format. eg. ``'#ff1056'`` def stringify(self): """Returns the color value in hexcode format. eg. ``'#ff1056'`` """ hexcode = "#" for x in self.value: part = hex(x)[2:] if len(part) < 2: part = "0" + part ...
Return a list of valid options to a menu insert, given a Scriptable for context. Mostly complete, excepting 'attribute'. def options(self, scriptable=None): """Return a list of valid options to a menu insert, given a Scriptable for context. Mostly complete, excepting 'attribut...
The text displayed on the block. String containing ``"%s"`` in place of inserts. eg. ``'say %s for %s secs'`` def text(self): """The text displayed on the block. String containing ``"%s"`` in place of inserts. eg. ``'say %s for %s secs'`` """ parts = [("%s" ...
The :attr:`text`, with spaces and inserts removed. Used by :class:`BlockType.get` to look up blocks. def stripped_text(self): """The :attr:`text`, with spaces and inserts removed. Used by :class:`BlockType.get` to look up blocks. """ return BaseBlockType._strip_text( ...
Returns text with spaces and inserts removed. def _strip_text(text): """Returns text with spaces and inserts removed.""" text = re.sub(r'[ ,?:]|%s', "", text.lower()) for chr in "-%": new_text = text.replace(chr, "") if new_text: text = new_text r...
Returns True if any of the inserts have the given shape. def has_insert(self, shape): """Returns True if any of the inserts have the given shape.""" for insert in self.inserts: if insert.shape == shape: return True return False
Add a new PluginBlockType conversion. If the plugin already exists, do nothing. def _add_conversion(self, plugin, pbt): """Add a new PluginBlockType conversion. If the plugin already exists, do nothing. """ assert self.shape == pbt.shape assert len(self.inserts) == le...
Return a :class:`PluginBlockType` for the given plugin name. If plugin is ``None``, return the first registered plugin. def convert(self, plugin=None): """Return a :class:`PluginBlockType` for the given plugin name. If plugin is ``None``, return the first registered plugin. """ ...
Return True if the plugin supports this block. def has_conversion(self, plugin): """Return True if the plugin supports this block.""" plugin = kurt.plugin.Kurt.get_plugin(plugin) return plugin.name in self._plugins
Returns True if any of the plugins have the given command. def has_command(self, command): """Returns True if any of the plugins have the given command.""" for pbt in self._plugins.values(): if pbt.command == command: return True return False
Return a :class:`BlockType` instance from the given parameter. * If it's already a BlockType instance, return that. * If it exactly matches the command on a :class:`PluginBlockType`, return the corresponding BlockType. * If it loosely matches the text on a PluginBlockType, return th...
Return a new Block instance with the same attributes. def copy(self): """Return a new Block instance with the same attributes.""" args = [] for arg in self.args: if isinstance(arg, Block): arg = arg.copy() elif isinstance(arg, list): arg =...
Return a new instance with the same attributes. def copy(self): """Return a new instance with the same attributes.""" return self.__class__([b.copy() for b in self.blocks], tuple(self.pos) if self.pos else None)
Load costume from image file. Uses :attr:`Image.load`, but will set the Costume's name based on the image filename. def load(self, path): """Load costume from image file. Uses :attr:`Image.load`, but will set the Costume's name based on the image filename. """ ...
A :class:`PIL.Image.Image` instance containing the image data. def pil_image(self): """A :class:`PIL.Image.Image` instance containing the image data.""" if not self._pil_image: if self._format == "SVG": raise VectorImageError("can't rasterise vector images") self...
The raw file contents as a string. def contents(self): """The raw file contents as a string.""" if not self._contents: if self._path: # Read file into memory so we don't run out of file descriptors f = open(self._path, "rb") self._contents = f...
The format of the image file. An uppercase string corresponding to the :attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include ``"JPEG"`` and ``"PNG"``. def format(self): """The format of the image file. An uppercase string corresponding to the :attr:`P...
``(width, height)`` in pixels. def size(self): """``(width, height)`` in pixels.""" if self._size and not self._pil_image: return self._size else: return self.pil_image.size
Load image from file. def load(cls, path): """Load image from file.""" assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) image = Image(None) image._path = path image._f...
Return an Image instance with the first matching format. For each format in ``*args``: If the image's :attr:`format` attribute is the same as the format, return self, otherwise try the next format. If none of the formats match, return a new Image instance with the last format. def con...
Return a new Image instance with the given format. Returns self if the format is already the same. def _convert(self, format): """Return a new Image instance with the given format. Returns self if the format is already the same. """ if self.format == format: retur...
Save image to file path. The image format is guessed from the extension. If path has no extension, the image's :attr:`format` is used. :returns: Path to the saved file. def save(self, path): """Save image to file path. The image format is guessed from the extension. If path h...
Return a new Image instance filled with a color. def new(self, size, fill): """Return a new Image instance filled with a color.""" return Image(PIL.Image.new("RGB", size, fill))
Return a new Image instance with the given size. def resize(self, size): """Return a new Image instance with the given size.""" return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))
Return a new Image with the given image pasted on top. This image will show through transparent areas of the given image. def paste(self, other): """Return a new Image with the given image pasted on top. This image will show through transparent areas of the given image. """ r...
Load sound from wave file. Uses :attr:`Waveform.load`, but will set the Waveform's name based on the sound filename. def load(self, path): """Load sound from wave file. Uses :attr:`Waveform.load`, but will set the Waveform's name based on the sound filename. """ ...
Save the sound to a wave file at the given path. Uses :attr:`Waveform.save`, but if the path ends in a folder instead of a file, the filename is based on the project's :attr:`name`. :returns: Path to the saved file. def save(self, path): """Save the sound to a wave file at the given p...
The raw file contents as a string. def contents(self): """The raw file contents as a string.""" if not self._contents: if self._path: # Read file into memory so we don't run out of file descriptors f = open(self._path, "rb") self._contents = f...
Return a wave.Wave_read instance from the ``wave`` module. def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self ...
Load Waveform from file. def load(cls, path): """Load Waveform from file.""" assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) wave = Waveform(None) wave._path = path r...
Save waveform to file path as a WAV file. :returns: Path to the saved file. def save(self, path): """Save waveform to file path as a WAV file. :returns: Path to the saved file. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename)...
Sort the given list in the way that humans expect. def sort_nicely(l): """Sort the given list in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] l.sort(key=alphanum_key)
Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`Channel` object. def open_channel(self): """ Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`...
Close the connection by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. def close(self): """ Close the connection by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """ if not self.is_closed(): self._c...
Is sent in case protocol lost connection to server. def handle_PoisonPillFrame(self, frame): """ Is sent in case protocol lost connection to server.""" # Will be delivered after Close or CloseOK handlers. It's for channels, # so ignore it. if self.connection.closed.done(): r...
AMQP server closed the channel with an error def handle_ConnectionClose(self, frame): """ AMQP server closed the channel with an error """ # Notify server we are OK to close. self.sender.send_CloseOK() exc = ConnectionClosed(frame.payload.reply_text, fram...
Publish a message on the exchange, to be asynchronously delivered to queues. :param asynqp.Message message: the message to send :param str routing_key: the routing key with which to publish the message :param bool mandatory: if True (the default) undeliverable messages result in an error (see a...
Delete the exchange. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the exchange will only be deleted if it has no queues bound to it. def delete(self, *, if_unused=True): """ Delete the exchange. This method is a :ref:`coroutine ...
Reject the message. :keyword bool requeue: if true, the broker will attempt to requeue the message and deliver it to an alternate consumer. def reject(self, *, requeue=True): """ Reject the message. :keyword bool requeue: if true, the broker will attempt to requeue the ...
Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created. This method is a :ref:`coroutine <coroutine>`. :param str name: the name of the exchange. :param str type: the type of the exchange (usually one of ``'fanout'``, ``'direct'``, ``'topic'`...
Declare a queue on the broker. If the queue does not exist, it will be created. This method is a :ref:`coroutine <coroutine>`. :param str name: the name of the queue. Supplying a name of '' will create a queue with a unique name of the server's choosing. :keyword bool durable: If t...
Specify quality of service by requesting that messages be pre-fetched from the server. Pre-fetching means that the server will deliver messages to the client while the client is still processing unacknowledged messages. This method is a :ref:`coroutine <coroutine>`. :param int prefetch...
Close the channel by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. def close(self): """ Close the channel by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """ # If we aren't already closed ask for server to cl...
AMQP server closed the channel with an error def handle_ChannelClose(self, frame): """ AMQP server closed the channel with an error """ # By docs: # The response to receiving a Close after sending Close must be to # send Close-Ok. # # No need for additional checks ...
AMQP server closed channel as per our request def handle_ChannelCloseOK(self, frame): """ AMQP server closed channel as per our request """ assert self.channel._closing, "received a not expected CloseOk" # Release the `close` method's future self.synchroniser.notify(spec.ChannelCloseOK)...
Bind a queue to an exchange, with the supplied routing key. This action 'subscribes' the queue to the routing key; the precise meaning of this varies with the exchange type. This method is a :ref:`coroutine <coroutine>`. :param asynqp.Exchange exchange: the :class:`Exchange` to bind t...
Start a consumer on the queue. Messages will be delivered asynchronously to the consumer. The callback function will be called whenever a new message arrives on the queue. Advanced usage: the callback object must be callable (it must be a function or define a ``__call__`` method), but m...
Synchronously get a message from the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message. :return: an :class:`~asynqp.message.IncomingMessage`, or ``None`` if there were no messa...
Purge all undelivered messages from the queue. This method is a :ref:`coroutine <coroutine>`. def purge(self): """ Purge all undelivered messages from the queue. This method is a :ref:`coroutine <coroutine>`. """ self.sender.send_QueuePurge(self.name) yield fro...
Delete the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the queue will only be deleted if it has no consumers. :keyword bool if_empty: If true, the queue will only be deleted if it has no unacknowledged messages. def delete(se...
Unbind the queue from the exchange. This method is a :ref:`coroutine <coroutine>`. def unbind(self, arguments=None): """ Unbind the queue from the exchange. This method is a :ref:`coroutine <coroutine>`. """ if self.deleted: raise Deleted("Queue {} was alre...
Cancel the consumer and stop recieving messages. This method is a :ref:`coroutine <coroutine>`. def cancel(self): """ Cancel the consumer and stop recieving messages. This method is a :ref:`coroutine <coroutine>`. """ self.sender.send_BasicCancel(self.tag) try:...
Sends a 'hello world' message and then reads it from the queue. def hello_world(): """ Sends a 'hello world' message and then reads it from the queue. """ # connect to the RabbitMQ broker connection = yield from asynqp.connect('localhost', 5672, username='guest', password='guest') # Open a com...
Connection/Channel was closed. All subsequent and ongoing requests should raise an error def killall(self, exc): """ Connection/Channel was closed. All subsequent and ongoing requests should raise an error """ self.connection_exc = exc # Set an exception for all ...
Connect to an AMQP server on the given host and port. Log in to the given virtual host using the supplied credentials. This function is a :ref:`coroutine <coroutine>`. :param str host: the host server to connect to. :param int port: the port which the AMQP server is listening on. :param str userna...
Connect to an AMQP server and open a channel on the connection. This function is a :ref:`coroutine <coroutine>`. Parameters of this function are the same as :func:`connect`. :return: a tuple of ``(connection, channel)``. Equivalent to:: connection = yield from connect(host, port, username, p...
Called by heartbeat_monitor on timeout def heartbeat_timeout(self): """ Called by heartbeat_monitor on timeout """ assert not self._closed, "Did we not stop heartbeat_monitor on close?" log.error("Heartbeat time out") poison_exc = ConnectionLostError('Heartbeat timed out') poiso...
Take a python object and convert it to the format Imgur expects. def convert_general(value): """Take a python object and convert it to the format Imgur expects.""" if isinstance(value, bool): return "true" if value else "false" elif isinstance(value, list): value = [convert_general(item) fo...
Convert the parameters to the format Imgur expects. def to_imgur_format(params): """Convert the parameters to the format Imgur expects.""" if params is None: return None return dict((k, convert_general(val)) for (k, val) in params.items())