Search is not available for this dataset
text
stringlengths
75
104k
def unregister_hook(self, func): """ Unregisters a hook. For further explanation, please have a look at ``register_hook``. """ if func in self.hooks: self.hooks.remove(func)
async def dispatch_event(self, event): """ Dispatches an event to all registered hooks. """ log.debug('Dispatching event of type {} to {} hooks'.format(event.__class__.__name__, len(self.hooks))) for hook in self.hooks: try: if asyncio.iscoroutinefunction(hook): ...
async def update_state(self, data): """ Updates a player's state when a payload with opcode ``playerUpdate`` is received. """ guild_id = int(data['guildId']) if guild_id in self.players: player = self.players.get(guild_id) player.position = data['state'].get('posit...
async def get_tracks(self, query): """ Returns a Dictionary containing search results for a given query. """ log.debug('Requesting tracks for query {}'.format(query)) async with self.http.get(self.rest_uri + quote(query), headers={'Authorization': self.password}) as res: return...
async def on_socket_response(self, data): """ This coroutine will be called every time an event from Discord is received. It is used to update a player's voice state through forwarding a payload via the WebSocket connection to Lavalink. ------------- :param data: ...
def destroy(self): """ Destroys the Lavalink client. """ self.ws.destroy() self.bot.remove_listener(self.on_socket_response) self.hooks.clear()
def format_time(time): """ Formats the given time into HH:MM:SS. """ hours, remainder = divmod(time / 1000, 3600) minutes, seconds = divmod(remainder, 60) return '%02d:%02d:%02d' % (hours, minutes, seconds)
def build(self, track, requester): """ Returns an optional AudioTrack. """ try: self.track = track['track'] self.identifier = track['info']['identifier'] self.can_seek = track['info']['isSeekable'] self.author = track['info']['author'] s...
async def _previous(self, ctx): """ Plays the previous song. """ player = self.bot.lavalink.players.get(ctx.guild.id) try: await player.play_previous() except lavalink.NoPreviousTrack: await ctx.send('There is no previous song to play.')
async def _playnow(self, ctx, *, query: str): """ Plays immediately a song. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue and not player.is_playing: return await ctx.invoke(self._play, query=query) query = query.strip('<>') i...
async def _playat(self, ctx, index: int): """ Plays the queue from a specific point. Disregards tracks before the index. """ player = self.bot.lavalink.players.get(ctx.guild.id) if index < 1: return await ctx.send('Invalid specified index.') if len(player.queue) < in...
async def _find(self, ctx, *, query): """ Lists the first 10 search results from a given query. """ if not query.startswith('ytsearch:') and not query.startswith('scsearch:'): query = 'ytsearch:' + query results = await self.bot.lavalink.get_tracks(query) if not resu...
def add_suggestions(self, *suggestions, **kwargs): """ Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string. If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores """ pipe = self.redis....
def delete(self, string): """ Delete a string from the AutoCompleter index. Returns 1 if the string was found and deleted, 0 otherwise """ return self.redis.execute_command(AutoCompleter.SUGDEL_COMMAND, self.key, string)
def get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False): """ Get a list of suggestions from the AutoCompleter, for a given prefix ### Parameters: - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8** - **fuzzy**:...
def create_index(self, fields, no_term_offsets=False, no_field_flags=False, stopwords = None): """ Create the search index. The index must not already exist. ### Parameters: - **fields**: a list of TextField or NumericField objects - **no_term_offsets**: If...
def _add_document(self, doc_id, conn=None, nosave=False, score=1.0, payload=None, replace=False, partial=False, language=None, **fields): """ Internal add_document used for both batch and single doc indexing """ if conn is None: conn = self.redis ...
def add_document(self, doc_id, nosave=False, score=1.0, payload=None, replace=False, partial=False, language=None, **fields): """ Add a single document to the index. ### Parameters - **doc_id**: the id of the saved document. - **nosave**: if set to true, we...
def delete_document(self, doc_id, conn=None): """ Delete a document from index Returns 1 if the document was deleted, 0 if not """ if conn is None: conn = self.redis return conn.execute_command(self.DEL_CMD, self.index_name, doc_id)
def load_document(self, id): """ Load a single document by id """ fields = self.redis.hgetall(id) if six.PY3: f2 = {to_string(k): to_string(v) for k, v in fields.items()} fields = f2 try: del fields['id'] except KeyError: ...
def info(self): """ Get info an stats about the the current index, including the number of documents, memory consumption, etc """ res = self.redis.execute_command('FT.INFO', self.index_name) it = six.moves.map(to_string, res) return dict(six.moves.zip(it, it))
def search(self, query): """ Search the index for a given query, and return a result of documents ### Parameters - **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries. See RediSearch's documen...
def aggregate(self, query): """ Issue an aggregation query ### Parameters **query**: This can be either an `AggeregateRequest`, or a `Cursor` An `AggregateResult` object is returned. You can access the rows from its `rows` property, which will always yield the rows of ...
def alias(self, alias): """ Set the alias for this reducer. ### Parameters - **alias**: The value of the alias for this reducer. If this is the special value `aggregation.FIELDNAME` then this reducer will be aliased using the same name as the field upon which it...
def group_by(self, fields, *reducers): """ Specify by which fields to group the aggregation. ### Parameters - **fields**: Fields to group by. This can either be a single string, or a list of strings. both cases, the field should be specified as `@field`. ...
def apply(self, **kwexpr): """ Specify one or more projection expressions to add to each result ### Parameters - **kwexpr**: One or more key-value pairs for a projection. The key is the alias for the projection, and the value is the projection expression itself,...
def limit(self, offset, num): """ Sets the limit for the most recent group or query. If no group has been defined yet (via `group_by()`) then this sets the limit for the initial pool of results from the query. Otherwise, this limits the number of items operated on from the previ...
def sort_by(self, *fields, **kwargs): """ Indicate how the results should be sorted. This can also be used for *top-N* style queries ### Parameters - **fields**: The fields by which to sort. This can be either a single field or a list of fields. If you wish to speci...
def summarize(self, fields=None, context_len=None, num_frags=None, sep=None): """ Return an abridged format of the field, containing only the segments of the field which contain the matching term(s). If `fields` is specified, then only the mentioned fields are summarized; otherw...
def highlight(self, fields=None, tags=None): """ Apply specified markup to matched term(s) within the returned field(s) - **fields** If specified then only those mentioned fields are highlighted, otherwise all fields are highlighted - **tags** A list of two strings to surround the match...
def get_args(self): """ Format the redis arguments for this query and return them """ args = [self._query_string] if self._no_content: args.append('NOCONTENT') if self._fields: args.append('INFIELDS') args.append(len(self._fields)) ...
def paging(self, offset, num): """ Set the paging for the query (defaults to 0..10). - **offset**: Paging offset for the results. Defaults to 0 - **num**: How many results do we want """ self._offset = offset self._num = num return self
def sort_by(self, field, asc=True): """ Add a sortby field to the query - **field** - the name of the field to sort by - **asc** - when `True`, sorting will be done in asceding order """ self._sortby = SortbyField(field, asc) return self
def between(a, b, inclusive_min=True, inclusive_max=True): """ Indicate that value is a numeric range """ return RangeValue(a, b, inclusive_min=inclusive_min, inclusive_max=inclusive_max)
def geo(lat, lon, radius, unit='km'): """ Indicate that value is a geo region """ return GeoValue(lat, lon, radius, unit)
def transform(self, jam): '''Bypass transformations. Parameters ---------- jam : pyjams.JAMS A muda-enabled JAMS object Yields ------ jam_out : pyjams.JAMS iterator The first result is `jam` (unmodified), by reference All subs...
def __sox(y, sr, *args): '''Execute sox Parameters ---------- y : np.ndarray Audio time series sr : int > 0 Sampling rate of `y` *args Additional arguments to sox Returns ------- y_out : np.ndarray `y` after sox transformation ''' assert s...
def transpose(label, n_semitones): '''Transpose a chord label by some number of semitones Parameters ---------- label : str A chord string n_semitones : float The number of semitones to move `label` Returns ------- label_transpose : str The transposed chord lab...
def jam_pack(jam, **kwargs): '''Pack data into a jams sandbox. If not already present, this creates a `muda` field within `jam.sandbox`, along with `history`, `state`, and version arrays which are populated by deformation objects. Any additional fields can be added to the `muda` sandbox by supplyi...
def load_jam_audio(jam_in, audio_file, validate=True, strict=True, fmt='auto', **kwargs): '''Load a jam and pack it with audio. Parameters ---------- jam_in : str, file descriptor, or jams.JAMS JAMS filename, open file-...
def save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs): '''Save a muda jam to disk Parameters ---------- filename_audio: str The path to store the audio file filename_jam: str The path to store the jams object strict: bool Strict safety checking...
def __reconstruct(params): '''Reconstruct a transformation or pipeline given a parameter dump.''' if isinstance(params, dict): if '__class__' in params: cls = params['__class__'] data = __reconstruct(params['params']) return cls(**data) else: data...
def serialize(transform, **kwargs): '''Serialize a transformation object or pipeline. Parameters ---------- transform : BaseTransform or Pipeline The transformation object to be serialized kwargs Additional keyword arguments to `jsonpickle.encode()` Returns ------- jso...
def deserialize(encoded, **kwargs): '''Construct a muda transformation from a JSON encoded string. Parameters ---------- encoded : str JSON encoding of the transformation or pipeline kwargs Additional keyword arguments to `jsonpickle.decode()` Returns ------- obj ...
def _pprint(params, offset=0, printer=repr): """Pretty print the dictionary 'params' Parameters ---------- params: dict The dictionary to pretty print offset: int The offset in characters to add at the begin of each line. printer: The function to convert entries to str...
def _get_param_names(cls): '''Get the list of parameter names for the object''' init = cls.__init__ args, varargs = inspect.getargspec(init)[:2] if varargs is not None: raise RuntimeError('BaseTransformer objects cannot have varargs') args.pop(0) args.sort...
def get_params(self, deep=True): '''Get the parameters for this object. Returns as a dict. Parameters ---------- deep : bool Recurse on nested objects Returns ------- params : dict A dictionary containing all parameters for this object ...
def _transform(self, jam, state): '''Apply the transformation to audio and annotations. The input jam is copied and modified, and returned contained in a list. Parameters ---------- jam : jams.JAMS A single jam object to modify Returns -----...
def transform(self, jam): '''Iterative transformation generator Applies the deformation to an input jams object. This generates a sequence of deformed output JAMS. Parameters ---------- jam : jams.JAMS The jam to transform Examples --------...
def get_params(self): '''Get the parameters for this object. Returns as a dict.''' out = {} out['__class__'] = self.__class__ out['params'] = dict(steps=[]) for name, step in self.steps: out['params']['steps'].append([name, step.get_params(deep=True)]) ret...
def __recursive_transform(self, jam, steps): '''A recursive transformation pipeline''' if len(steps) > 0: head_transformer = steps[0][1] for t_jam in head_transformer.transform(jam): for q in self.__recursive_transform(t_jam, steps[1:]): yield...
def transform(self, jam): '''Apply the sequence of transformations to a single jam object. Parameters ---------- jam : jams.JAMS The jam object to transform Yields ------ jam_out : jams.JAMS The jam objects produced by the transformation ...
def __serial_transform(self, jam, steps): '''A serial transformation union''' # This uses the round-robin itertools recipe if six.PY2: attr = 'next' else: attr = '__next__' pending = len(steps) nexts = itertools.cycle(getattr(iter(D.transform(jam...
def transform(self, jam): '''Apply the sequence of transformations to a single jam object. Parameters ---------- jam : jams.JAMS The jam object to transform Yields ------ jam_out : jams.JAMS The jam objects produced by each member of the ...
def sample_clip_indices(filename, n_samples, sr): '''Calculate the indices at which to sample a fragment of audio from a file. Parameters ---------- filename : str Path to the input file n_samples : int > 0 The number of samples to load sr : int > 0 The target sampling...
def slice_clip(filename, start, stop, n_samples, sr, mono=True): '''Slice a fragment of audio from a file. This uses pysoundfile to efficiently seek without loading the entire stream. Parameters ---------- filename : str Path to the input file start : int The sample index ...
def norm_remote_path(path): """Normalize `path`. All remote paths are absolute. """ path = os.path.normpath(path) if path.startswith(os.path.sep): return path[1:] else: return path
def split_storage(path, default='osfstorage'): """Extract storage name from file path. If a path begins with a known storage provider the name is removed from the path. Otherwise the `default` storage provider is returned and the path is not modified. """ path = norm_remote_path(path) for ...
def file_empty(fp): """Determine if a file is empty or not.""" # for python 2 we need to use a homemade peek() if six.PY2: contents = fp.read() fp.seek(0) return not bool(contents) else: return not fp.peek()
def checksum(file_path, hash_type='md5', block_size=65536): """Returns either the md5 or sha256 hash of a file at `file_path`. md5 is the default hash_type as it is faster than sha256 The default block size is 64 kb, which appears to be one of a few command choices according to https://stackoverfl...
def storage(self, provider='osfstorage'): """Return storage `provider`.""" stores = self._json(self._get(self._storages_url), 200) stores = stores['data'] for store in stores: provides = self._get_attribute(store, 'attributes', 'provider') if provides == provider:...
def storages(self): """Iterate over all storages for this projects.""" stores = self._json(self._get(self._storages_url), 200) stores = stores['data'] for store in stores: yield Storage(store, self.session)
def create_file(self, path, fp, force=False, update=False): """Store a new file at `path` in this storage. The contents of the file descriptor `fp` (opened in 'rb' mode) will be uploaded to `path` which is the full path at which to store the file. To force overwrite of an exist...
def copyfileobj(fsrc, fdst, total, length=16*1024): """Copy data from file-like object fsrc to file-like object fdst This is like shutil.copyfileobj but with a progressbar. """ with tqdm(unit='bytes', total=total, unit_scale=True) as pbar: while 1: buf = fsrc.read(length) ...
def write_to(self, fp): """Write contents of this file to a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode. """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") response = self._get(self...
def remove(self): """Remove this file from the remote storage.""" response = self._delete(self._delete_url) if response.status_code != 204: raise RuntimeError('Could not delete {}.'.format(self.path))
def update(self, fp): """Update the remote file from a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode. """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") url = self._upload_url ...
def _iter_children(self, url, kind, klass, recurse=None): """Iterate over all children of `kind` Yield an instance of `klass` when a child is of type `kind`. Uses `recurse` as the path of attributes in the JSON returned from `url` to find more children. """ children = se...
def might_need_auth(f): """Decorate a CLI function that might require authentication. Catches any UnauthorizedException raised, prints a helpful message and then exits. """ @wraps(f) def wrapper(cli_args): try: return_value = f(cli_args) except UnauthorizedException ...
def init(args): """Initialize or edit an existing .osfcli.config file.""" # reading existing config file, convert to configparser object config = config_from_file() config_ = configparser.ConfigParser() config_.add_section('osf') if 'username' not in config.keys(): config_.set('osf', 'us...
def clone(args): """Copy all files from all storages of a project. The output directory defaults to the current directory. If the project is private you need to specify a username. If args.update is True, overwrite any existing local files only if local and remote files differ. """ osf = ...
def fetch(args): """Fetch an individual file from a project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. The local path defaults to the name of the remote file. If the project is private you need ...
def list_(args): """List all files from all storages for project. If the project is private you need to specify a username. """ osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: p...
def upload(args): """Upload a new file to an existing project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. If the project is private you need to specify a username. To upload a whole directory (an...
def remove(args): """Remove a file from the project's storage. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys...
def login(self, username, password=None, token=None): """Login user for protected API calls.""" self.session.basic_auth(username, password)
def project(self, project_id): """Fetch project `project_id`.""" type_ = self.guid(project_id) url = self._build_url(type_, project_id) if type_ in Project._types: return Project(self._json(self._get(url), 200), self.session) raise OSFException('{} is unrecognized typ...
def guid(self, guid): """Determines JSONAPI type for provided GUID""" return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']
def _json(self, response, status_code): """Extract JSON from response if `status_code` matches.""" if isinstance(status_code, numbers.Integral): status_code = (status_code,) if response.status_code in status_code: return response.json() else: raise Ru...
def _follow_next(self, url): """Follow the 'next' link on paginated results.""" response = self._json(self._get(url), 200) data = response['data'] next_url = self._get_attribute(response, 'links', 'next') while next_url is not None: response = self._json(self._get(ne...
def project(*descs, root_file=None): """ Make a new project, using recursion and alias resolution. Use this function in preference to calling Project() directly. """ load.ROOT_FILE = root_file desc = merge.merge(merge.DEFAULT_PROJECT, *descs) path = desc.get('path', '') if root_file: ...
def clear(self): """Clear description to default values""" self._desc = {} for key, value in merge.DEFAULT_PROJECT.items(): if key not in self._HIDDEN: self._desc[key] = type(value)()
def update(self, desc=None, **kwds): """This method updates the description much like dict.update(), *except*: 1. for description which have dictionary values, it uses update to alter the existing value and does not replace them. 2. `None` is a special value that means "clear sectio...
def SPI(ledtype=None, num=0, **kwargs): """Wrapper function for using SPI device drivers on systems like the Raspberry Pi and BeagleBone. This allows using any of the SPI drivers from a single entry point instead importing the driver for a specific LED type. Provides the same parameters of :py:...
def put_edit(self, f, *args, **kwds): """ Defer an edit to run on the EditQueue. :param callable f: The function to be called :param tuple args: Positional arguments to the function :param tuple kwds: Keyword arguments to the function :throws queue.Full: if the queue is ...
def get_and_run_edits(self): """ Get all the edits in the queue, then execute them. The algorithm gets all edits, and then executes all of them. It does *not* pull off one edit, execute, repeat until the queue is empty, and that means that the queue might not be empty at the en...
def error(self, text): """SHOULD BE PRIVATE""" msg = 'Error with dev: {}, spi_speed: {} - {}'.format( self._dev, self._spi_speed, text) log.error(msg) raise IOError(msg)
def send_packet(self, data): """SHOULD BE PRIVATE""" package_size = 4032 # bit smaller than 4096 because of headers for i in range(int(math.ceil(len(data) / package_size))): start = i * package_size end = (i + 1) * package_size self._spi.write(data[start:end]...
def find_serial_devices(self): """Scan and report all compatible serial devices on system. :returns: List of discovered devices """ if self.devices is not None: return self.devices self.devices = {} hardware_id = "(?i)" + self.hardware_id # forces case inse...
def get_device(self, id=None): """Returns details of either the first or specified device :param int id: Identifier of desired device. If not given, first device found will be returned :returns tuple: Device ID, Device Address, Firmware Version """ if id is None: ...
def error(self, fail=True, action=''): """ SHOULD BE PRIVATE METHOD """ e = 'There was an unknown error communicating with the device.' if action: e = 'While %s: %s' % (action, e) log.error(e) if fail: raise IOError(e)
def set_device_id(self, dev, id): """Set device ID to new value. :param str dev: Serial device address/path :param id: Device ID to set """ if id < 0 or id > 255: raise ValueError("ID must be an unsigned byte!") com, code, ok = io.send_packet( CMD...
def get_device_id(self, dev): """Get device ID at given address/path. :param str dev: Serial device address/path :param baudrate: Baudrate to use when connecting (optional) """ com, code, ok = io.send_packet(CMDTYPE.GETID, 0, dev, self.baudrate, 5) if code is None: ...
def get(name=None): """ Return a named Palette, or None if no such name exists. If ``name`` is omitted, the default value is used. """ if name is None or name == 'default': return _DEFAULT_PALETTE if isinstance(name, str): return PROJECT_PALETTES.get(name) or BUILT_IN_PALETTES....
def crop(image, top_offset=0, left_offset=0, bottom_offset=0, right_offset=0): """Return an image cropped on top, bottom, left or right.""" if bottom_offset or top_offset or left_offset or right_offset: width, height = image.size box = (left_offset, top_offset, width - right_offse...
def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB', resample=None): """Return an image resized.""" if x <= 0: raise ValueError('x must be greater than zero') if y <= 0: raise ValueError('y must be greater than zero') from PIL import Image resample = I...
def extract(self, msg): """Yield an ordered dictionary if msg['type'] is in keys_by_type.""" def normal(key): v = msg.get(key) if v is None: return v normalizer = self.normalizers.get(key, lambda x: x) return normalizer(v) def odic...
def get(self, x, y): """ Return the pixel color at position (x, y), or Colors.black if that position is out-of-bounds. """ try: pixel = self.coord_map[y][x] return self._get_base(pixel) except IndexError: return colors.COLORS.Black
def drawCircle(self, x0, y0, r, color=None): """ Draw a circle in an RGB color, with center x0, y0 and radius r. """ md.draw_circle(self.set, x0, y0, r, color)
def fillCircle(self, x0, y0, r, color=None): """ Draw a filled circle in an RGB color, with center x0, y0 and radius r. """ md.fill_circle(self.set, x0, y0, r, color)