INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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_note = register_note global m m = midi.MidiFile() m.o...
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': images.ap...
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 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.) """ runs = cls._length_run_coding.parse(b...
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 = "" for i in range(0, len(rgba_string), 4): raw += rgba_string[i+3] # alpha ...
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': subprocess.Popen(['open', path]) else: try: ...
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.
def load(cls, path, format=None): """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'...
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.project = p for sprite in self.sprites: s = ...
Convert the project in - place to a different file format.
def convert(self, format): """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:`ValueErr...
Save project to file.
def save(self, path=None, debug=False): """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, ...
Convert the project to a standardised form for the current plugin.
def _normalize(self): """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. """ unique_sprite_names = set(sprite.name for sprite in self.spri...
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.variables.items()) o.lists = dict((n, l.copy()) fo...
Parse the given code and add it to: attr: scripts.
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 reference. """ self.scripts.append(kurt.text.parse(text, self))
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.rotation_style = self.rotation_style o.size = self.s...
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.slider_min o.slider_max = self.slider_max ...
The type of value to watch based on: attr: block.
def kind(self): """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. """ if self.block.type.has_command('readVariable'): return 'variable' elif self.block...
Return the: class: Variable or: class: List to watch.
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.target.variables[self.block.args[0]] elif self.kind == 'list': return self.target.lists[self...
Returns the color value in hexcode format.
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 hexcode += part return hexcode
Return a list of valid options to a menu insert given a Scriptable for context.
def options(self, scriptable=None): """Return a list of valid options to a menu insert, given a Scriptable for context. Mostly complete, excepting 'attribute'. """ options = list(Insert.KIND_OPTIONS.get(self.kind, [])) if scriptable: if self.kind == 'var': ...
The text displayed on the block.
def text(self): """The text displayed on the block. String containing ``"%s"`` in place of inserts. eg. ``'say %s for %s secs'`` """ parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts] parts = [("%%" if p == "%" else p) for p in parts] # escape percent...
The: attr: text with spaces and inserts removed.
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( self.text % tuple((i.default if i.shape == 'inline' else '%s') for i ...
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 return text.lower()
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.
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) == len(pbt.inserts) for (i, o) in zip(self.inserts, pbt.inserts): assert i....
Return a: class: PluginBlockType for the given plugin name.
def convert(self, plugin=None): """Return a :class:`PluginBlockType` for the given plugin name. If plugin is ``None``, return the first registered plugin. """ if plugin: plugin = kurt.plugin.Kurt.get_plugin(plugin) if plugin.name in self._plugins: ...
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.
def get(cls, block_type): """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...
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 = [b.copy() for b in arg] args.append(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.
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. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Costume(name, Image.lo...
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._pil_image = PIL.Image.open(StringIO(self.contents)) re...
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.read() f.close() ...
The format of the image file.
def format(self): """The format of the image file. An uppercase string corresponding to the :attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include ``"JPEG"`` and ``"PNG"``. """ if self._format: return self._format elif self.pil_image...
( 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._format = Image.image_for...
Return an Image instance with the first matching format.
def convert(self, *formats): """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 instanc...
Return a new Image instance with the given format.
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: return self else: image = Image(self.pil_image) image._format = format ...
Save image to file path.
def save(self, path): """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. """ (folder, filename) = os.path.split(path) (name, extension) = os...
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.
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, g, b, alpha = other.pil_image.split() pil_image = self.pil_image.copy() pil_image.paste(other.pil_image, mask=alph...
Load sound from wave file.
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. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Sound(name, Waveform....
Save the sound to a wave file at the given path.
def save(self, path): """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. """ (folder, filename) = os....
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.read() f.close() ...
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 err.args = (err.message,) raise
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 return wave
Save waveform to file path as a WAV 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) if not name: raise ValueError, "name is required" path ...
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.
def open_channel(self): """ Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`Channel` object. """ if self._closing: raise ConnectionClosed("Closed by application") if self.closed.done(): ...
Close the connection by handshaking with the server.
def close(self): """ Close the connection by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """ if not self.is_closed(): self._closing = True # Let the ConnectionActor do the actual close operations. # It will do t...
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(): return # If connection was not closed already ...
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, frame.payload.reply_code) self._close_all(...
Publish a message on the exchange to be asynchronously delivered to queues.
def publish(self, message, routing_key, *, mandatory=True): """ 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 m...
Delete the exchange.
def delete(self, *, if_unused=True): """ 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. """ self.sender.send_ExchangeDelete(self.name, i...
Reject the message.
def reject(self, *, requeue=True): """ Reject the message. :keyword bool requeue: if true, the broker will attempt to requeue the message and deliver it to an alternate consumer. """ self.sender.send_BasicReject(self.delivery_tag, requeue)
Declare an: class: Exchange on the broker. If the exchange does not exist it will be created.
def declare_exchange(self, name, type, *, durable=True, auto_delete=False, passive=False, internal=False, nowait=False, arguments=None): """ Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created. This met...
Declare a queue on the broker. If the queue does not exist it will be created.
def declare_queue(self, name='', *, durable=True, exclusive=False, auto_delete=False, passive=False, nowait=False, arguments=None): """ Declare a queue on the broker. If the queue does not exist, it will be created. This method is a :ref:`coroutine <c...
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.
def set_qos(self, prefetch_size=0, prefetch_count=0, apply_globally=False): """ 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 unacknowledge...
Close the channel by handshaking with the server.
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 close if not self.is_closed(): self._closing = True # Let the ChannelActor do...
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 self.sender.send_CloseOK() exc = ex...
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) exc = ChannelClosed() self._c...
Bind a queue to an exchange with the supplied routing key.
def bind(self, exchange, routing_key, *, arguments=None): """ 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 <coroutin...
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.
def consume(self, callback, *, no_local=False, no_ack=False, exclusive=False, arguments=None): """ 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: ...
Synchronously get a message from the queue.
def get(self, *, no_ack=False): """ 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.IncomingMess...
Purge all undelivered messages from the queue.
def purge(self): """ Purge all undelivered messages from the queue. This method is a :ref:`coroutine <coroutine>`. """ self.sender.send_QueuePurge(self.name) yield from self.synchroniser.wait(spec.QueuePurgeOK) self.reader.ready()
Delete the queue.
def delete(self, *, if_unused=True, if_empty=True): """ 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 ...
Unbind the queue from the exchange.
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 already unbound from exchange {}".format(self.queue.name, self.exchange.name)) self.send...
Cancel the consumer and stop recieving messages.
def cancel(self): """ Cancel the consumer and stop recieving messages. This method is a :ref:`coroutine <coroutine>`. """ self.sender.send_BasicCancel(self.tag) try: yield from self.synchroniser.wait(spec.BasicCancelOK) except AMQPError: p...
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 communications channel channel = yield from connection.open_chan...
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 others for method, futs in self._futures.items(): for fut in futs: ...
Connect to an AMQP server on the given host and port.
def connect(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, loop=None, sock=None, **kwargs): """ Connect to an AMQP server on the given host and port. Log in to the given virtual host...
Connect to an AMQP server and open a channel on the connection. This function is a: ref: coroutine <coroutine >.
def connect_and_open_channel(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, loop=None, **kwargs): """ ...
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') poison_frame = frames.PoisonPillFrame(poison_...
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) for item in value] value = convert_to_imgur_list(value) ...
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())
Handle a few expected values for rendering the current choice.
def render(self, name, value, attrs=None, *args, **kwargs): """Handle a few expected values for rendering the current choice. Extracts the state name from StateWrapper and State object. """ if isinstance(value, base.StateWrapper): state_name = value.state.name elif i...
Contribute the state to a Model.
def contribute_to_class(self, cls, name): """Contribute the state to a Model. Attaches a StateFieldProperty to wrap the attribute. """ super(StateField, self).contribute_to_class(cls, name) parent_property = getattr(cls, self.name, None) setattr(cls, self.name, StateFie...
Converts the DB - stored value into a Python value.
def to_python(self, value): """Converts the DB-stored value into a Python value.""" if isinstance(value, base.StateWrapper): res = value else: if isinstance(value, base.State): state = value elif value is None: state = self.work...
Convert a value to DB storage.
def get_db_prep_value(self, value, connection, prepared=False): """Convert a value to DB storage. Returns the state name. """ if not prepared: value = self.get_prep_value(value) return value.state.name
Convert a field value to a string.
def value_to_string(self, obj): """Convert a field value to a string. Returns the state name. """ statefield = self.to_python(self.value_from_object(obj)) return statefield.state.name
Validate that a given value is a valid option for a given model instance.
def validate(self, value, model_instance): """Validate that a given value is a valid option for a given model instance. Args: value (xworkflows.base.StateWrapper): The base.StateWrapper returned by to_python. model_instance: A WorkflowEnabled instance """ if not ...
Deconstruction for migrations.
def deconstruct(self): """Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django doesn't like deconstructing metaclass-built classes. """ name, path, args, kwargs = super(StateField, self).de...
Find workflow definition ( s ) in a WorkflowEnabled definition.
def _find_workflows(mcs, attrs): """Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects. """ workflows = {} for k, v in attrs.items(): if isinsta...
Cache for fetching the actual log model object once django is loaded.
def _get_log_model_class(self): """Cache for fetching the actual log model object once django is loaded. Otherwise, import conflict occur: WorkflowEnabled imports <log_model> which tries to import all models to retrieve the proper model class. """ if self.log_model_class is not ...
Logs the transition into the database.
def db_log(self, transition, from_state, instance, *args, **kwargs): """Logs the transition into the database.""" if self.log_model: model_class = self._get_log_model_class() extras = {} for db_field, transition_arg, default in model_class.EXTRA_LOG_ATTRIBUTES: ...
Generic transition logging.
def log_transition(self, transition, from_state, instance, *args, **kwargs): """Generic transition logging.""" save = kwargs.pop('save', True) log = kwargs.pop('log', True) super(Workflow, self).log_transition( transition, from_state, instance, *args, **kwargs) if sav...
Cleanup README. rst for proper PyPI formatting.
def clean_readme(fname): """Cleanup README.rst for proper PyPI formatting.""" with codecs.open(fname, 'r', 'utf-8') as f: return ''.join( re.sub(r':\w+:`([^`]+?)( <[^<>]+>)?`', r'``\1``', line) for line in f if not (line.startswith('.. currentmodule') or line.startswi...
Return a gallery image/ album depending on what the json represent.
def _get_album_or_image(json, imgur): """Return a gallery image/album depending on what the json represent.""" if json['is_album']: return Gallery_album(json, imgur, has_fetched=False) return Gallery_image(json, imgur)
Refresh this objects attributes to the newest values.
def refresh(self): """ Refresh this objects attributes to the newest values. Attributes that weren't added to the object before, due to lazy loading, will be added by calling refresh. """ resp = self._imgur._send_request(self._INFO_URL) self._populate(resp) ...
Add images to the album.
def add_images(self, images): """ Add images to the album. :param images: A list of the images we want to add to the album. Can be Image objects, ids or a combination of the two. Images that you cannot add (non-existing or not owned by you) will not cause ex...
Remove images from the album.
def remove_images(self, images): """ Remove images from the album. :param images: A list of the images we want to remove from the album. Can be Image objects, ids or a combination of the two. Images that you cannot remove (non-existing, not owned by you or not part of ...
Set the images in this album.
def set_images(self, images): """ Set the images in this album. :param images: A list of the images we want the album to contain. Can be Image objects, ids or a combination of the two. Images that images that you cannot set (non-existing or not owned by you) will ...
Add this to the gallery.
def submit_to_gallery(self, title, bypass_terms=False): """ Add this to the gallery. Require that the authenticated user has accepted gallery terms and verified their email. :param title: The title of the new gallery item. :param bypass_terms: If the user has not accept...
Update the album s information.
def update(self, title=None, description=None, images=None, cover=None, layout=None, privacy=None): """ Update the album's information. Arguments with the value None will retain their old values. :param title: The title of the album. :param description: A descrip...
Get the replies to this comment.
def get_replies(self): """Get the replies to this comment.""" url = self._imgur._base_url + "/3/comment/{0}/replies".format(self.id) json = self._imgur._send_request(url) child_comments = json['children'] return [Comment(com, self._imgur) for com in child_comments]
Make a top - level comment to this.
def comment(self, text): """ Make a top-level comment to this. :param text: The comment text. """ url = self._imgur._base_url + "/3/comment" payload = {'image_id': self.id, 'comment': text} resp = self._imgur._send_request(url, params=payload, needs_auth=True, ...
Dislike this.
def downvote(self): """ Dislike this. A downvote will replace a neutral vote or an upvote. Downvoting something the authenticated user has already downvoted will set the vote to neutral. """ url = self._imgur._base_url + "/3/gallery/{0}/vote/down".format(self.id)...
Get a list of the top - level comments.
def get_comments(self): """Get a list of the top-level comments.""" url = self._imgur._base_url + "/3/gallery/{0}/comments".format(self.id) resp = self._imgur._send_request(url) return [Comment(com, self._imgur) for com in resp]
Remove this image from the gallery.
def remove_from_gallery(self): """Remove this image from the gallery.""" url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) self._imgur._send_request(url, needs_auth=True, method='DELETE') if isinstance(self, Image): item = self._imgur.get_image(self.id) e...