_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q256200
AccessControlList.deny
validation
def deny(self, role, method, resource, with_children=False): """Add denying rules. :param role: Role of this rule. :param method: Method to deny in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Deny role's children in rule ...
python
{ "resource": "" }
q256201
AccessControlList.exempt
validation
def exempt(self, resource): """Exempt a view function from being checked permission :param resource: The view function exempt from checking. """ if resource not in self._exempt: self._exempt.append(resource)
python
{ "resource": "" }
q256202
AccessControlList.is_allowed
validation
def is_allowed(self, role, method, resource): """Check whether role is allowed to access resource :param role: Role to be checked. :param method: Method to be checked. :param resource: View function to be checked. """ return (role, method, resource) in self._allowed
python
{ "resource": "" }
q256203
AccessControlList.is_denied
validation
def is_denied(self, role, method, resource): """Check wherther role is denied to access resource :param role: Role to be checked. :param method: Method to be checked. :param resource: View function to be checked. """ return (role, method, resource) in self._denied
python
{ "resource": "" }
q256204
RBAC.allow
validation
def allow(self, roles, methods, with_children=True): """This is a decorator function. You can allow roles to access the view func with it. An example:: @app.route('/website/setting', methods=['GET', 'POST']) @rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])...
python
{ "resource": "" }
q256205
remove_binaries
validation
def remove_binaries(): """Remove all binary files in the adslib directory.""" patterns = ( "adslib/*.a", "adslib/*.o", "adslib/obj/*.o", "adslib/*.bin", "adslib/*.so", ) for f in functools.reduce(operator.iconcat, [glob.glob(p) for p in patterns]): ...
python
{ "resource": "" }
q256206
router_function
validation
def router_function(fn): # type: (Callable) -> Callable """Raise a runtime error if on Win32 systems. Decorator. Decorator for functions that interact with the router for the Linux implementation of the ADS library. Unlike the Windows implementation which uses a separate router daemon, th...
python
{ "resource": "" }
q256207
adsAddRoute
validation
def adsAddRoute(net_id, ip_address): # type: (SAmsNetId, str) -> None """Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint """ add_route = _adsDLL.AdsAddRoute add_route.restyp...
python
{ "resource": "" }
q256208
adsPortCloseEx
validation
def adsPortCloseEx(port): # type: (int) -> None """Close the connection to the TwinCAT message router.""" port_close_ex = _adsDLL.AdsPortCloseEx port_close_ex.restype = ctypes.c_long error_code = port_close_ex(port) if error_code: raise ADSError(error_code)
python
{ "resource": "" }
q256209
adsGetLocalAddressEx
validation
def adsGetLocalAddressEx(port): # type: (int) -> AmsAddr """Return the local AMS-address and the port number. :rtype: pyads.structs.AmsAddr :return: AMS-address """ get_local_address_ex = _adsDLL.AdsGetLocalAddressEx ams_address_struct = SAmsAddr() error_code = get_local_address_ex(por...
python
{ "resource": "" }
q256210
adsSyncReadStateReqEx
validation
def adsSyncReadStateReqEx(port, address): # type: (int, AmsAddr) -> Tuple[int, int] """Read the current ADS-state and the machine-state. Read the current ADS-state and the machine-state from the ADS-server. :param pyads.structs.AmsAddr address: local or remote AmsAddr :rtype: (int, int) :r...
python
{ "resource": "" }
q256211
adsSyncReadDeviceInfoReqEx
validation
def adsSyncReadDeviceInfoReqEx(port, address): # type: (int, AmsAddr) -> Tuple[str, AdsVersion] """Read the name and the version number of the ADS-server. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :rtype: string, Ads...
python
{ "resource": "" }
q256212
adsSyncWriteControlReqEx
validation
def adsSyncWriteControlReqEx( port, address, ads_state, device_state, data, plc_data_type ): # type: (int, AmsAddr, int, int, Any, Type) -> None """Change the ADS state and the machine-state of the ADS-server. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAd...
python
{ "resource": "" }
q256213
adsSyncWriteReqEx
validation
def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type): # type: (int, AmsAddr, int, int, Any, Type) -> None """Send data synchronous to an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsA...
python
{ "resource": "" }
q256214
adsSyncReadReqEx2
validation
def adsSyncReadReqEx2( port, address, index_group, index_offset, data_type, return_ctypes=False ): # type: (int, AmsAddr, int, int, Type, bool) -> Any """Read data synchronous from an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: lo...
python
{ "resource": "" }
q256215
adsSyncReadByNameEx
validation
def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False): # type: (int, AmsAddr, str, Type, bool) -> Any """Read data synchronous from an ADS-device from data name. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or rem...
python
{ "resource": "" }
q256216
adsSyncWriteByNameEx
validation
def adsSyncWriteByNameEx(port, address, data_name, value, data_type): # type: (int, AmsAddr, str, Any, Type) -> None """Send data synchronous to an ADS-device from data name. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr ...
python
{ "resource": "" }
q256217
adsSyncAddDeviceNotificationReqEx
validation
def adsSyncAddDeviceNotificationReqEx( port, adr, data_name, pNoteAttrib, callback, user_handle=None ): # type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int] """Add a device notification. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs...
python
{ "resource": "" }
q256218
adsSyncDelDeviceNotificationReqEx
validation
def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle): # type: (int, AmsAddr, int, int) -> None """Remove a device notification. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr adr: local or remote AmsAddr :param int notificat...
python
{ "resource": "" }
q256219
adsSyncSetTimeoutEx
validation
def adsSyncSetTimeoutEx(port, nMs): # type: (int, int) -> None """Set Timeout. :param int port: local AMS port as returned by adsPortOpenEx() :param int nMs: timeout in ms """ adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx cms = ctypes.c_long(nMs) err_code = adsSyncSetTimeoutFct(po...
python
{ "resource": "" }
q256220
OfficialMissionsDataset._generate_ranges
validation
def _generate_ranges(start_date, end_date): """ Generate a list of 2 month ranges for the range requested with an intersection between months. This is necessary because we can't search for ranges longer than 3 months and the period searched has to encompass the whole period of th...
python
{ "resource": "" }
q256221
DeputiesDataset.fetch
validation
def fetch(self): """ Fetches the list of deputies for the current term. """ xml = urllib.request.urlopen(self.URL) tree = ET.ElementTree(file=xml) records = self._parse_deputies(tree.getroot()) df = pd.DataFrame(records, columns=( 'congressperson_id'...
python
{ "resource": "" }
q256222
HashRing.remove_node
validation
def remove_node(self, node): """Removes `node` from the hash ring and its replicas. """ self.nodes.remove(node) for x in xrange(self.replicas): ring_key = self.hash_method(b("%s:%d" % (node, x))) self.ring.pop(ring_key) self.sorted_keys.remove(ring_key...
python
{ "resource": "" }
q256223
RedisShardAPI.mget
validation
def mget(self, keys, *args): """ Returns a list of values ordered identically to ``keys`` """ args = list_or_args(keys, args) server_keys = {} ret_dict = {} for key in args: server_name = self.get_server_name(key) server_keys[server_name] =...
python
{ "resource": "" }
q256224
RedisShardAPI.lock
validation
def lock(self, name, timeout=None, sleep=0.1): """ Return a new Lock object using key ``name`` that mimics the behavior of threading.Lock. If specified, ``timeout`` indicates a maximum life for the lock. By default, it will remain locked until release() is called. ``sle...
python
{ "resource": "" }
q256225
parse_line
validation
def parse_line(line, document=None): ''' Return a language-server diagnostic from a line of the Mypy error report; optionally, use the whole document to provide more context on it. ''' result = re.match(line_pattern, line) if result: _, lineno, offset, severity, msg = result.groups() ...
python
{ "resource": "" }
q256226
WebSocket.connect
validation
async def connect(self): """ Establishes a connection to the Lavalink server. """ await self._lavalink.bot.wait_until_ready() if self._ws and self._ws.open: log.debug('WebSocket still open, closing...') await self._ws.close() user_id = self._lavalink.bot...
python
{ "resource": "" }
q256227
WebSocket.listen
validation
async def listen(self): """ Waits to receive a payload from the Lavalink server and processes it. """ while not self._shutdown: try: data = json.loads(await self._ws.recv()) except websockets.ConnectionClosed as error: log.warning('Disconnect...
python
{ "resource": "" }
q256228
DefaultPlayer.connected_channel
validation
def connected_channel(self): """ Returns the voice channel the player is connected to. """ if not self.channel_id: return None return self._lavalink.bot.get_channel(int(self.channel_id))
python
{ "resource": "" }
q256229
DefaultPlayer.connect
validation
async def connect(self, channel_id: int): """ Connects to a voice channel. """ ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id)) await ws.voice_state(self.guild_id, str(channel_id))
python
{ "resource": "" }
q256230
DefaultPlayer.disconnect
validation
async def disconnect(self): """ Disconnects from the voice channel, if any. """ if not self.is_connected: return await self.stop() ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id)) await ws.voice_state(self.guild_id, None)
python
{ "resource": "" }
q256231
DefaultPlayer.store
validation
def store(self, key: object, value: object): """ Stores custom user data. """ self._user_data.update({key: value})
python
{ "resource": "" }
q256232
DefaultPlayer.fetch
validation
def fetch(self, key: object, default=None): """ Retrieves the related value from the stored user data. """ return self._user_data.get(key, default)
python
{ "resource": "" }
q256233
DefaultPlayer.add
validation
def add(self, requester: int, track: dict): """ Adds a track to the queue. """ self.queue.append(AudioTrack().build(track, requester))
python
{ "resource": "" }
q256234
DefaultPlayer.add_next
validation
def add_next(self, requester: int, track: dict): """ Adds a track to beginning of the queue """ self.queue.insert(0, AudioTrack().build(track, requester))
python
{ "resource": "" }
q256235
DefaultPlayer.add_at
validation
def add_at(self, index: int, requester: int, track: dict): """ Adds a track at a specific index in the queue. """ self.queue.insert(min(index, len(self.queue) - 1), AudioTrack().build(track, requester))
python
{ "resource": "" }
q256236
DefaultPlayer.play
validation
async def play(self, track_index: int = 0, ignore_shuffle: bool = False): """ Plays the first track in the queue, if any or plays a track from the specified index in the queue. """ if self.repeat and self.current: self.queue.append(self.current) self.previous = self.current ...
python
{ "resource": "" }
q256237
DefaultPlayer.play_now
validation
async def play_now(self, requester: int, track: dict): """ Add track and play it. """ self.add_next(requester, track) await self.play(ignore_shuffle=True)
python
{ "resource": "" }
q256238
DefaultPlayer.play_at
validation
async def play_at(self, index: int): """ Play the queue from a specific point. Disregards tracks before the index. """ self.queue = self.queue[min(index, len(self.queue) - 1):len(self.queue)] await self.play(ignore_shuffle=True)
python
{ "resource": "" }
q256239
DefaultPlayer.play_previous
validation
async def play_previous(self): """ Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. """ if not self.previous: raise NoPreviousTrack self.queue.insert(0, self.previous) await self.play(ignore_shuffle=True)
python
{ "resource": "" }
q256240
DefaultPlayer.stop
validation
async def stop(self): """ Stops the player, if playing. """ await self._lavalink.ws.send(op='stop', guildId=self.guild_id) self.current = None
python
{ "resource": "" }
q256241
DefaultPlayer.set_pause
validation
async def set_pause(self, pause: bool): """ Sets the player's paused state. """ await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause) self.paused = pause
python
{ "resource": "" }
q256242
DefaultPlayer.seek
validation
async def seek(self, pos: int): """ Seeks to a given position in the track. """ await self._lavalink.ws.send(op='seek', guildId=self.guild_id, position=pos)
python
{ "resource": "" }
q256243
DefaultPlayer.handle_event
validation
async def handle_event(self, event): """ Makes the player play the next song from the queue if a song has finished or an issue occurred. """ if isinstance(event, (TrackStuckEvent, TrackExceptionEvent)) or \ isinstance(event, TrackEndEvent) and event.reason == 'FINISHED': ...
python
{ "resource": "" }
q256244
PlayerManager.get
validation
def get(self, guild_id): """ Returns a player from the cache, or creates one if it does not exist. """ if guild_id not in self._players: p = self._player(lavalink=self.lavalink, guild_id=guild_id) self._players[guild_id] = p return self._players[guild_id]
python
{ "resource": "" }
q256245
PlayerManager.remove
validation
def remove(self, guild_id): """ Removes a player from the current players. """ if guild_id in self._players: self._players[guild_id].cleanup() del self._players[guild_id]
python
{ "resource": "" }
q256246
Music._play
validation
async def _play(self, ctx, *, query: str): """ Searches and plays a song from a given query. """ player = self.bot.lavalink.players.get(ctx.guild.id) query = query.strip('<>') if not url_rx.match(query): query = f'ytsearch:{query}' tracks = await self.bot....
python
{ "resource": "" }
q256247
Music._seek
validation
async def _seek(self, ctx, *, time: str): """ Seeks to a given position in a track. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send('Not playing.') seconds = time_rx.search(time) if not seconds: ...
python
{ "resource": "" }
q256248
Music._now
validation
async def _now(self, ctx): """ Shows some stats about the currently playing song. """ player = self.bot.lavalink.players.get(ctx.guild.id) song = 'Nothing' if player.current: position = lavalink.Utils.format_time(player.position) if player.current.stream: ...
python
{ "resource": "" }
q256249
Music._queue
validation
async def _queue(self, ctx, page: int = 1): """ Shows the player's queue. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send('There\'s nothing in the queue! Why not queue something?') items_per_page = 10 pages...
python
{ "resource": "" }
q256250
Music._remove
validation
async def _remove(self, ctx, index: int): """ Removes an item from the player's queue with the given index. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send('Nothing queued.') if index > len(player.queue) or index < ...
python
{ "resource": "" }
q256251
Music.ensure_voice
validation
async def ensure_voice(self, ctx): """ A few checks to make sure the bot can join a voice channel. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_connected: if not ctx.author.voice or not ctx.author.voice.channel: await ctx.send('You ...
python
{ "resource": "" }
q256252
Client.unregister_hook
validation
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)
python
{ "resource": "" }
q256253
Client.dispatch_event
validation
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): ...
python
{ "resource": "" }
q256254
Client.update_state
validation
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...
python
{ "resource": "" }
q256255
Client.get_tracks
validation
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...
python
{ "resource": "" }
q256256
Client.destroy
validation
def destroy(self): """ Destroys the Lavalink client. """ self.ws.destroy() self.bot.remove_listener(self.on_socket_response) self.hooks.clear()
python
{ "resource": "" }
q256257
AudioTrack.build
validation
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...
python
{ "resource": "" }
q256258
Music._previous
validation
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.')
python
{ "resource": "" }
q256259
Music._playnow
validation
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...
python
{ "resource": "" }
q256260
Music._playat
validation
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...
python
{ "resource": "" }
q256261
Music._find
validation
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...
python
{ "resource": "" }
q256262
AutoCompleter.add_suggestions
validation
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....
python
{ "resource": "" }
q256263
AutoCompleter.delete
validation
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)
python
{ "resource": "" }
q256264
AutoCompleter.get_suggestions
validation
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**:...
python
{ "resource": "" }
q256265
Client.create_index
validation
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...
python
{ "resource": "" }
q256266
Client._add_document
validation
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 ...
python
{ "resource": "" }
q256267
Client.add_document
validation
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...
python
{ "resource": "" }
q256268
Client.delete_document
validation
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)
python
{ "resource": "" }
q256269
Client.load_document
validation
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: ...
python
{ "resource": "" }
q256270
Client.info
validation
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))
python
{ "resource": "" }
q256271
Client.search
validation
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...
python
{ "resource": "" }
q256272
Client.aggregate
validation
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 ...
python
{ "resource": "" }
q256273
Reducer.alias
validation
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...
python
{ "resource": "" }
q256274
AggregateRequest.group_by
validation
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`. ...
python
{ "resource": "" }
q256275
AggregateRequest.apply
validation
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,...
python
{ "resource": "" }
q256276
AggregateRequest.limit
validation
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...
python
{ "resource": "" }
q256277
Query.get_args
validation
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)) ...
python
{ "resource": "" }
q256278
Query.sort_by
validation
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
python
{ "resource": "" }
q256279
between
validation
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)
python
{ "resource": "" }
q256280
geo
validation
def geo(lat, lon, radius, unit='km'): """ Indicate that value is a geo region """ return GeoValue(lat, lon, radius, unit)
python
{ "resource": "" }
q256281
Bypass.transform
validation
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...
python
{ "resource": "" }
q256282
transpose
validation
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...
python
{ "resource": "" }
q256283
jam_pack
validation
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...
python
{ "resource": "" }
q256284
load_jam_audio
validation
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-...
python
{ "resource": "" }
q256285
save
validation
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...
python
{ "resource": "" }
q256286
__reconstruct
validation
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...
python
{ "resource": "" }
q256287
serialize
validation
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...
python
{ "resource": "" }
q256288
deserialize
validation
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 ...
python
{ "resource": "" }
q256289
_pprint
validation
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...
python
{ "resource": "" }
q256290
BaseTransformer._get_param_names
validation
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...
python
{ "resource": "" }
q256291
BaseTransformer._transform
validation
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 -----...
python
{ "resource": "" }
q256292
BaseTransformer.transform
validation
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 --------...
python
{ "resource": "" }
q256293
Pipeline.__recursive_transform
validation
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...
python
{ "resource": "" }
q256294
Union.__serial_transform
validation
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...
python
{ "resource": "" }
q256295
sample_clip_indices
validation
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...
python
{ "resource": "" }
q256296
slice_clip
validation
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 ...
python
{ "resource": "" }
q256297
norm_remote_path
validation
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
python
{ "resource": "" }
q256298
split_storage
validation
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 ...
python
{ "resource": "" }
q256299
file_empty
validation
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()
python
{ "resource": "" }