partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
Client.unregister_hook
Unregisters a hook. For further explanation, please have a look at ``register_hook``.
lavalink/Client.py
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)
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)
[ "Unregisters", "a", "hook", ".", "For", "further", "explanation", "please", "have", "a", "look", "at", "register_hook", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L100-L103
[ "def", "unregister_hook", "(", "self", ",", "func", ")", ":", "if", "func", "in", "self", ".", "hooks", ":", "self", ".", "hooks", ".", "remove", "(", "func", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Client.dispatch_event
Dispatches an event to all registered hooks.
lavalink/Client.py
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): await hook(event) else: hook(event) except Exception as e: # pylint: disable=broad-except # Catch generic exception thrown by user hooks log.warning( 'Encountered exception while dispatching an event to hook `{}` ({})'.format(hook.__name__, str(e))) if isinstance(event, (TrackEndEvent, TrackExceptionEvent, TrackStuckEvent)) and event.player: await event.player.handle_event(event)
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): await hook(event) else: hook(event) except Exception as e: # pylint: disable=broad-except # Catch generic exception thrown by user hooks log.warning( 'Encountered exception while dispatching an event to hook `{}` ({})'.format(hook.__name__, str(e))) if isinstance(event, (TrackEndEvent, TrackExceptionEvent, TrackStuckEvent)) and event.player: await event.player.handle_event(event)
[ "Dispatches", "an", "event", "to", "all", "registered", "hooks", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L105-L120
[ "async", "def", "dispatch_event", "(", "self", ",", "event", ")", ":", "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", ")", ":", "await", "hook", "(", "event", ")", "else", ":", "hook", "(", "event", ")", "except", "Exception", "as", "e", ":", "# pylint: disable=broad-except\r", "# Catch generic exception thrown by user hooks\r", "log", ".", "warning", "(", "'Encountered exception while dispatching an event to hook `{}` ({})'", ".", "format", "(", "hook", ".", "__name__", ",", "str", "(", "e", ")", ")", ")", "if", "isinstance", "(", "event", ",", "(", "TrackEndEvent", ",", "TrackExceptionEvent", ",", "TrackStuckEvent", ")", ")", "and", "event", ".", "player", ":", "await", "event", ".", "player", ".", "handle_event", "(", "event", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Client.update_state
Updates a player's state when a payload with opcode ``playerUpdate`` is received.
lavalink/Client.py
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('position', 0) player.position_timestamp = data['state']['time']
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('position', 0) player.position_timestamp = data['state']['time']
[ "Updates", "a", "player", "s", "state", "when", "a", "payload", "with", "opcode", "playerUpdate", "is", "received", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L122-L129
[ "async", "def", "update_state", "(", "self", ",", "data", ")", ":", "guild_id", "=", "int", "(", "data", "[", "'guildId'", "]", ")", "if", "guild_id", "in", "self", ".", "players", ":", "player", "=", "self", ".", "players", ".", "get", "(", "guild_id", ")", "player", ".", "position", "=", "data", "[", "'state'", "]", ".", "get", "(", "'position'", ",", "0", ")", "player", ".", "position_timestamp", "=", "data", "[", "'state'", "]", "[", "'time'", "]" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Client.get_tracks
Returns a Dictionary containing search results for a given query.
lavalink/Client.py
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 await res.json(content_type=None)
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 await res.json(content_type=None)
[ "Returns", "a", "Dictionary", "containing", "search", "results", "for", "a", "given", "query", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L131-L136
[ "async", "def", "get_tracks", "(", "self", ",", "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", "await", "res", ".", "json", "(", "content_type", "=", "None", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Client.on_socket_response
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: The payload received from Discord.
lavalink/Client.py
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: The payload received from Discord. """ # INTERCEPT VOICE UPDATES if not data or data.get('t', '') not in ['VOICE_STATE_UPDATE', 'VOICE_SERVER_UPDATE']: return if data['t'] == 'VOICE_SERVER_UPDATE': self.voice_state.update({ 'op': 'voiceUpdate', 'guildId': data['d']['guild_id'], 'event': data['d'] }) else: if int(data['d']['user_id']) != self.bot.user.id: return self.voice_state.update({'sessionId': data['d']['session_id']}) guild_id = int(data['d']['guild_id']) if self.players[guild_id]: self.players[guild_id].channel_id = data['d']['channel_id'] if {'op', 'guildId', 'sessionId', 'event'} == self.voice_state.keys(): await self.ws.send(**self.voice_state) self.voice_state.clear()
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: The payload received from Discord. """ # INTERCEPT VOICE UPDATES if not data or data.get('t', '') not in ['VOICE_STATE_UPDATE', 'VOICE_SERVER_UPDATE']: return if data['t'] == 'VOICE_SERVER_UPDATE': self.voice_state.update({ 'op': 'voiceUpdate', 'guildId': data['d']['guild_id'], 'event': data['d'] }) else: if int(data['d']['user_id']) != self.bot.user.id: return self.voice_state.update({'sessionId': data['d']['session_id']}) guild_id = int(data['d']['guild_id']) if self.players[guild_id]: self.players[guild_id].channel_id = data['d']['channel_id'] if {'op', 'guildId', 'sessionId', 'event'} == self.voice_state.keys(): await self.ws.send(**self.voice_state) self.voice_state.clear()
[ "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", ":", "The", "payload", "received", "from", "Discord", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L139-L171
[ "async", "def", "on_socket_response", "(", "self", ",", "data", ")", ":", "# INTERCEPT VOICE UPDATES\r", "if", "not", "data", "or", "data", ".", "get", "(", "'t'", ",", "''", ")", "not", "in", "[", "'VOICE_STATE_UPDATE'", ",", "'VOICE_SERVER_UPDATE'", "]", ":", "return", "if", "data", "[", "'t'", "]", "==", "'VOICE_SERVER_UPDATE'", ":", "self", ".", "voice_state", ".", "update", "(", "{", "'op'", ":", "'voiceUpdate'", ",", "'guildId'", ":", "data", "[", "'d'", "]", "[", "'guild_id'", "]", ",", "'event'", ":", "data", "[", "'d'", "]", "}", ")", "else", ":", "if", "int", "(", "data", "[", "'d'", "]", "[", "'user_id'", "]", ")", "!=", "self", ".", "bot", ".", "user", ".", "id", ":", "return", "self", ".", "voice_state", ".", "update", "(", "{", "'sessionId'", ":", "data", "[", "'d'", "]", "[", "'session_id'", "]", "}", ")", "guild_id", "=", "int", "(", "data", "[", "'d'", "]", "[", "'guild_id'", "]", ")", "if", "self", ".", "players", "[", "guild_id", "]", ":", "self", ".", "players", "[", "guild_id", "]", ".", "channel_id", "=", "data", "[", "'d'", "]", "[", "'channel_id'", "]", "if", "{", "'op'", ",", "'guildId'", ",", "'sessionId'", ",", "'event'", "}", "==", "self", ".", "voice_state", ".", "keys", "(", ")", ":", "await", "self", ".", "ws", ".", "send", "(", "*", "*", "self", ".", "voice_state", ")", "self", ".", "voice_state", ".", "clear", "(", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Client.destroy
Destroys the Lavalink client.
lavalink/Client.py
def destroy(self): """ Destroys the Lavalink client. """ self.ws.destroy() self.bot.remove_listener(self.on_socket_response) self.hooks.clear()
def destroy(self): """ Destroys the Lavalink client. """ self.ws.destroy() self.bot.remove_listener(self.on_socket_response) self.hooks.clear()
[ "Destroys", "the", "Lavalink", "client", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L173-L177
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "ws", ".", "destroy", "(", ")", "self", ".", "bot", ".", "remove_listener", "(", "self", ".", "on_socket_response", ")", "self", ".", "hooks", ".", "clear", "(", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
format_time
Formats the given time into HH:MM:SS.
lavalink/Utils.py
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 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)
[ "Formats", "the", "given", "time", "into", "HH", ":", "MM", ":", "SS", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Utils.py#L1-L6
[ "def", "format_time", "(", "time", ")", ":", "hours", ",", "remainder", "=", "divmod", "(", "time", "/", "1000", ",", "3600", ")", "minutes", ",", "seconds", "=", "divmod", "(", "remainder", ",", "60", ")", "return", "'%02d:%02d:%02d'", "%", "(", "hours", ",", "minutes", ",", "seconds", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
AudioTrack.build
Returns an optional AudioTrack.
lavalink/AudioTrack.py
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'] self.duration = track['info']['length'] self.stream = track['info']['isStream'] self.title = track['info']['title'] self.uri = track['info']['uri'] self.requester = requester return self except KeyError: raise InvalidTrack('An invalid track was passed.')
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'] self.duration = track['info']['length'] self.stream = track['info']['isStream'] self.title = track['info']['title'] self.uri = track['info']['uri'] self.requester = requester return self except KeyError: raise InvalidTrack('An invalid track was passed.')
[ "Returns", "an", "optional", "AudioTrack", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/AudioTrack.py#L6-L21
[ "def", "build", "(", "self", ",", "track", ",", "requester", ")", ":", "try", ":", "self", ".", "track", "=", "track", "[", "'track'", "]", "self", ".", "identifier", "=", "track", "[", "'info'", "]", "[", "'identifier'", "]", "self", ".", "can_seek", "=", "track", "[", "'info'", "]", "[", "'isSeekable'", "]", "self", ".", "author", "=", "track", "[", "'info'", "]", "[", "'author'", "]", "self", ".", "duration", "=", "track", "[", "'info'", "]", "[", "'length'", "]", "self", ".", "stream", "=", "track", "[", "'info'", "]", "[", "'isStream'", "]", "self", ".", "title", "=", "track", "[", "'info'", "]", "[", "'title'", "]", "self", ".", "uri", "=", "track", "[", "'info'", "]", "[", "'uri'", "]", "self", ".", "requester", "=", "requester", "return", "self", "except", "KeyError", ":", "raise", "InvalidTrack", "(", "'An invalid track was passed.'", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Music._previous
Plays the previous song.
examples/music-v3.py
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 _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.')
[ "Plays", "the", "previous", "song", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L92-L99
[ "async", "def", "_previous", "(", "self", ",", "ctx", ")", ":", "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.'", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Music._playnow
Plays immediately a song.
examples/music-v3.py
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('<>') if not url_rx.match(query): query = f'ytsearch:{query}' results = await self.bot.lavalink.get_tracks(query) if not results or not results['tracks']: return await ctx.send('Nothing found!') tracks = results['tracks'] track = tracks.pop(0) if results['loadType'] == 'PLAYLIST_LOADED': for _track in tracks: player.add(requester=ctx.author.id, track=_track) await player.play_now(requester=ctx.author.id, track=track)
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('<>') if not url_rx.match(query): query = f'ytsearch:{query}' results = await self.bot.lavalink.get_tracks(query) if not results or not results['tracks']: return await ctx.send('Nothing found!') tracks = results['tracks'] track = tracks.pop(0) if results['loadType'] == 'PLAYLIST_LOADED': for _track in tracks: player.add(requester=ctx.author.id, track=_track) await player.play_now(requester=ctx.author.id, track=track)
[ "Plays", "immediately", "a", "song", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L103-L127
[ "async", "def", "_playnow", "(", "self", ",", "ctx", ",", "*", ",", "query", ":", "str", ")", ":", "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", "(", "'<>'", ")", "if", "not", "url_rx", ".", "match", "(", "query", ")", ":", "query", "=", "f'ytsearch:{query}'", "results", "=", "await", "self", ".", "bot", ".", "lavalink", ".", "get_tracks", "(", "query", ")", "if", "not", "results", "or", "not", "results", "[", "'tracks'", "]", ":", "return", "await", "ctx", ".", "send", "(", "'Nothing found!'", ")", "tracks", "=", "results", "[", "'tracks'", "]", "track", "=", "tracks", ".", "pop", "(", "0", ")", "if", "results", "[", "'loadType'", "]", "==", "'PLAYLIST_LOADED'", ":", "for", "_track", "in", "tracks", ":", "player", ".", "add", "(", "requester", "=", "ctx", ".", "author", ".", "id", ",", "track", "=", "_track", ")", "await", "player", ".", "play_now", "(", "requester", "=", "ctx", ".", "author", ".", "id", ",", "track", "=", "track", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Music._playat
Plays the queue from a specific point. Disregards tracks before the index.
examples/music-v3.py
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) < index: return await ctx.send('This index exceeds the queue\'s length.') await player.play_at(index-1)
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) < index: return await ctx.send('This index exceeds the queue\'s length.') await player.play_at(index-1)
[ "Plays", "the", "queue", "from", "a", "specific", "point", ".", "Disregards", "tracks", "before", "the", "index", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L131-L141
[ "async", "def", "_playat", "(", "self", ",", "ctx", ",", "index", ":", "int", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "index", "<", "1", ":", "return", "await", "ctx", ".", "send", "(", "'Invalid specified index.'", ")", "if", "len", "(", "player", ".", "queue", ")", "<", "index", ":", "return", "await", "ctx", ".", "send", "(", "'This index exceeds the queue\\'s length.'", ")", "await", "player", ".", "play_at", "(", "index", "-", "1", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
Music._find
Lists the first 10 search results from a given query.
examples/music-v3.py
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 results or not results['tracks']: return await ctx.send('Nothing found') tracks = results['tracks'][:10] # First 10 results o = '' for index, track in enumerate(tracks, start=1): track_title = track["info"]["title"] track_uri = track["info"]["uri"] o += f'`{index}.` [{track_title}]({track_uri})\n' embed = discord.Embed(color=discord.Color.blurple(), description=o) await ctx.send(embed=embed)
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 results or not results['tracks']: return await ctx.send('Nothing found') tracks = results['tracks'][:10] # First 10 results o = '' for index, track in enumerate(tracks, start=1): track_title = track["info"]["title"] track_uri = track["info"]["uri"] o += f'`{index}.` [{track_title}]({track_uri})\n' embed = discord.Embed(color=discord.Color.blurple(), description=o) await ctx.send(embed=embed)
[ "Lists", "the", "first", "10", "search", "results", "from", "a", "given", "query", "." ]
Devoxin/Lavalink.py
python
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v3.py#L303-L323
[ "async", "def", "_find", "(", "self", ",", "ctx", ",", "*", ",", "query", ")", ":", "if", "not", "query", ".", "startswith", "(", "'ytsearch:'", ")", "and", "not", "query", ".", "startswith", "(", "'scsearch:'", ")", ":", "query", "=", "'ytsearch:'", "+", "query", "results", "=", "await", "self", ".", "bot", ".", "lavalink", ".", "get_tracks", "(", "query", ")", "if", "not", "results", "or", "not", "results", "[", "'tracks'", "]", ":", "return", "await", "ctx", ".", "send", "(", "'Nothing found'", ")", "tracks", "=", "results", "[", "'tracks'", "]", "[", ":", "10", "]", "# First 10 results\r", "o", "=", "''", "for", "index", ",", "track", "in", "enumerate", "(", "tracks", ",", "start", "=", "1", ")", ":", "track_title", "=", "track", "[", "\"info\"", "]", "[", "\"title\"", "]", "track_uri", "=", "track", "[", "\"info\"", "]", "[", "\"uri\"", "]", "o", "+=", "f'`{index}.` [{track_title}]({track_uri})\\n'", "embed", "=", "discord", ".", "Embed", "(", "color", "=", "discord", ".", "Color", ".", "blurple", "(", ")", ",", "description", "=", "o", ")", "await", "ctx", ".", "send", "(", "embed", "=", "embed", ")" ]
63f55c3d726d24c4cfd3674d3cd6aab6f5be110d
valid
AutoCompleter.add_suggestions
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
redisearch/auto_complete.py
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.pipeline() for sug in suggestions: args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score] if kwargs.get('increment'): args.append(AutoCompleter.INCR) if sug.payload: args.append('PAYLOAD') args.append(sug.payload) pipe.execute_command(*args) return pipe.execute()[-1]
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.pipeline() for sug in suggestions: args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score] if kwargs.get('increment'): args.append(AutoCompleter.INCR) if sug.payload: args.append('PAYLOAD') args.append(sug.payload) pipe.execute_command(*args) return pipe.execute()[-1]
[ "Add", "suggestion", "terms", "to", "the", "AutoCompleter", "engine", ".", "Each", "suggestion", "has", "a", "score", "and", "string", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/auto_complete.py#L81-L98
[ "def", "add_suggestions", "(", "self", ",", "*", "suggestions", ",", "*", "*", "kwargs", ")", ":", "pipe", "=", "self", ".", "redis", ".", "pipeline", "(", ")", "for", "sug", "in", "suggestions", ":", "args", "=", "[", "AutoCompleter", ".", "SUGADD_COMMAND", ",", "self", ".", "key", ",", "sug", ".", "string", ",", "sug", ".", "score", "]", "if", "kwargs", ".", "get", "(", "'increment'", ")", ":", "args", ".", "append", "(", "AutoCompleter", ".", "INCR", ")", "if", "sug", ".", "payload", ":", "args", ".", "append", "(", "'PAYLOAD'", ")", "args", ".", "append", "(", "sug", ".", "payload", ")", "pipe", ".", "execute_command", "(", "*", "args", ")", "return", "pipe", ".", "execute", "(", ")", "[", "-", "1", "]" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
AutoCompleter.delete
Delete a string from the AutoCompleter index. Returns 1 if the string was found and deleted, 0 otherwise
redisearch/auto_complete.py
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 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)
[ "Delete", "a", "string", "from", "the", "AutoCompleter", "index", ".", "Returns", "1", "if", "the", "string", "was", "found", "and", "deleted", "0", "otherwise" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/auto_complete.py#L108-L113
[ "def", "delete", "(", "self", ",", "string", ")", ":", "return", "self", ".", "redis", ".", "execute_command", "(", "AutoCompleter", ".", "SUGDEL_COMMAND", ",", "self", ".", "key", ",", "string", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
AutoCompleter.get_suggestions
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**: If set to true, the prefix search is done in fuzzy mode. **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index. - **with_scores**: if set to true, we also return the (refactored) score of each suggestion. This is normally not needed, and is NOT the original score inserted into the index - **with_payloads**: Return suggestion payloads - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions. Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.
redisearch/auto_complete.py
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**: If set to true, the prefix search is done in fuzzy mode. **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index. - **with_scores**: if set to true, we also return the (refactored) score of each suggestion. This is normally not needed, and is NOT the original score inserted into the index - **with_payloads**: Return suggestion payloads - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions. Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1. """ args = [AutoCompleter.SUGGET_COMMAND, self.key, prefix, 'MAX', num] if fuzzy: args.append(AutoCompleter.FUZZY) if with_scores: args.append(AutoCompleter.WITHSCORES) if with_payloads: args.append(AutoCompleter.WITHPAYLOADS) ret = self.redis.execute_command(*args) results = [] if not ret: return results parser = SuggestionParser(with_scores, with_payloads, ret) return [s for s in parser]
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**: If set to true, the prefix search is done in fuzzy mode. **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index. - **with_scores**: if set to true, we also return the (refactored) score of each suggestion. This is normally not needed, and is NOT the original score inserted into the index - **with_payloads**: Return suggestion payloads - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions. Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1. """ args = [AutoCompleter.SUGGET_COMMAND, self.key, prefix, 'MAX', num] if fuzzy: args.append(AutoCompleter.FUZZY) if with_scores: args.append(AutoCompleter.WITHSCORES) if with_payloads: args.append(AutoCompleter.WITHPAYLOADS) ret = self.redis.execute_command(*args) results = [] if not ret: return results parser = SuggestionParser(with_scores, with_payloads, ret) return [s for s in parser]
[ "Get", "a", "list", "of", "suggestions", "from", "the", "AutoCompleter", "for", "a", "given", "prefix" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/auto_complete.py#L115-L145
[ "def", "get_suggestions", "(", "self", ",", "prefix", ",", "fuzzy", "=", "False", ",", "num", "=", "10", ",", "with_scores", "=", "False", ",", "with_payloads", "=", "False", ")", ":", "args", "=", "[", "AutoCompleter", ".", "SUGGET_COMMAND", ",", "self", ".", "key", ",", "prefix", ",", "'MAX'", ",", "num", "]", "if", "fuzzy", ":", "args", ".", "append", "(", "AutoCompleter", ".", "FUZZY", ")", "if", "with_scores", ":", "args", ".", "append", "(", "AutoCompleter", ".", "WITHSCORES", ")", "if", "with_payloads", ":", "args", ".", "append", "(", "AutoCompleter", ".", "WITHPAYLOADS", ")", "ret", "=", "self", ".", "redis", ".", "execute_command", "(", "*", "args", ")", "results", "=", "[", "]", "if", "not", "ret", ":", "return", "results", "parser", "=", "SuggestionParser", "(", "with_scores", ",", "with_payloads", ",", "ret", ")", "return", "[", "s", "for", "s", "in", "parser", "]" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client.create_index
Create the search index. The index must not already exist. ### Parameters: - **fields**: a list of TextField or NumericField objects - **no_term_offsets**: If true, we will not save term offsets in the index - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty
redisearch/client.py
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 true, we will not save term offsets in the index - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty """ args = [self.CREATE_CMD, self.index_name] if no_term_offsets: args.append(self.NOOFFSETS) if no_field_flags: args.append(self.NOFIELDS) if stopwords is not None and isinstance(stopwords, (list, tuple, set)): args += [self.STOPWORDS, len(stopwords)] if len(stopwords) > 0: args += list(stopwords) args.append('SCHEMA') args += list(itertools.chain(*(f.redis_args() for f in fields))) return self.redis.execute_command(*args)
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 true, we will not save term offsets in the index - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty """ args = [self.CREATE_CMD, self.index_name] if no_term_offsets: args.append(self.NOOFFSETS) if no_field_flags: args.append(self.NOFIELDS) if stopwords is not None and isinstance(stopwords, (list, tuple, set)): args += [self.STOPWORDS, len(stopwords)] if len(stopwords) > 0: args += list(stopwords) args.append('SCHEMA') args += list(itertools.chain(*(f.redis_args() for f in fields))) return self.redis.execute_command(*args)
[ "Create", "the", "search", "index", ".", "The", "index", "must", "not", "already", "exist", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L174-L201
[ "def", "create_index", "(", "self", ",", "fields", ",", "no_term_offsets", "=", "False", ",", "no_field_flags", "=", "False", ",", "stopwords", "=", "None", ")", ":", "args", "=", "[", "self", ".", "CREATE_CMD", ",", "self", ".", "index_name", "]", "if", "no_term_offsets", ":", "args", ".", "append", "(", "self", ".", "NOOFFSETS", ")", "if", "no_field_flags", ":", "args", ".", "append", "(", "self", ".", "NOFIELDS", ")", "if", "stopwords", "is", "not", "None", "and", "isinstance", "(", "stopwords", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "args", "+=", "[", "self", ".", "STOPWORDS", ",", "len", "(", "stopwords", ")", "]", "if", "len", "(", "stopwords", ")", ">", "0", ":", "args", "+=", "list", "(", "stopwords", ")", "args", ".", "append", "(", "'SCHEMA'", ")", "args", "+=", "list", "(", "itertools", ".", "chain", "(", "*", "(", "f", ".", "redis_args", "(", ")", "for", "f", "in", "fields", ")", ")", ")", "return", "self", ".", "redis", ".", "execute_command", "(", "*", "args", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client._add_document
Internal add_document used for both batch and single doc indexing
redisearch/client.py
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 if partial: replace = True args = [self.ADD_CMD, self.index_name, doc_id, score] if nosave: args.append('NOSAVE') if payload is not None: args.append('PAYLOAD') args.append(payload) if replace: args.append('REPLACE') if partial: args.append('PARTIAL') if language: args += ['LANGUAGE', language] args.append('FIELDS') args += list(itertools.chain(*fields.items())) return conn.execute_command(*args)
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 if partial: replace = True args = [self.ADD_CMD, self.index_name, doc_id, score] if nosave: args.append('NOSAVE') if payload is not None: args.append('PAYLOAD') args.append(payload) if replace: args.append('REPLACE') if partial: args.append('PARTIAL') if language: args += ['LANGUAGE', language] args.append('FIELDS') args += list(itertools.chain(*fields.items())) return conn.execute_command(*args)
[ "Internal", "add_document", "used", "for", "both", "batch", "and", "single", "doc", "indexing" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L209-L234
[ "def", "_add_document", "(", "self", ",", "doc_id", ",", "conn", "=", "None", ",", "nosave", "=", "False", ",", "score", "=", "1.0", ",", "payload", "=", "None", ",", "replace", "=", "False", ",", "partial", "=", "False", ",", "language", "=", "None", ",", "*", "*", "fields", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "redis", "if", "partial", ":", "replace", "=", "True", "args", "=", "[", "self", ".", "ADD_CMD", ",", "self", ".", "index_name", ",", "doc_id", ",", "score", "]", "if", "nosave", ":", "args", ".", "append", "(", "'NOSAVE'", ")", "if", "payload", "is", "not", "None", ":", "args", ".", "append", "(", "'PAYLOAD'", ")", "args", ".", "append", "(", "payload", ")", "if", "replace", ":", "args", ".", "append", "(", "'REPLACE'", ")", "if", "partial", ":", "args", ".", "append", "(", "'PARTIAL'", ")", "if", "language", ":", "args", "+=", "[", "'LANGUAGE'", ",", "language", "]", "args", ".", "append", "(", "'FIELDS'", ")", "args", "+=", "list", "(", "itertools", ".", "chain", "(", "*", "fields", ".", "items", "(", ")", ")", ")", "return", "conn", ".", "execute_command", "(", "*", "args", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client.add_document
Add a single document to the index. ### Parameters - **doc_id**: the id of the saved document. - **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids. - **score**: the document ranking, between 0.0 and 1.0 - **payload**: optional inner-index payload we can save for fast access in scoring functions - **replace**: if True, and the document already is in the index, we perform an update and reindex the document - **partial**: if True, the fields specified will be added to the existing document. This has the added benefit that any fields specified with `no_index` will not be reindexed again. Implies `replace` - **language**: Specify the language used for document tokenization. - **fields** kwargs dictionary of the document fields to be saved and/or indexed. NOTE: Geo points shoule be encoded as strings of "lon,lat"
redisearch/client.py
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 just index the document, and don't save a copy of it. This means that searches will just return ids. - **score**: the document ranking, between 0.0 and 1.0 - **payload**: optional inner-index payload we can save for fast access in scoring functions - **replace**: if True, and the document already is in the index, we perform an update and reindex the document - **partial**: if True, the fields specified will be added to the existing document. This has the added benefit that any fields specified with `no_index` will not be reindexed again. Implies `replace` - **language**: Specify the language used for document tokenization. - **fields** kwargs dictionary of the document fields to be saved and/or indexed. NOTE: Geo points shoule be encoded as strings of "lon,lat" """ return self._add_document(doc_id, conn=None, nosave=nosave, score=score, payload=payload, replace=replace, partial=partial, language=language, **fields)
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 just index the document, and don't save a copy of it. This means that searches will just return ids. - **score**: the document ranking, between 0.0 and 1.0 - **payload**: optional inner-index payload we can save for fast access in scoring functions - **replace**: if True, and the document already is in the index, we perform an update and reindex the document - **partial**: if True, the fields specified will be added to the existing document. This has the added benefit that any fields specified with `no_index` will not be reindexed again. Implies `replace` - **language**: Specify the language used for document tokenization. - **fields** kwargs dictionary of the document fields to be saved and/or indexed. NOTE: Geo points shoule be encoded as strings of "lon,lat" """ return self._add_document(doc_id, conn=None, nosave=nosave, score=score, payload=payload, replace=replace, partial=partial, language=language, **fields)
[ "Add", "a", "single", "document", "to", "the", "index", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L236-L257
[ "def", "add_document", "(", "self", ",", "doc_id", ",", "nosave", "=", "False", ",", "score", "=", "1.0", ",", "payload", "=", "None", ",", "replace", "=", "False", ",", "partial", "=", "False", ",", "language", "=", "None", ",", "*", "*", "fields", ")", ":", "return", "self", ".", "_add_document", "(", "doc_id", ",", "conn", "=", "None", ",", "nosave", "=", "nosave", ",", "score", "=", "score", ",", "payload", "=", "payload", ",", "replace", "=", "replace", ",", "partial", "=", "partial", ",", "language", "=", "language", ",", "*", "*", "fields", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client.delete_document
Delete a document from index Returns 1 if the document was deleted, 0 if not
redisearch/client.py
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 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)
[ "Delete", "a", "document", "from", "index", "Returns", "1", "if", "the", "document", "was", "deleted", "0", "if", "not" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L259-L267
[ "def", "delete_document", "(", "self", ",", "doc_id", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "redis", "return", "conn", ".", "execute_command", "(", "self", ".", "DEL_CMD", ",", "self", ".", "index_name", ",", "doc_id", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client.load_document
Load a single document by id
redisearch/client.py
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: pass return Document(id=id, **fields)
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: pass return Document(id=id, **fields)
[ "Load", "a", "single", "document", "by", "id" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L269-L283
[ "def", "load_document", "(", "self", ",", "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", ":", "pass", "return", "Document", "(", "id", "=", "id", ",", "*", "*", "fields", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client.info
Get info an stats about the the current index, including the number of documents, memory consumption, etc
redisearch/client.py
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 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))
[ "Get", "info", "an", "stats", "about", "the", "the", "current", "index", "including", "the", "number", "of", "documents", "memory", "consumption", "etc" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L285-L292
[ "def", "info", "(", "self", ")", ":", "res", "=", "self", ".", "redis", ".", "execute_command", "(", "'FT.INFO'", ",", "self", ".", "index_name", ")", "it", "=", "six", ".", "moves", ".", "map", "(", "to_string", ",", "res", ")", "return", "dict", "(", "six", ".", "moves", ".", "zip", "(", "it", ",", "it", ")", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client.search
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 documentation on query format - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}
redisearch/client.py
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 documentation on query format - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500} """ args, query = self._mk_query_args(query) st = time.time() res = self.redis.execute_command(self.SEARCH_CMD, *args) return Result(res, not query._no_content, duration=(time.time() - st) * 1000.0, has_payload=query._with_payloads)
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 documentation on query format - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500} """ args, query = self._mk_query_args(query) st = time.time() res = self.redis.execute_command(self.SEARCH_CMD, *args) return Result(res, not query._no_content, duration=(time.time() - st) * 1000.0, has_payload=query._with_payloads)
[ "Search", "the", "index", "for", "a", "given", "query", "and", "return", "a", "result", "of", "documents" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L306-L323
[ "def", "search", "(", "self", ",", "query", ")", ":", "args", ",", "query", "=", "self", ".", "_mk_query_args", "(", "query", ")", "st", "=", "time", ".", "time", "(", ")", "res", "=", "self", ".", "redis", ".", "execute_command", "(", "self", ".", "SEARCH_CMD", ",", "*", "args", ")", "return", "Result", "(", "res", ",", "not", "query", ".", "_no_content", ",", "duration", "=", "(", "time", ".", "time", "(", ")", "-", "st", ")", "*", "1000.0", ",", "has_payload", "=", "query", ".", "_with_payloads", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Client.aggregate
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 the result
redisearch/client.py
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 the result """ if isinstance(query, AggregateRequest): has_schema = query._with_schema has_cursor = bool(query._cursor) cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args() elif isinstance(query, Cursor): has_schema = False has_cursor = True cmd = [self.CURSOR_CMD, 'READ', self.index_name] + query.build_args() else: raise ValueError('Bad query', query) raw = self.redis.execute_command(*cmd) if has_cursor: if isinstance(query, Cursor): query.cid = raw[1] cursor = query else: cursor = Cursor(raw[1]) raw = raw[0] else: cursor = None if query._with_schema: schema = raw[0] rows = raw[2:] else: schema = None rows = raw[1:] res = AggregateResult(rows, cursor, schema) return res
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 the result """ if isinstance(query, AggregateRequest): has_schema = query._with_schema has_cursor = bool(query._cursor) cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args() elif isinstance(query, Cursor): has_schema = False has_cursor = True cmd = [self.CURSOR_CMD, 'READ', self.index_name] + query.build_args() else: raise ValueError('Bad query', query) raw = self.redis.execute_command(*cmd) if has_cursor: if isinstance(query, Cursor): query.cid = raw[1] cursor = query else: cursor = Cursor(raw[1]) raw = raw[0] else: cursor = None if query._with_schema: schema = raw[0] rows = raw[2:] else: schema = None rows = raw[1:] res = AggregateResult(rows, cursor, schema) return res
[ "Issue", "an", "aggregation", "query" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L329-L370
[ "def", "aggregate", "(", "self", ",", "query", ")", ":", "if", "isinstance", "(", "query", ",", "AggregateRequest", ")", ":", "has_schema", "=", "query", ".", "_with_schema", "has_cursor", "=", "bool", "(", "query", ".", "_cursor", ")", "cmd", "=", "[", "self", ".", "AGGREGATE_CMD", ",", "self", ".", "index_name", "]", "+", "query", ".", "build_args", "(", ")", "elif", "isinstance", "(", "query", ",", "Cursor", ")", ":", "has_schema", "=", "False", "has_cursor", "=", "True", "cmd", "=", "[", "self", ".", "CURSOR_CMD", ",", "'READ'", ",", "self", ".", "index_name", "]", "+", "query", ".", "build_args", "(", ")", "else", ":", "raise", "ValueError", "(", "'Bad query'", ",", "query", ")", "raw", "=", "self", ".", "redis", ".", "execute_command", "(", "*", "cmd", ")", "if", "has_cursor", ":", "if", "isinstance", "(", "query", ",", "Cursor", ")", ":", "query", ".", "cid", "=", "raw", "[", "1", "]", "cursor", "=", "query", "else", ":", "cursor", "=", "Cursor", "(", "raw", "[", "1", "]", ")", "raw", "=", "raw", "[", "0", "]", "else", ":", "cursor", "=", "None", "if", "query", ".", "_with_schema", ":", "schema", "=", "raw", "[", "0", "]", "rows", "=", "raw", "[", "2", ":", "]", "else", ":", "schema", "=", "None", "rows", "=", "raw", "[", "1", ":", "]", "res", "=", "AggregateResult", "(", "rows", ",", "cursor", ",", "schema", ")", "return", "res" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Reducer.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 operates. Note that using `FIELDNAME` is only possible on reducers which operate on a single field value. This method returns the `Reducer` object making it suitable for chaining.
redisearch/aggregation.py
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 operates. Note that using `FIELDNAME` is only possible on reducers which operate on a single field value. This method returns the `Reducer` object making it suitable for chaining. """ if alias is FIELDNAME: if not self._field: raise ValueError("Cannot use FIELDNAME alias with no field") # Chop off initial '@' alias = self._field[1:] self._alias = alias return self
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 operates. Note that using `FIELDNAME` is only possible on reducers which operate on a single field value. This method returns the `Reducer` object making it suitable for chaining. """ if alias is FIELDNAME: if not self._field: raise ValueError("Cannot use FIELDNAME alias with no field") # Chop off initial '@' alias = self._field[1:] self._alias = alias return self
[ "Set", "the", "alias", "for", "this", "reducer", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L32-L53
[ "def", "alias", "(", "self", ",", "alias", ")", ":", "if", "alias", "is", "FIELDNAME", ":", "if", "not", "self", ".", "_field", ":", "raise", "ValueError", "(", "\"Cannot use FIELDNAME alias with no field\"", ")", "# Chop off initial '@'", "alias", "=", "self", ".", "_field", "[", "1", ":", "]", "self", ".", "_alias", "=", "alias", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
AggregateRequest.group_by
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`. - **reducers**: One or more reducers. Reducers may be found in the `aggregation` module.
redisearch/aggregation.py
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`. - **reducers**: One or more reducers. Reducers may be found in the `aggregation` module. """ group = Group(fields, reducers) self._groups.append(group) return self
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`. - **reducers**: One or more reducers. Reducers may be found in the `aggregation` module. """ group = Group(fields, reducers) self._groups.append(group) return self
[ "Specify", "by", "which", "fields", "to", "group", "the", "aggregation", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L152-L167
[ "def", "group_by", "(", "self", ",", "fields", ",", "*", "reducers", ")", ":", "group", "=", "Group", "(", "fields", ",", "reducers", ")", "self", ".", "_groups", ".", "append", "(", "group", ")", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
AggregateRequest.apply
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, for example `apply(square_root="sqrt(@foo)")`
redisearch/aggregation.py
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, for example `apply(square_root="sqrt(@foo)")` """ for alias, expr in kwexpr.items(): self._projections.append([alias, expr]) return self
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, for example `apply(square_root="sqrt(@foo)")` """ for alias, expr in kwexpr.items(): self._projections.append([alias, expr]) return self
[ "Specify", "one", "or", "more", "projection", "expressions", "to", "add", "to", "each", "result" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L169-L182
[ "def", "apply", "(", "self", ",", "*", "*", "kwexpr", ")", ":", "for", "alias", ",", "expr", "in", "kwexpr", ".", "items", "(", ")", ":", "self", ".", "_projections", ".", "append", "(", "[", "alias", ",", "expr", "]", ")", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
AggregateRequest.limit
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 previous group. Setting a limit on the initial search results may be useful when attempting to execute an aggregation on a sample of a large data set. ### Parameters - **offset**: Result offset from which to begin paging - **num**: Number of results to return Example of sorting the initial results: ``` AggregateRequest('@sale_amount:[10000, inf]')\ .limit(0, 10)\ .group_by('@state', r.count()) ``` Will only group by the states found in the first 10 results of the query `@sale_amount:[10000, inf]`. On the other hand, ``` AggregateRequest('@sale_amount:[10000, inf]')\ .limit(0, 1000)\ .group_by('@state', r.count()\ .limit(0, 10) ``` Will group all the results matching the query, but only return the first 10 groups. If you only wish to return a *top-N* style query, consider using `sort_by()` instead.
redisearch/aggregation.py
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 previous group. Setting a limit on the initial search results may be useful when attempting to execute an aggregation on a sample of a large data set. ### Parameters - **offset**: Result offset from which to begin paging - **num**: Number of results to return Example of sorting the initial results: ``` AggregateRequest('@sale_amount:[10000, inf]')\ .limit(0, 10)\ .group_by('@state', r.count()) ``` Will only group by the states found in the first 10 results of the query `@sale_amount:[10000, inf]`. On the other hand, ``` AggregateRequest('@sale_amount:[10000, inf]')\ .limit(0, 1000)\ .group_by('@state', r.count()\ .limit(0, 10) ``` Will group all the results matching the query, but only return the first 10 groups. If you only wish to return a *top-N* style query, consider using `sort_by()` instead. """ limit = Limit(offset, num) if self._groups: self._groups[-1].limit = limit else: self._limit = limit return self
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 previous group. Setting a limit on the initial search results may be useful when attempting to execute an aggregation on a sample of a large data set. ### Parameters - **offset**: Result offset from which to begin paging - **num**: Number of results to return Example of sorting the initial results: ``` AggregateRequest('@sale_amount:[10000, inf]')\ .limit(0, 10)\ .group_by('@state', r.count()) ``` Will only group by the states found in the first 10 results of the query `@sale_amount:[10000, inf]`. On the other hand, ``` AggregateRequest('@sale_amount:[10000, inf]')\ .limit(0, 1000)\ .group_by('@state', r.count()\ .limit(0, 10) ``` Will group all the results matching the query, but only return the first 10 groups. If you only wish to return a *top-N* style query, consider using `sort_by()` instead. """ limit = Limit(offset, num) if self._groups: self._groups[-1].limit = limit else: self._limit = limit return self
[ "Sets", "the", "limit", "for", "the", "most", "recent", "group", "or", "query", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L184-L231
[ "def", "limit", "(", "self", ",", "offset", ",", "num", ")", ":", "limit", "=", "Limit", "(", "offset", ",", "num", ")", "if", "self", ".", "_groups", ":", "self", ".", "_groups", "[", "-", "1", "]", ".", "limit", "=", "limit", "else", ":", "self", ".", "_limit", "=", "limit", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
AggregateRequest.sort_by
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 specify order, you can use the `Asc` or `Desc` wrapper classes. - **max**: Maximum number of results to return. This can be used instead of `LIMIT` and is also faster. Example of sorting by `foo` ascending and `bar` descending: ``` sort_by(Asc('@foo'), Desc('@bar')) ``` Return the top 10 customers: ``` AggregateRequest()\ .group_by('@customer', r.sum('@paid').alias(FIELDNAME))\ .sort_by(Desc('@paid'), max=10) ```
redisearch/aggregation.py
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 specify order, you can use the `Asc` or `Desc` wrapper classes. - **max**: Maximum number of results to return. This can be used instead of `LIMIT` and is also faster. Example of sorting by `foo` ascending and `bar` descending: ``` sort_by(Asc('@foo'), Desc('@bar')) ``` Return the top 10 customers: ``` AggregateRequest()\ .group_by('@customer', r.sum('@paid').alias(FIELDNAME))\ .sort_by(Desc('@paid'), max=10) ``` """ self._max = kwargs.get('max', 0) if isinstance(fields, (string_types, SortDirection)): fields = [fields] for f in fields: if isinstance(f, SortDirection): self._sortby += [f.field, f.DIRSTRING] else: self._sortby.append(f) return self
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 specify order, you can use the `Asc` or `Desc` wrapper classes. - **max**: Maximum number of results to return. This can be used instead of `LIMIT` and is also faster. Example of sorting by `foo` ascending and `bar` descending: ``` sort_by(Asc('@foo'), Desc('@bar')) ``` Return the top 10 customers: ``` AggregateRequest()\ .group_by('@customer', r.sum('@paid').alias(FIELDNAME))\ .sort_by(Desc('@paid'), max=10) ``` """ self._max = kwargs.get('max', 0) if isinstance(fields, (string_types, SortDirection)): fields = [fields] for f in fields: if isinstance(f, SortDirection): self._sortby += [f.field, f.DIRSTRING] else: self._sortby.append(f) return self
[ "Indicate", "how", "the", "results", "should", "be", "sorted", ".", "This", "can", "also", "be", "used", "for", "*", "top", "-", "N", "*", "style", "queries" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L233-L269
[ "def", "sort_by", "(", "self", ",", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_max", "=", "kwargs", ".", "get", "(", "'max'", ",", "0", ")", "if", "isinstance", "(", "fields", ",", "(", "string_types", ",", "SortDirection", ")", ")", ":", "fields", "=", "[", "fields", "]", "for", "f", "in", "fields", ":", "if", "isinstance", "(", "f", ",", "SortDirection", ")", ":", "self", ".", "_sortby", "+=", "[", "f", ".", "field", ",", "f", ".", "DIRSTRING", "]", "else", ":", "self", ".", "_sortby", ".", "append", "(", "f", ")", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Query.summarize
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; otherwise all results are summarized. Server side defaults are used for each option (except `fields`) if not specified - **fields** List of fields to summarize. All fields are summarized if not specified - **context_len** Amount of context to include with each fragment - **num_frags** Number of fragments per document - **sep** Separator string to separate fragments
redisearch/query.py
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; otherwise all results are summarized. Server side defaults are used for each option (except `fields`) if not specified - **fields** List of fields to summarize. All fields are summarized if not specified - **context_len** Amount of context to include with each fragment - **num_frags** Number of fragments per document - **sep** Separator string to separate fragments """ args = ['SUMMARIZE'] fields = self._mk_field_list(fields) if fields: args += ['FIELDS', str(len(fields))] + fields if context_len is not None: args += ['LEN', str(context_len)] if num_frags is not None: args += ['FRAGS', str(num_frags)] if sep is not None: args += ['SEPARATOR', sep] self._summarize_fields = args return self
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; otherwise all results are summarized. Server side defaults are used for each option (except `fields`) if not specified - **fields** List of fields to summarize. All fields are summarized if not specified - **context_len** Amount of context to include with each fragment - **num_frags** Number of fragments per document - **sep** Separator string to separate fragments """ args = ['SUMMARIZE'] fields = self._mk_field_list(fields) if fields: args += ['FIELDS', str(len(fields))] + fields if context_len is not None: args += ['LEN', str(context_len)] if num_frags is not None: args += ['FRAGS', str(num_frags)] if sep is not None: args += ['SEPARATOR', sep] self._summarize_fields = args return self
[ "Return", "an", "abridged", "format", "of", "the", "field", "containing", "only", "the", "segments", "of", "the", "field", "which", "contain", "the", "matching", "term", "(", "s", ")", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/query.py#L61-L89
[ "def", "summarize", "(", "self", ",", "fields", "=", "None", ",", "context_len", "=", "None", ",", "num_frags", "=", "None", ",", "sep", "=", "None", ")", ":", "args", "=", "[", "'SUMMARIZE'", "]", "fields", "=", "self", ".", "_mk_field_list", "(", "fields", ")", "if", "fields", ":", "args", "+=", "[", "'FIELDS'", ",", "str", "(", "len", "(", "fields", ")", ")", "]", "+", "fields", "if", "context_len", "is", "not", "None", ":", "args", "+=", "[", "'LEN'", ",", "str", "(", "context_len", ")", "]", "if", "num_frags", "is", "not", "None", ":", "args", "+=", "[", "'FRAGS'", ",", "str", "(", "num_frags", ")", "]", "if", "sep", "is", "not", "None", ":", "args", "+=", "[", "'SEPARATOR'", ",", "sep", "]", "self", ".", "_summarize_fields", "=", "args", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Query.highlight
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.
redisearch/query.py
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. """ args = ['HIGHLIGHT'] fields = self._mk_field_list(fields) if fields: args += ['FIELDS', str(len(fields))] + fields if tags: args += ['TAGS'] + list(tags) self._highlight_fields = args return self
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. """ args = ['HIGHLIGHT'] fields = self._mk_field_list(fields) if fields: args += ['FIELDS', str(len(fields))] + fields if tags: args += ['TAGS'] + list(tags) self._highlight_fields = args return self
[ "Apply", "specified", "markup", "to", "matched", "term", "(", "s", ")", "within", "the", "returned", "field", "(", "s", ")" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/query.py#L91-L106
[ "def", "highlight", "(", "self", ",", "fields", "=", "None", ",", "tags", "=", "None", ")", ":", "args", "=", "[", "'HIGHLIGHT'", "]", "fields", "=", "self", ".", "_mk_field_list", "(", "fields", ")", "if", "fields", ":", "args", "+=", "[", "'FIELDS'", ",", "str", "(", "len", "(", "fields", ")", ")", "]", "+", "fields", "if", "tags", ":", "args", "+=", "[", "'TAGS'", "]", "+", "list", "(", "tags", ")", "self", ".", "_highlight_fields", "=", "args", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Query.get_args
Format the redis arguments for this query and return them
redisearch/query.py
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)) args += self._fields if self._verbatim: args.append('VERBATIM') if self._no_stopwords: args.append('NOSTOPWORDS') if self._filters: for flt in self._filters: assert isinstance(flt, Filter) args += flt.args if self._with_payloads: args.append('WITHPAYLOADS') if self._ids: args.append('INKEYS') args.append(len(self._ids)) args += self._ids if self._slop >= 0: args += ['SLOP', self._slop] if self._in_order: args.append('INORDER') if self._return_fields: args.append('RETURN') args.append(len(self._return_fields)) args += self._return_fields if self._sortby: assert isinstance(self._sortby, SortbyField) args.append('SORTBY') args += self._sortby.args if self._language: args += ['LANGUAGE', self._language] args += self._summarize_fields + self._highlight_fields args += ["LIMIT", self._offset, self._num] return args
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)) args += self._fields if self._verbatim: args.append('VERBATIM') if self._no_stopwords: args.append('NOSTOPWORDS') if self._filters: for flt in self._filters: assert isinstance(flt, Filter) args += flt.args if self._with_payloads: args.append('WITHPAYLOADS') if self._ids: args.append('INKEYS') args.append(len(self._ids)) args += self._ids if self._slop >= 0: args += ['SLOP', self._slop] if self._in_order: args.append('INORDER') if self._return_fields: args.append('RETURN') args.append(len(self._return_fields)) args += self._return_fields if self._sortby: assert isinstance(self._sortby, SortbyField) args.append('SORTBY') args += self._sortby.args if self._language: args += ['LANGUAGE', self._language] args += self._summarize_fields + self._highlight_fields args += ["LIMIT", self._offset, self._num] return args
[ "Format", "the", "redis", "arguments", "for", "this", "query", "and", "return", "them" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/query.py#L131-L187
[ "def", "get_args", "(", "self", ")", ":", "args", "=", "[", "self", ".", "_query_string", "]", "if", "self", ".", "_no_content", ":", "args", ".", "append", "(", "'NOCONTENT'", ")", "if", "self", ".", "_fields", ":", "args", ".", "append", "(", "'INFIELDS'", ")", "args", ".", "append", "(", "len", "(", "self", ".", "_fields", ")", ")", "args", "+=", "self", ".", "_fields", "if", "self", ".", "_verbatim", ":", "args", ".", "append", "(", "'VERBATIM'", ")", "if", "self", ".", "_no_stopwords", ":", "args", ".", "append", "(", "'NOSTOPWORDS'", ")", "if", "self", ".", "_filters", ":", "for", "flt", "in", "self", ".", "_filters", ":", "assert", "isinstance", "(", "flt", ",", "Filter", ")", "args", "+=", "flt", ".", "args", "if", "self", ".", "_with_payloads", ":", "args", ".", "append", "(", "'WITHPAYLOADS'", ")", "if", "self", ".", "_ids", ":", "args", ".", "append", "(", "'INKEYS'", ")", "args", ".", "append", "(", "len", "(", "self", ".", "_ids", ")", ")", "args", "+=", "self", ".", "_ids", "if", "self", ".", "_slop", ">=", "0", ":", "args", "+=", "[", "'SLOP'", ",", "self", ".", "_slop", "]", "if", "self", ".", "_in_order", ":", "args", ".", "append", "(", "'INORDER'", ")", "if", "self", ".", "_return_fields", ":", "args", ".", "append", "(", "'RETURN'", ")", "args", ".", "append", "(", "len", "(", "self", ".", "_return_fields", ")", ")", "args", "+=", "self", ".", "_return_fields", "if", "self", ".", "_sortby", ":", "assert", "isinstance", "(", "self", ".", "_sortby", ",", "SortbyField", ")", "args", ".", "append", "(", "'SORTBY'", ")", "args", "+=", "self", ".", "_sortby", ".", "args", "if", "self", ".", "_language", ":", "args", "+=", "[", "'LANGUAGE'", ",", "self", ".", "_language", "]", "args", "+=", "self", ".", "_summarize_fields", "+", "self", ".", "_highlight_fields", "args", "+=", "[", "\"LIMIT\"", ",", "self", ".", "_offset", ",", "self", ".", "_num", "]", "return", "args" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Query.paging
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
redisearch/query.py
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 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
[ "Set", "the", "paging", "for", "the", "query", "(", "defaults", "to", "0", "..", "10", ")", "." ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/query.py#L189-L198
[ "def", "paging", "(", "self", ",", "offset", ",", "num", ")", ":", "self", ".", "_offset", "=", "offset", "self", ".", "_num", "=", "num", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Query.sort_by
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
redisearch/query.py
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 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
[ "Add", "a", "sortby", "field", "to", "the", "query" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/query.py#L249-L257
[ "def", "sort_by", "(", "self", ",", "field", ",", "asc", "=", "True", ")", ":", "self", ".", "_sortby", "=", "SortbyField", "(", "field", ",", "asc", ")", "return", "self" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
between
Indicate that value is a numeric range
redisearch/querystring.py
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 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)
[ "Indicate", "that", "value", "is", "a", "numeric", "range" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/querystring.py#L16-L21
[ "def", "between", "(", "a", ",", "b", ",", "inclusive_min", "=", "True", ",", "inclusive_max", "=", "True", ")", ":", "return", "RangeValue", "(", "a", ",", "b", ",", "inclusive_min", "=", "inclusive_min", ",", "inclusive_max", "=", "inclusive_max", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
geo
Indicate that value is a geo region
redisearch/querystring.py
def geo(lat, lon, radius, unit='km'): """ Indicate that value is a geo region """ return GeoValue(lat, lon, radius, unit)
def geo(lat, lon, radius, unit='km'): """ Indicate that value is a geo region """ return GeoValue(lat, lon, radius, unit)
[ "Indicate", "that", "value", "is", "a", "geo", "region" ]
RediSearch/redisearch-py
python
https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/querystring.py#L58-L62
[ "def", "geo", "(", "lat", ",", "lon", ",", "radius", ",", "unit", "=", "'km'", ")", ":", "return", "GeoValue", "(", "lat", ",", "lon", ",", "radius", ",", "unit", ")" ]
f65d1dd078713cbe9b83584e86655a254d0531ab
valid
Bypass.transform
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 subsequent results are generated by `transformer`
muda/deformers/util.py
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 subsequent results are generated by `transformer` ''' # Step 1: yield the unmodified jam yield jam # Step 2: yield from the transformer for jam_out in self.transformer.transform(jam): yield jam_out
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 subsequent results are generated by `transformer` ''' # Step 1: yield the unmodified jam yield jam # Step 2: yield from the transformer for jam_out in self.transformer.transform(jam): yield jam_out
[ "Bypass", "transformations", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/util.py#L40-L59
[ "def", "transform", "(", "self", ",", "jam", ")", ":", "# Step 1: yield the unmodified jam", "yield", "jam", "# Step 2: yield from the transformer", "for", "jam_out", "in", "self", ".", "transformer", ".", "transform", "(", "jam", ")", ":", "yield", "jam_out" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
__sox
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
muda/deformers/sox.py
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 sr > 0 fdesc, infile = tempfile.mkstemp(suffix='.wav') os.close(fdesc) fdesc, outfile = tempfile.mkstemp(suffix='.wav') os.close(fdesc) # Dump the audio librosa.output.write_wav(infile, y, sr) try: arguments = ['sox', infile, outfile, '-q'] arguments.extend(args) subprocess.check_call(arguments) y_out, sr = psf.read(outfile) y_out = y_out.T if y.ndim == 1: y_out = librosa.to_mono(y_out) finally: os.unlink(infile) os.unlink(outfile) return y_out
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 sr > 0 fdesc, infile = tempfile.mkstemp(suffix='.wav') os.close(fdesc) fdesc, outfile = tempfile.mkstemp(suffix='.wav') os.close(fdesc) # Dump the audio librosa.output.write_wav(infile, y, sr) try: arguments = ['sox', infile, outfile, '-q'] arguments.extend(args) subprocess.check_call(arguments) y_out, sr = psf.read(outfile) y_out = y_out.T if y.ndim == 1: y_out = librosa.to_mono(y_out) finally: os.unlink(infile) os.unlink(outfile) return y_out
[ "Execute", "sox" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/sox.py#L25-L70
[ "def", "__sox", "(", "y", ",", "sr", ",", "*", "args", ")", ":", "assert", "sr", ">", "0", "fdesc", ",", "infile", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.wav'", ")", "os", ".", "close", "(", "fdesc", ")", "fdesc", ",", "outfile", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.wav'", ")", "os", ".", "close", "(", "fdesc", ")", "# Dump the audio", "librosa", ".", "output", ".", "write_wav", "(", "infile", ",", "y", ",", "sr", ")", "try", ":", "arguments", "=", "[", "'sox'", ",", "infile", ",", "outfile", ",", "'-q'", "]", "arguments", ".", "extend", "(", "args", ")", "subprocess", ".", "check_call", "(", "arguments", ")", "y_out", ",", "sr", "=", "psf", ".", "read", "(", "outfile", ")", "y_out", "=", "y_out", ".", "T", "if", "y", ".", "ndim", "==", "1", ":", "y_out", "=", "librosa", ".", "to_mono", "(", "y_out", ")", "finally", ":", "os", ".", "unlink", "(", "infile", ")", "os", ".", "unlink", "(", "outfile", ")", "return", "y_out" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
transpose
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 label
muda/deformers/pitch.py
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 label ''' # Otherwise, split off the note from the modifier match = re.match(six.text_type('(?P<note>[A-G][b#]*)(?P<mod>.*)'), six.text_type(label)) if not match: return label note = match.group('note') new_note = librosa.midi_to_note(librosa.note_to_midi(note) + n_semitones, octave=False) return new_note + match.group('mod')
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 label ''' # Otherwise, split off the note from the modifier match = re.match(six.text_type('(?P<note>[A-G][b#]*)(?P<mod>.*)'), six.text_type(label)) if not match: return label note = match.group('note') new_note = librosa.midi_to_note(librosa.note_to_midi(note) + n_semitones, octave=False) return new_note + match.group('mod')
[ "Transpose", "a", "chord", "label", "by", "some", "number", "of", "semitones" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/pitch.py#L18-L48
[ "def", "transpose", "(", "label", ",", "n_semitones", ")", ":", "# Otherwise, split off the note from the modifier", "match", "=", "re", ".", "match", "(", "six", ".", "text_type", "(", "'(?P<note>[A-G][b#]*)(?P<mod>.*)'", ")", ",", "six", ".", "text_type", "(", "label", ")", ")", "if", "not", "match", ":", "return", "label", "note", "=", "match", ".", "group", "(", "'note'", ")", "new_note", "=", "librosa", ".", "midi_to_note", "(", "librosa", ".", "note_to_midi", "(", "note", ")", "+", "n_semitones", ",", "octave", "=", "False", ")", "return", "new_note", "+", "match", ".", "group", "(", "'mod'", ")" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
jam_pack
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 supplying keyword arguments. Parameters ---------- jam : jams.JAMS A JAMS object Returns ------- jam : jams.JAMS The updated JAMS object Examples -------- >>> jam = jams.JAMS() >>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None)) >>> jam.sandbox <Sandbox: muda> >>> jam.sandbox.muda <Sandbox: state, version, my_data, history> >>> jam.sandbox.muda.my_data {'foo': 5, 'bar': None}
muda/core.py
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 supplying keyword arguments. Parameters ---------- jam : jams.JAMS A JAMS object Returns ------- jam : jams.JAMS The updated JAMS object Examples -------- >>> jam = jams.JAMS() >>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None)) >>> jam.sandbox <Sandbox: muda> >>> jam.sandbox.muda <Sandbox: state, version, my_data, history> >>> jam.sandbox.muda.my_data {'foo': 5, 'bar': None} ''' if not hasattr(jam.sandbox, 'muda'): # If there's no mudabox, create one jam.sandbox.muda = jams.Sandbox(history=[], state=[], version=dict(muda=version, librosa=librosa.__version__, jams=jams.__version__, pysoundfile=psf.__version__)) elif not isinstance(jam.sandbox.muda, jams.Sandbox): # If there is a muda entry, but it's not a sandbox, coerce it jam.sandbox.muda = jams.Sandbox(**jam.sandbox.muda) jam.sandbox.muda.update(**kwargs) return jam
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 supplying keyword arguments. Parameters ---------- jam : jams.JAMS A JAMS object Returns ------- jam : jams.JAMS The updated JAMS object Examples -------- >>> jam = jams.JAMS() >>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None)) >>> jam.sandbox <Sandbox: muda> >>> jam.sandbox.muda <Sandbox: state, version, my_data, history> >>> jam.sandbox.muda.my_data {'foo': 5, 'bar': None} ''' if not hasattr(jam.sandbox, 'muda'): # If there's no mudabox, create one jam.sandbox.muda = jams.Sandbox(history=[], state=[], version=dict(muda=version, librosa=librosa.__version__, jams=jams.__version__, pysoundfile=psf.__version__)) elif not isinstance(jam.sandbox.muda, jams.Sandbox): # If there is a muda entry, but it's not a sandbox, coerce it jam.sandbox.muda = jams.Sandbox(**jam.sandbox.muda) jam.sandbox.muda.update(**kwargs) return jam
[ "Pack", "data", "into", "a", "jams", "sandbox", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L18-L65
[ "def", "jam_pack", "(", "jam", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "jam", ".", "sandbox", ",", "'muda'", ")", ":", "# If there's no mudabox, create one", "jam", ".", "sandbox", ".", "muda", "=", "jams", ".", "Sandbox", "(", "history", "=", "[", "]", ",", "state", "=", "[", "]", ",", "version", "=", "dict", "(", "muda", "=", "version", ",", "librosa", "=", "librosa", ".", "__version__", ",", "jams", "=", "jams", ".", "__version__", ",", "pysoundfile", "=", "psf", ".", "__version__", ")", ")", "elif", "not", "isinstance", "(", "jam", ".", "sandbox", ".", "muda", ",", "jams", ".", "Sandbox", ")", ":", "# If there is a muda entry, but it's not a sandbox, coerce it", "jam", ".", "sandbox", ".", "muda", "=", "jams", ".", "Sandbox", "(", "*", "*", "jam", ".", "sandbox", ".", "muda", ")", "jam", ".", "sandbox", ".", "muda", ".", "update", "(", "*", "*", "kwargs", ")", "return", "jam" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
load_jam_audio
Load a jam and pack it with audio. Parameters ---------- jam_in : str, file descriptor, or jams.JAMS JAMS filename, open file-descriptor, or object to load. See ``jams.load`` for acceptable formats. audio_file : str Audio filename to load validate : bool strict : bool fmt : str Parameters to `jams.load` kwargs : additional keyword arguments See `librosa.load` Returns ------- jam : jams.JAMS A jams object with audio data in the top-level sandbox Notes ----- This operation can modify the `file_metadata.duration` field of `jam_in`: If it is not currently set, it will be populated with the duration of the audio file. See Also -------- jams.load librosa.core.load
muda/core.py
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-descriptor, or object to load. See ``jams.load`` for acceptable formats. audio_file : str Audio filename to load validate : bool strict : bool fmt : str Parameters to `jams.load` kwargs : additional keyword arguments See `librosa.load` Returns ------- jam : jams.JAMS A jams object with audio data in the top-level sandbox Notes ----- This operation can modify the `file_metadata.duration` field of `jam_in`: If it is not currently set, it will be populated with the duration of the audio file. See Also -------- jams.load librosa.core.load ''' if isinstance(jam_in, jams.JAMS): jam = jam_in else: jam = jams.load(jam_in, validate=validate, strict=strict, fmt=fmt) y, sr = librosa.load(audio_file, **kwargs) if jam.file_metadata.duration is None: jam.file_metadata.duration = librosa.get_duration(y=y, sr=sr) return jam_pack(jam, _audio=dict(y=y, sr=sr))
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-descriptor, or object to load. See ``jams.load`` for acceptable formats. audio_file : str Audio filename to load validate : bool strict : bool fmt : str Parameters to `jams.load` kwargs : additional keyword arguments See `librosa.load` Returns ------- jam : jams.JAMS A jams object with audio data in the top-level sandbox Notes ----- This operation can modify the `file_metadata.duration` field of `jam_in`: If it is not currently set, it will be populated with the duration of the audio file. See Also -------- jams.load librosa.core.load ''' if isinstance(jam_in, jams.JAMS): jam = jam_in else: jam = jams.load(jam_in, validate=validate, strict=strict, fmt=fmt) y, sr = librosa.load(audio_file, **kwargs) if jam.file_metadata.duration is None: jam.file_metadata.duration = librosa.get_duration(y=y, sr=sr) return jam_pack(jam, _audio=dict(y=y, sr=sr))
[ "Load", "a", "jam", "and", "pack", "it", "with", "audio", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L68-L119
[ "def", "load_jam_audio", "(", "jam_in", ",", "audio_file", ",", "validate", "=", "True", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "jam_in", ",", "jams", ".", "JAMS", ")", ":", "jam", "=", "jam_in", "else", ":", "jam", "=", "jams", ".", "load", "(", "jam_in", ",", "validate", "=", "validate", ",", "strict", "=", "strict", ",", "fmt", "=", "fmt", ")", "y", ",", "sr", "=", "librosa", ".", "load", "(", "audio_file", ",", "*", "*", "kwargs", ")", "if", "jam", ".", "file_metadata", ".", "duration", "is", "None", ":", "jam", ".", "file_metadata", ".", "duration", "=", "librosa", ".", "get_duration", "(", "y", "=", "y", ",", "sr", "=", "sr", ")", "return", "jam_pack", "(", "jam", ",", "_audio", "=", "dict", "(", "y", "=", "y", ",", "sr", "=", "sr", ")", ")" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
save
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 for jams output fmt : str Output format parameter for `jams.JAMS.save` kwargs Additional parameters to `soundfile.write`
muda/core.py
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 for jams output fmt : str Output format parameter for `jams.JAMS.save` kwargs Additional parameters to `soundfile.write` ''' y = jam.sandbox.muda._audio['y'] sr = jam.sandbox.muda._audio['sr'] # First, dump the audio file psf.write(filename_audio, y, sr, **kwargs) # Then dump the jam jam.save(filename_jam, strict=strict, fmt=fmt)
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 for jams output fmt : str Output format parameter for `jams.JAMS.save` kwargs Additional parameters to `soundfile.write` ''' y = jam.sandbox.muda._audio['y'] sr = jam.sandbox.muda._audio['sr'] # First, dump the audio file psf.write(filename_audio, y, sr, **kwargs) # Then dump the jam jam.save(filename_jam, strict=strict, fmt=fmt)
[ "Save", "a", "muda", "jam", "to", "disk" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L122-L150
[ "def", "save", "(", "filename_audio", ",", "filename_jam", ",", "jam", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ",", "*", "*", "kwargs", ")", ":", "y", "=", "jam", ".", "sandbox", ".", "muda", ".", "_audio", "[", "'y'", "]", "sr", "=", "jam", ".", "sandbox", ".", "muda", ".", "_audio", "[", "'sr'", "]", "# First, dump the audio file", "psf", ".", "write", "(", "filename_audio", ",", "y", ",", "sr", ",", "*", "*", "kwargs", ")", "# Then dump the jam", "jam", ".", "save", "(", "filename_jam", ",", "strict", "=", "strict", ",", "fmt", "=", "fmt", ")" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
__reconstruct
Reconstruct a transformation or pipeline given a parameter dump.
muda/core.py
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 = dict() for key, value in six.iteritems(params): data[key] = __reconstruct(value) return data elif isinstance(params, (list, tuple)): return [__reconstruct(v) for v in params] else: return params
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 = dict() for key, value in six.iteritems(params): data[key] = __reconstruct(value) return data elif isinstance(params, (list, tuple)): return [__reconstruct(v) for v in params] else: return params
[ "Reconstruct", "a", "transformation", "or", "pipeline", "given", "a", "parameter", "dump", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L153-L171
[ "def", "__reconstruct", "(", "params", ")", ":", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "if", "'__class__'", "in", "params", ":", "cls", "=", "params", "[", "'__class__'", "]", "data", "=", "__reconstruct", "(", "params", "[", "'params'", "]", ")", "return", "cls", "(", "*", "*", "data", ")", "else", ":", "data", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "params", ")", ":", "data", "[", "key", "]", "=", "__reconstruct", "(", "value", ")", "return", "data", "elif", "isinstance", "(", "params", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "__reconstruct", "(", "v", ")", "for", "v", "in", "params", "]", "else", ":", "return", "params" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
serialize
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 ------- json_str : str A JSON encoding of the transformation See Also -------- deserialize Examples -------- >>> D = muda.deformers.TimeStretch(rate=1.5) >>> muda.serialize(D) '{"params": {"rate": 1.5}, "__class__": {"py/type": "muda.deformers.time.TimeStretch"}}'
muda/core.py
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 ------- json_str : str A JSON encoding of the transformation See Also -------- deserialize Examples -------- >>> D = muda.deformers.TimeStretch(rate=1.5) >>> muda.serialize(D) '{"params": {"rate": 1.5}, "__class__": {"py/type": "muda.deformers.time.TimeStretch"}}' ''' params = transform.get_params() return jsonpickle.encode(params, **kwargs)
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 ------- json_str : str A JSON encoding of the transformation See Also -------- deserialize Examples -------- >>> D = muda.deformers.TimeStretch(rate=1.5) >>> muda.serialize(D) '{"params": {"rate": 1.5}, "__class__": {"py/type": "muda.deformers.time.TimeStretch"}}' ''' params = transform.get_params() return jsonpickle.encode(params, **kwargs)
[ "Serialize", "a", "transformation", "object", "or", "pipeline", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L174-L203
[ "def", "serialize", "(", "transform", ",", "*", "*", "kwargs", ")", ":", "params", "=", "transform", ".", "get_params", "(", ")", "return", "jsonpickle", ".", "encode", "(", "params", ",", "*", "*", "kwargs", ")" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
deserialize
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 The transformation See Also -------- serialize Examples -------- >>> D = muda.deformers.TimeStretch(rate=1.5) >>> D_serial = muda.serialize(D) >>> D2 = muda.deserialize(D_serial) >>> D2 TimeStretch(rate=1.5)
muda/core.py
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 The transformation See Also -------- serialize Examples -------- >>> D = muda.deformers.TimeStretch(rate=1.5) >>> D_serial = muda.serialize(D) >>> D2 = muda.deserialize(D_serial) >>> D2 TimeStretch(rate=1.5) ''' params = jsonpickle.decode(encoded, **kwargs) return __reconstruct(params)
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 The transformation See Also -------- serialize Examples -------- >>> D = muda.deformers.TimeStretch(rate=1.5) >>> D_serial = muda.serialize(D) >>> D2 = muda.deserialize(D_serial) >>> D2 TimeStretch(rate=1.5) ''' params = jsonpickle.decode(encoded, **kwargs) return __reconstruct(params)
[ "Construct", "a", "muda", "transformation", "from", "a", "JSON", "encoded", "string", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L206-L237
[ "def", "deserialize", "(", "encoded", ",", "*", "*", "kwargs", ")", ":", "params", "=", "jsonpickle", ".", "decode", "(", "encoded", ",", "*", "*", "kwargs", ")", "return", "__reconstruct", "(", "params", ")" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
_pprint
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 strings, typically the builtin str or repr
muda/base.py
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 strings, typically the builtin str or repr """ # Do a multi-line justified repr: options = np.get_printoptions() np.set_printoptions(precision=5, threshold=64, edgeitems=2) params_list = list() this_line_length = offset line_sep = ',\n' + (1 + offset // 2) * ' ' for i, (k, v) in enumerate(sorted(six.iteritems(params))): if type(v) is float: # use str for representing floating point numbers # this way we get consistent representation across # architectures and versions. this_repr = '%s=%s' % (k, str(v)) else: # use repr of the rest this_repr = '%s=%s' % (k, printer(v)) if len(this_repr) > 500: this_repr = this_repr[:300] + '...' + this_repr[-100:] if i > 0: if (this_line_length + len(this_repr) >= 75 or '\n' in this_repr): params_list.append(line_sep) this_line_length = len(line_sep) else: params_list.append(', ') this_line_length += 2 params_list.append(this_repr) this_line_length += len(this_repr) np.set_printoptions(**options) lines = ''.join(params_list) # Strip trailing space to avoid nightmare in doctests lines = '\n'.join(l.rstrip(' ') for l in lines.split('\n')) return lines
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 strings, typically the builtin str or repr """ # Do a multi-line justified repr: options = np.get_printoptions() np.set_printoptions(precision=5, threshold=64, edgeitems=2) params_list = list() this_line_length = offset line_sep = ',\n' + (1 + offset // 2) * ' ' for i, (k, v) in enumerate(sorted(six.iteritems(params))): if type(v) is float: # use str for representing floating point numbers # this way we get consistent representation across # architectures and versions. this_repr = '%s=%s' % (k, str(v)) else: # use repr of the rest this_repr = '%s=%s' % (k, printer(v)) if len(this_repr) > 500: this_repr = this_repr[:300] + '...' + this_repr[-100:] if i > 0: if (this_line_length + len(this_repr) >= 75 or '\n' in this_repr): params_list.append(line_sep) this_line_length = len(line_sep) else: params_list.append(', ') this_line_length += 2 params_list.append(this_repr) this_line_length += len(this_repr) np.set_printoptions(**options) lines = ''.join(params_list) # Strip trailing space to avoid nightmare in doctests lines = '\n'.join(l.rstrip(' ') for l in lines.split('\n')) return lines
[ "Pretty", "print", "the", "dictionary", "params" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L347-L394
[ "def", "_pprint", "(", "params", ",", "offset", "=", "0", ",", "printer", "=", "repr", ")", ":", "# Do a multi-line justified repr:", "options", "=", "np", ".", "get_printoptions", "(", ")", "np", ".", "set_printoptions", "(", "precision", "=", "5", ",", "threshold", "=", "64", ",", "edgeitems", "=", "2", ")", "params_list", "=", "list", "(", ")", "this_line_length", "=", "offset", "line_sep", "=", "',\\n'", "+", "(", "1", "+", "offset", "//", "2", ")", "*", "' '", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "sorted", "(", "six", ".", "iteritems", "(", "params", ")", ")", ")", ":", "if", "type", "(", "v", ")", "is", "float", ":", "# use str for representing floating point numbers", "# this way we get consistent representation across", "# architectures and versions.", "this_repr", "=", "'%s=%s'", "%", "(", "k", ",", "str", "(", "v", ")", ")", "else", ":", "# use repr of the rest", "this_repr", "=", "'%s=%s'", "%", "(", "k", ",", "printer", "(", "v", ")", ")", "if", "len", "(", "this_repr", ")", ">", "500", ":", "this_repr", "=", "this_repr", "[", ":", "300", "]", "+", "'...'", "+", "this_repr", "[", "-", "100", ":", "]", "if", "i", ">", "0", ":", "if", "(", "this_line_length", "+", "len", "(", "this_repr", ")", ">=", "75", "or", "'\\n'", "in", "this_repr", ")", ":", "params_list", ".", "append", "(", "line_sep", ")", "this_line_length", "=", "len", "(", "line_sep", ")", "else", ":", "params_list", ".", "append", "(", "', '", ")", "this_line_length", "+=", "2", "params_list", ".", "append", "(", "this_repr", ")", "this_line_length", "+=", "len", "(", "this_repr", ")", "np", ".", "set_printoptions", "(", "*", "*", "options", ")", "lines", "=", "''", ".", "join", "(", "params_list", ")", "# Strip trailing space to avoid nightmare in doctests", "lines", "=", "'\\n'", ".", "join", "(", "l", ".", "rstrip", "(", "' '", ")", "for", "l", "in", "lines", ".", "split", "(", "'\\n'", ")", ")", "return", "lines" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
BaseTransformer._get_param_names
Get the list of parameter names for the object
muda/base.py
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() return args
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() return args
[ "Get", "the", "list", "of", "parameter", "names", "for", "the", "object" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L21-L33
[ "def", "_get_param_names", "(", "cls", ")", ":", "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", "(", ")", "return", "args" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
BaseTransformer.get_params
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
muda/base.py
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 ''' out = dict(__class__=self.__class__, params=dict()) for key in self._get_param_names(): value = getattr(self, key, None) if deep and hasattr(value, 'get_params'): deep_items = value.get_params().items() out['params'][key] = dict(__class__=value.__class__) out['params'][key].update((k, val) for k, val in deep_items) else: out['params'][key] = value return out
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 ''' out = dict(__class__=self.__class__, params=dict()) for key in self._get_param_names(): value = getattr(self, key, None) if deep and hasattr(value, 'get_params'): deep_items = value.get_params().items() out['params'][key] = dict(__class__=value.__class__) out['params'][key].update((k, val) for k, val in deep_items) else: out['params'][key] = value return out
[ "Get", "the", "parameters", "for", "this", "object", ".", "Returns", "as", "a", "dict", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L35-L62
[ "def", "get_params", "(", "self", ",", "deep", "=", "True", ")", ":", "out", "=", "dict", "(", "__class__", "=", "self", ".", "__class__", ",", "params", "=", "dict", "(", ")", ")", "for", "key", "in", "self", ".", "_get_param_names", "(", ")", ":", "value", "=", "getattr", "(", "self", ",", "key", ",", "None", ")", "if", "deep", "and", "hasattr", "(", "value", ",", "'get_params'", ")", ":", "deep_items", "=", "value", ".", "get_params", "(", ")", ".", "items", "(", ")", "out", "[", "'params'", "]", "[", "key", "]", "=", "dict", "(", "__class__", "=", "value", ".", "__class__", ")", "out", "[", "'params'", "]", "[", "key", "]", ".", "update", "(", "(", "k", ",", "val", ")", "for", "k", ",", "val", "in", "deep_items", ")", "else", ":", "out", "[", "'params'", "]", "[", "key", "]", "=", "value", "return", "out" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
BaseTransformer._transform
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 ------- jam_list : list A length-1 list containing `jam` after transformation See also -------- core.load_jam_audio
muda/base.py
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 ------- jam_list : list A length-1 list containing `jam` after transformation See also -------- core.load_jam_audio ''' if not hasattr(jam.sandbox, 'muda'): raise RuntimeError('No muda state found in jams sandbox.') # We'll need a working copy of this object for modification purposes jam_w = copy.deepcopy(jam) # Push our reconstructor onto the history stack jam_w.sandbox.muda['history'].append({'transformer': self.__serialize__, 'state': state}) if hasattr(self, 'audio'): self.audio(jam_w.sandbox.muda, state) if hasattr(self, 'metadata'): self.metadata(jam_w.file_metadata, state) # Walk over the list of deformers for query, function_name in six.iteritems(self.dispatch): function = getattr(self, function_name) for matched_annotation in jam_w.search(namespace=query): function(matched_annotation, state) return jam_w
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 ------- jam_list : list A length-1 list containing `jam` after transformation See also -------- core.load_jam_audio ''' if not hasattr(jam.sandbox, 'muda'): raise RuntimeError('No muda state found in jams sandbox.') # We'll need a working copy of this object for modification purposes jam_w = copy.deepcopy(jam) # Push our reconstructor onto the history stack jam_w.sandbox.muda['history'].append({'transformer': self.__serialize__, 'state': state}) if hasattr(self, 'audio'): self.audio(jam_w.sandbox.muda, state) if hasattr(self, 'metadata'): self.metadata(jam_w.file_metadata, state) # Walk over the list of deformers for query, function_name in six.iteritems(self.dispatch): function = getattr(self, function_name) for matched_annotation in jam_w.search(namespace=query): function(matched_annotation, state) return jam_w
[ "Apply", "the", "transformation", "to", "audio", "and", "annotations", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L81-L124
[ "def", "_transform", "(", "self", ",", "jam", ",", "state", ")", ":", "if", "not", "hasattr", "(", "jam", ".", "sandbox", ",", "'muda'", ")", ":", "raise", "RuntimeError", "(", "'No muda state found in jams sandbox.'", ")", "# We'll need a working copy of this object for modification purposes", "jam_w", "=", "copy", ".", "deepcopy", "(", "jam", ")", "# Push our reconstructor onto the history stack", "jam_w", ".", "sandbox", ".", "muda", "[", "'history'", "]", ".", "append", "(", "{", "'transformer'", ":", "self", ".", "__serialize__", ",", "'state'", ":", "state", "}", ")", "if", "hasattr", "(", "self", ",", "'audio'", ")", ":", "self", ".", "audio", "(", "jam_w", ".", "sandbox", ".", "muda", ",", "state", ")", "if", "hasattr", "(", "self", ",", "'metadata'", ")", ":", "self", ".", "metadata", "(", "jam_w", ".", "file_metadata", ",", "state", ")", "# Walk over the list of deformers", "for", "query", ",", "function_name", "in", "six", ".", "iteritems", "(", "self", ".", "dispatch", ")", ":", "function", "=", "getattr", "(", "self", ",", "function_name", ")", "for", "matched_annotation", "in", "jam_w", ".", "search", "(", "namespace", "=", "query", ")", ":", "function", "(", "matched_annotation", ",", "state", ")", "return", "jam_w" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
BaseTransformer.transform
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 -------- >>> for jam_out in deformer.transform(jam_in): ... process(jam_out)
muda/base.py
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 -------- >>> for jam_out in deformer.transform(jam_in): ... process(jam_out) ''' for state in self.states(jam): yield self._transform(jam, state)
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 -------- >>> for jam_out in deformer.transform(jam_in): ... process(jam_out) ''' for state in self.states(jam): yield self._transform(jam, state)
[ "Iterative", "transformation", "generator" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L126-L145
[ "def", "transform", "(", "self", ",", "jam", ")", ":", "for", "state", "in", "self", ".", "states", "(", "jam", ")", ":", "yield", "self", ".", "_transform", "(", "jam", ",", "state", ")" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
Pipeline.get_params
Get the parameters for this object. Returns as a dict.
muda/base.py
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)]) return out
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)]) return out
[ "Get", "the", "parameters", "for", "this", "object", ".", "Returns", "as", "a", "dict", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L196-L206
[ "def", "get_params", "(", "self", ")", ":", "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", ")", "]", ")", "return", "out" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
Pipeline.__recursive_transform
A recursive transformation pipeline
muda/base.py
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 q else: yield jam
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 q else: yield jam
[ "A", "recursive", "transformation", "pipeline" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L216-L225
[ "def", "__recursive_transform", "(", "self", ",", "jam", ",", "steps", ")", ":", "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", "q", "else", ":", "yield", "jam" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
Pipeline.transform
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 sequence
muda/base.py
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 sequence ''' for output in self.__recursive_transform(jam, self.steps): yield output
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 sequence ''' for output in self.__recursive_transform(jam, self.steps): yield output
[ "Apply", "the", "sequence", "of", "transformations", "to", "a", "single", "jam", "object", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L227-L242
[ "def", "transform", "(", "self", ",", "jam", ")", ":", "for", "output", "in", "self", ".", "__recursive_transform", "(", "jam", ",", "self", ".", "steps", ")", ":", "yield", "output" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
Union.__serial_transform
A serial transformation union
muda/base.py
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)), attr) for (name, D) in steps) while pending: try: for next_jam in nexts: yield next_jam() except StopIteration: pending -= 1 nexts = itertools.cycle(itertools.islice(nexts, pending))
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)), attr) for (name, D) in steps) while pending: try: for next_jam in nexts: yield next_jam() except StopIteration: pending -= 1 nexts = itertools.cycle(itertools.islice(nexts, pending))
[ "A", "serial", "transformation", "union" ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L306-L325
[ "def", "__serial_transform", "(", "self", ",", "jam", ",", "steps", ")", ":", "# 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", ")", ")", ",", "attr", ")", "for", "(", "name", ",", "D", ")", "in", "steps", ")", "while", "pending", ":", "try", ":", "for", "next_jam", "in", "nexts", ":", "yield", "next_jam", "(", ")", "except", "StopIteration", ":", "pending", "-=", "1", "nexts", "=", "itertools", ".", "cycle", "(", "itertools", ".", "islice", "(", "nexts", ",", "pending", ")", ")" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
Union.transform
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 union
muda/base.py
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 union ''' for output in self.__serial_transform(jam, self.steps): yield output
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 union ''' for output in self.__serial_transform(jam, self.steps): yield output
[ "Apply", "the", "sequence", "of", "transformations", "to", "a", "single", "jam", "object", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L327-L342
[ "def", "transform", "(", "self", ",", "jam", ")", ":", "for", "output", "in", "self", ".", "__serial_transform", "(", "jam", ",", "self", ".", "steps", ")", ":", "yield", "output" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
sample_clip_indices
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 rate Returns ------- start : int The sample index from `filename` at which the audio fragment starts stop : int The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop])
muda/deformers/background.py
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 rate Returns ------- start : int The sample index from `filename` at which the audio fragment starts stop : int The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop]) ''' with psf.SoundFile(str(filename), mode='r') as soundf: # Measure required length of fragment n_target = int(np.ceil(n_samples * soundf.samplerate / float(sr))) # Raise exception if source is too short if len(soundf) < n_target: raise RuntimeError('Source {} (length={})'.format(filename, len(soundf)) + ' must be at least the length of the input ({})'.format(n_target)) # Draw a starting point at random in the background waveform start = np.random.randint(0, 1 + len(soundf) - n_target) stop = start + n_target return start, stop
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 rate Returns ------- start : int The sample index from `filename` at which the audio fragment starts stop : int The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop]) ''' with psf.SoundFile(str(filename), mode='r') as soundf: # Measure required length of fragment n_target = int(np.ceil(n_samples * soundf.samplerate / float(sr))) # Raise exception if source is too short if len(soundf) < n_target: raise RuntimeError('Source {} (length={})'.format(filename, len(soundf)) + ' must be at least the length of the input ({})'.format(n_target)) # Draw a starting point at random in the background waveform start = np.random.randint(0, 1 + len(soundf) - n_target) stop = start + n_target return start, stop
[ "Calculate", "the", "indices", "at", "which", "to", "sample", "a", "fragment", "of", "audio", "from", "a", "file", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/background.py#L15-L50
[ "def", "sample_clip_indices", "(", "filename", ",", "n_samples", ",", "sr", ")", ":", "with", "psf", ".", "SoundFile", "(", "str", "(", "filename", ")", ",", "mode", "=", "'r'", ")", "as", "soundf", ":", "# Measure required length of fragment", "n_target", "=", "int", "(", "np", ".", "ceil", "(", "n_samples", "*", "soundf", ".", "samplerate", "/", "float", "(", "sr", ")", ")", ")", "# Raise exception if source is too short", "if", "len", "(", "soundf", ")", "<", "n_target", ":", "raise", "RuntimeError", "(", "'Source {} (length={})'", ".", "format", "(", "filename", ",", "len", "(", "soundf", ")", ")", "+", "' must be at least the length of the input ({})'", ".", "format", "(", "n_target", ")", ")", "# Draw a starting point at random in the background waveform", "start", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "1", "+", "len", "(", "soundf", ")", "-", "n_target", ")", "stop", "=", "start", "+", "n_target", "return", "start", ",", "stop" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
slice_clip
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 of `filename` at which the audio fragment should start stop : int The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop]) n_samples : int > 0 The number of samples to load sr : int > 0 The target sampling rate mono : bool Ensure monophonic audio Returns ------- y : np.ndarray [shape=(n_samples,)] A fragment of audio sampled from `filename` Raises ------ ValueError If the source file is shorter than the requested length
muda/deformers/background.py
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 of `filename` at which the audio fragment should start stop : int The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop]) n_samples : int > 0 The number of samples to load sr : int > 0 The target sampling rate mono : bool Ensure monophonic audio Returns ------- y : np.ndarray [shape=(n_samples,)] A fragment of audio sampled from `filename` Raises ------ ValueError If the source file is shorter than the requested length ''' with psf.SoundFile(str(filename), mode='r') as soundf: n_target = stop - start soundf.seek(start) y = soundf.read(n_target).T if mono: y = librosa.to_mono(y) # Resample to initial sr y = librosa.resample(y, soundf.samplerate, sr) # Clip to the target length exactly y = librosa.util.fix_length(y, n_samples) return y
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 of `filename` at which the audio fragment should start stop : int The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop]) n_samples : int > 0 The number of samples to load sr : int > 0 The target sampling rate mono : bool Ensure monophonic audio Returns ------- y : np.ndarray [shape=(n_samples,)] A fragment of audio sampled from `filename` Raises ------ ValueError If the source file is shorter than the requested length ''' with psf.SoundFile(str(filename), mode='r') as soundf: n_target = stop - start soundf.seek(start) y = soundf.read(n_target).T if mono: y = librosa.to_mono(y) # Resample to initial sr y = librosa.resample(y, soundf.samplerate, sr) # Clip to the target length exactly y = librosa.util.fix_length(y, n_samples) return y
[ "Slice", "a", "fragment", "of", "audio", "from", "a", "file", "." ]
bmcfee/muda
python
https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/deformers/background.py#L53-L107
[ "def", "slice_clip", "(", "filename", ",", "start", ",", "stop", ",", "n_samples", ",", "sr", ",", "mono", "=", "True", ")", ":", "with", "psf", ".", "SoundFile", "(", "str", "(", "filename", ")", ",", "mode", "=", "'r'", ")", "as", "soundf", ":", "n_target", "=", "stop", "-", "start", "soundf", ".", "seek", "(", "start", ")", "y", "=", "soundf", ".", "read", "(", "n_target", ")", ".", "T", "if", "mono", ":", "y", "=", "librosa", ".", "to_mono", "(", "y", ")", "# Resample to initial sr", "y", "=", "librosa", ".", "resample", "(", "y", ",", "soundf", ".", "samplerate", ",", "sr", ")", "# Clip to the target length exactly", "y", "=", "librosa", ".", "util", ".", "fix_length", "(", "y", ",", "n_samples", ")", "return", "y" ]
ff82efdfaeb98da0a9f9124845826eb20536a9ba
valid
norm_remote_path
Normalize `path`. All remote paths are absolute.
osfclient/utils.py
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 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
[ "Normalize", "path", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L13-L22
[ "def", "norm_remote_path", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "if", "path", ".", "startswith", "(", "os", ".", "path", ".", "sep", ")", ":", "return", "path", "[", "1", ":", "]", "else", ":", "return", "path" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
split_storage
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.
osfclient/utils.py
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 provider in KNOWN_PROVIDERS: if path.startswith(provider + '/'): if six.PY3: return path.split('/', maxsplit=1) else: return path.split('/', 1) return (default, 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 provider in KNOWN_PROVIDERS: if path.startswith(provider + '/'): if six.PY3: return path.split('/', maxsplit=1) else: return path.split('/', 1) return (default, path)
[ "Extract", "storage", "name", "from", "file", "path", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L25-L41
[ "def", "split_storage", "(", "path", ",", "default", "=", "'osfstorage'", ")", ":", "path", "=", "norm_remote_path", "(", "path", ")", "for", "provider", "in", "KNOWN_PROVIDERS", ":", "if", "path", ".", "startswith", "(", "provider", "+", "'/'", ")", ":", "if", "six", ".", "PY3", ":", "return", "path", ".", "split", "(", "'/'", ",", "maxsplit", "=", "1", ")", "else", ":", "return", "path", ".", "split", "(", "'/'", ",", "1", ")", "return", "(", "default", ",", "path", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
file_empty
Determine if a file is empty or not.
osfclient/utils.py
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 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()
[ "Determine", "if", "a", "file", "is", "empty", "or", "not", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L55-L64
[ "def", "file_empty", "(", "fp", ")", ":", "# 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", "(", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
checksum
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://stackoverflow.com/a/44873382/2680. The code below is an extension of the example presented in that post.
osfclient/utils.py
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://stackoverflow.com/a/44873382/2680. The code below is an extension of the example presented in that post. """ if hash_type == 'md5': hash_ = hashlib.md5() elif hash_type == 'sha256': hash_ = hashlib.sha256() else: raise ValueError( "{} is an invalid hash_type. Expected 'md5' or 'sha256'." .format(hash_type) ) with open(file_path, 'rb') as f: for block in iter(lambda: f.read(block_size), b''): hash_.update(block) return hash_.hexdigest()
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://stackoverflow.com/a/44873382/2680. The code below is an extension of the example presented in that post. """ if hash_type == 'md5': hash_ = hashlib.md5() elif hash_type == 'sha256': hash_ = hashlib.sha256() else: raise ValueError( "{} is an invalid hash_type. Expected 'md5' or 'sha256'." .format(hash_type) ) with open(file_path, 'rb') as f: for block in iter(lambda: f.read(block_size), b''): hash_.update(block) return hash_.hexdigest()
[ "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" ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/utils.py#L67-L89
[ "def", "checksum", "(", "file_path", ",", "hash_type", "=", "'md5'", ",", "block_size", "=", "65536", ")", ":", "if", "hash_type", "==", "'md5'", ":", "hash_", "=", "hashlib", ".", "md5", "(", ")", "elif", "hash_type", "==", "'sha256'", ":", "hash_", "=", "hashlib", ".", "sha256", "(", ")", "else", ":", "raise", "ValueError", "(", "\"{} is an invalid hash_type. Expected 'md5' or 'sha256'.\"", ".", "format", "(", "hash_type", ")", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "for", "block", "in", "iter", "(", "lambda", ":", "f", ".", "read", "(", "block_size", ")", ",", "b''", ")", ":", "hash_", ".", "update", "(", "block", ")", "return", "hash_", ".", "hexdigest", "(", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
Project.storage
Return storage `provider`.
osfclient/models/project.py
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: return Storage(store, self.session) raise RuntimeError("Project has no storage " "provider '{}'".format(provider))
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: return Storage(store, self.session) raise RuntimeError("Project has no storage " "provider '{}'".format(provider))
[ "Return", "storage", "provider", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/project.py#L30-L40
[ "def", "storage", "(", "self", ",", "provider", "=", "'osfstorage'", ")", ":", "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", ":", "return", "Storage", "(", "store", ",", "self", ".", "session", ")", "raise", "RuntimeError", "(", "\"Project has no storage \"", "\"provider '{}'\"", ".", "format", "(", "provider", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
Project.storages
Iterate over all storages for this projects.
osfclient/models/project.py
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 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)
[ "Iterate", "over", "all", "storages", "for", "this", "projects", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/project.py#L43-L48
[ "def", "storages", "(", "self", ")", ":", "stores", "=", "self", ".", "_json", "(", "self", ".", "_get", "(", "self", ".", "_storages_url", ")", ",", "200", ")", "stores", "=", "stores", "[", "'data'", "]", "for", "store", "in", "stores", ":", "yield", "Storage", "(", "store", ",", "self", ".", "session", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
Storage.create_file
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 existing file, set `force=True`. To overwrite an existing file only if the files differ, set `update=True`
osfclient/models/storage.py
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 existing file, set `force=True`. To overwrite an existing file only if the files differ, set `update=True` """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") # all paths are assumed to be absolute path = norm_remote_path(path) directory, fname = os.path.split(path) directories = directory.split(os.path.sep) # navigate to the right parent object for our file parent = self for directory in directories: # skip empty directory names if directory: parent = parent.create_folder(directory, exist_ok=True) url = parent._new_file_url # When uploading a large file (>a few MB) that already exists # we sometimes get a ConnectionError instead of a status == 409. connection_error = False # peek at the file to check if it is an empty file which needs special # handling in requests. If we pass a file like object to data that # turns out to be of length zero then no file is created on the OSF. # See: https://github.com/osfclient/osfclient/pull/135 if file_empty(fp): response = self._put(url, params={'name': fname}, data=b'') else: try: response = self._put(url, params={'name': fname}, data=fp) except ConnectionError: connection_error = True if connection_error or response.status_code == 409: if not force and not update: # one-liner to get file size from file pointer from # https://stackoverflow.com/a/283719/2680824 file_size_bytes = get_local_file_size(fp) large_file_cutoff = 2**20 # 1 MB in bytes if connection_error and file_size_bytes < large_file_cutoff: msg = ( "There was a connection error which might mean {} " + "already exists. Try again with the `--force` flag " + "specified." ).format(path) raise RuntimeError(msg) else: # note in case of connection error, we are making an inference here raise FileExistsError(path) else: # find the upload URL for the file we are trying to update for file_ in self.files: if norm_remote_path(file_.path) == path: if not force: if checksum(path) == file_.hashes.get('md5'): # If the hashes are equal and force is False, # we're done here break # in the process of attempting to upload the file we # moved through it -> reset read position to beginning # of the file fp.seek(0) file_.update(fp) break else: raise RuntimeError("Could not create a new file at " "({}) nor update it.".format(path))
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 existing file, set `force=True`. To overwrite an existing file only if the files differ, set `update=True` """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") # all paths are assumed to be absolute path = norm_remote_path(path) directory, fname = os.path.split(path) directories = directory.split(os.path.sep) # navigate to the right parent object for our file parent = self for directory in directories: # skip empty directory names if directory: parent = parent.create_folder(directory, exist_ok=True) url = parent._new_file_url # When uploading a large file (>a few MB) that already exists # we sometimes get a ConnectionError instead of a status == 409. connection_error = False # peek at the file to check if it is an empty file which needs special # handling in requests. If we pass a file like object to data that # turns out to be of length zero then no file is created on the OSF. # See: https://github.com/osfclient/osfclient/pull/135 if file_empty(fp): response = self._put(url, params={'name': fname}, data=b'') else: try: response = self._put(url, params={'name': fname}, data=fp) except ConnectionError: connection_error = True if connection_error or response.status_code == 409: if not force and not update: # one-liner to get file size from file pointer from # https://stackoverflow.com/a/283719/2680824 file_size_bytes = get_local_file_size(fp) large_file_cutoff = 2**20 # 1 MB in bytes if connection_error and file_size_bytes < large_file_cutoff: msg = ( "There was a connection error which might mean {} " + "already exists. Try again with the `--force` flag " + "specified." ).format(path) raise RuntimeError(msg) else: # note in case of connection error, we are making an inference here raise FileExistsError(path) else: # find the upload URL for the file we are trying to update for file_ in self.files: if norm_remote_path(file_.path) == path: if not force: if checksum(path) == file_.hashes.get('md5'): # If the hashes are equal and force is False, # we're done here break # in the process of attempting to upload the file we # moved through it -> reset read position to beginning # of the file fp.seek(0) file_.update(fp) break else: raise RuntimeError("Could not create a new file at " "({}) nor update it.".format(path))
[ "Store", "a", "new", "file", "at", "path", "in", "this", "storage", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/storage.py#L55-L132
[ "def", "create_file", "(", "self", ",", "path", ",", "fp", ",", "force", "=", "False", ",", "update", "=", "False", ")", ":", "if", "'b'", "not", "in", "fp", ".", "mode", ":", "raise", "ValueError", "(", "\"File has to be opened in binary mode.\"", ")", "# all paths are assumed to be absolute", "path", "=", "norm_remote_path", "(", "path", ")", "directory", ",", "fname", "=", "os", ".", "path", ".", "split", "(", "path", ")", "directories", "=", "directory", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "# navigate to the right parent object for our file", "parent", "=", "self", "for", "directory", "in", "directories", ":", "# skip empty directory names", "if", "directory", ":", "parent", "=", "parent", ".", "create_folder", "(", "directory", ",", "exist_ok", "=", "True", ")", "url", "=", "parent", ".", "_new_file_url", "# When uploading a large file (>a few MB) that already exists", "# we sometimes get a ConnectionError instead of a status == 409.", "connection_error", "=", "False", "# peek at the file to check if it is an empty file which needs special", "# handling in requests. If we pass a file like object to data that", "# turns out to be of length zero then no file is created on the OSF.", "# See: https://github.com/osfclient/osfclient/pull/135", "if", "file_empty", "(", "fp", ")", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "params", "=", "{", "'name'", ":", "fname", "}", ",", "data", "=", "b''", ")", "else", ":", "try", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "params", "=", "{", "'name'", ":", "fname", "}", ",", "data", "=", "fp", ")", "except", "ConnectionError", ":", "connection_error", "=", "True", "if", "connection_error", "or", "response", ".", "status_code", "==", "409", ":", "if", "not", "force", "and", "not", "update", ":", "# one-liner to get file size from file pointer from", "# https://stackoverflow.com/a/283719/2680824", "file_size_bytes", "=", "get_local_file_size", "(", "fp", ")", "large_file_cutoff", "=", "2", "**", "20", "# 1 MB in bytes", "if", "connection_error", "and", "file_size_bytes", "<", "large_file_cutoff", ":", "msg", "=", "(", "\"There was a connection error which might mean {} \"", "+", "\"already exists. Try again with the `--force` flag \"", "+", "\"specified.\"", ")", ".", "format", "(", "path", ")", "raise", "RuntimeError", "(", "msg", ")", "else", ":", "# note in case of connection error, we are making an inference here", "raise", "FileExistsError", "(", "path", ")", "else", ":", "# find the upload URL for the file we are trying to update", "for", "file_", "in", "self", ".", "files", ":", "if", "norm_remote_path", "(", "file_", ".", "path", ")", "==", "path", ":", "if", "not", "force", ":", "if", "checksum", "(", "path", ")", "==", "file_", ".", "hashes", ".", "get", "(", "'md5'", ")", ":", "# If the hashes are equal and force is False,", "# we're done here", "break", "# in the process of attempting to upload the file we", "# moved through it -> reset read position to beginning", "# of the file", "fp", ".", "seek", "(", "0", ")", "file_", ".", "update", "(", "fp", ")", "break", "else", ":", "raise", "RuntimeError", "(", "\"Could not create a new file at \"", "\"({}) nor update it.\"", ".", "format", "(", "path", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
copyfileobj
Copy data from file-like object fsrc to file-like object fdst This is like shutil.copyfileobj but with a progressbar.
osfclient/models/file.py
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) if not buf: break fdst.write(buf) pbar.update(len(buf))
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) if not buf: break fdst.write(buf) pbar.update(len(buf))
[ "Copy", "data", "from", "file", "-", "like", "object", "fsrc", "to", "file", "-", "like", "object", "fdst" ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L7-L18
[ "def", "copyfileobj", "(", "fsrc", ",", "fdst", ",", "total", ",", "length", "=", "16", "*", "1024", ")", ":", "with", "tqdm", "(", "unit", "=", "'bytes'", ",", "total", "=", "total", ",", "unit_scale", "=", "True", ")", "as", "pbar", ":", "while", "1", ":", "buf", "=", "fsrc", ".", "read", "(", "length", ")", "if", "not", "buf", ":", "break", "fdst", ".", "write", "(", "buf", ")", "pbar", ".", "update", "(", "len", "(", "buf", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
File.write_to
Write contents of this file to a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode.
osfclient/models/file.py
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._download_url, stream=True) if response.status_code == 200: response.raw.decode_content = True copyfileobj(response.raw, fp, int(response.headers['Content-Length'])) else: raise RuntimeError("Response has status " "code {}.".format(response.status_code))
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._download_url, stream=True) if response.status_code == 200: response.raw.decode_content = True copyfileobj(response.raw, fp, int(response.headers['Content-Length'])) else: raise RuntimeError("Response has status " "code {}.".format(response.status_code))
[ "Write", "contents", "of", "this", "file", "to", "a", "local", "file", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L46-L63
[ "def", "write_to", "(", "self", ",", "fp", ")", ":", "if", "'b'", "not", "in", "fp", ".", "mode", ":", "raise", "ValueError", "(", "\"File has to be opened in binary mode.\"", ")", "response", "=", "self", ".", "_get", "(", "self", ".", "_download_url", ",", "stream", "=", "True", ")", "if", "response", ".", "status_code", "==", "200", ":", "response", ".", "raw", ".", "decode_content", "=", "True", "copyfileobj", "(", "response", ".", "raw", ",", "fp", ",", "int", "(", "response", ".", "headers", "[", "'Content-Length'", "]", ")", ")", "else", ":", "raise", "RuntimeError", "(", "\"Response has status \"", "\"code {}.\"", ".", "format", "(", "response", ".", "status_code", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
File.remove
Remove this file from the remote storage.
osfclient/models/file.py
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 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))
[ "Remove", "this", "file", "from", "the", "remote", "storage", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L65-L69
[ "def", "remove", "(", "self", ")", ":", "response", "=", "self", ".", "_delete", "(", "self", ".", "_delete_url", ")", "if", "response", ".", "status_code", "!=", "204", ":", "raise", "RuntimeError", "(", "'Could not delete {}.'", ".", "format", "(", "self", ".", "path", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
File.update
Update the remote file from a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode.
osfclient/models/file.py
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 # peek at the file to check if it is an ampty file which needs special # handling in requests. If we pass a file like object to data that # turns out to be of length zero then no file is created on the OSF if fp.peek(1): response = self._put(url, data=fp) else: response = self._put(url, data=b'') if response.status_code != 200: msg = ('Could not update {} (status ' 'code: {}).'.format(self.path, response.status_code)) raise RuntimeError(msg)
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 # peek at the file to check if it is an ampty file which needs special # handling in requests. If we pass a file like object to data that # turns out to be of length zero then no file is created on the OSF if fp.peek(1): response = self._put(url, data=fp) else: response = self._put(url, data=b'') if response.status_code != 200: msg = ('Could not update {} (status ' 'code: {}).'.format(self.path, response.status_code)) raise RuntimeError(msg)
[ "Update", "the", "remote", "file", "from", "a", "local", "file", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L71-L92
[ "def", "update", "(", "self", ",", "fp", ")", ":", "if", "'b'", "not", "in", "fp", ".", "mode", ":", "raise", "ValueError", "(", "\"File has to be opened in binary mode.\"", ")", "url", "=", "self", ".", "_upload_url", "# peek at the file to check if it is an ampty file which needs special", "# handling in requests. If we pass a file like object to data that", "# turns out to be of length zero then no file is created on the OSF", "if", "fp", ".", "peek", "(", "1", ")", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "data", "=", "fp", ")", "else", ":", "response", "=", "self", ".", "_put", "(", "url", ",", "data", "=", "b''", ")", "if", "response", ".", "status_code", "!=", "200", ":", "msg", "=", "(", "'Could not update {} (status '", "'code: {}).'", ".", "format", "(", "self", ".", "path", ",", "response", ".", "status_code", ")", ")", "raise", "RuntimeError", "(", "msg", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
ContainerMixin._iter_children
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.
osfclient/models/file.py
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 = self._follow_next(url) while children: child = children.pop() kind_ = child['attributes']['kind'] if kind_ == kind: yield klass(child, self.session) elif recurse is not None: # recurse into a child and add entries to `children` url = self._get_attribute(child, *recurse) children.extend(self._follow_next(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 = self._follow_next(url) while children: child = children.pop() kind_ = child['attributes']['kind'] if kind_ == kind: yield klass(child, self.session) elif recurse is not None: # recurse into a child and add entries to `children` url = self._get_attribute(child, *recurse) children.extend(self._follow_next(url))
[ "Iterate", "over", "all", "children", "of", "kind" ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L96-L113
[ "def", "_iter_children", "(", "self", ",", "url", ",", "kind", ",", "klass", ",", "recurse", "=", "None", ")", ":", "children", "=", "self", ".", "_follow_next", "(", "url", ")", "while", "children", ":", "child", "=", "children", ".", "pop", "(", ")", "kind_", "=", "child", "[", "'attributes'", "]", "[", "'kind'", "]", "if", "kind_", "==", "kind", ":", "yield", "klass", "(", "child", ",", "self", ".", "session", ")", "elif", "recurse", "is", "not", "None", ":", "# recurse into a child and add entries to `children`", "url", "=", "self", ".", "_get_attribute", "(", "child", ",", "*", "recurse", ")", "children", ".", "extend", "(", "self", ".", "_follow_next", "(", "url", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
might_need_auth
Decorate a CLI function that might require authentication. Catches any UnauthorizedException raised, prints a helpful message and then exits.
osfclient/cli.py
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 as e: config = config_from_env(config_from_file()) username = _get_username(cli_args, config) if username is None: sys.exit("Please set a username (run `osf -h` for details).") else: sys.exit("You are not authorized to access this project.") return return_value return wrapper
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 as e: config = config_from_env(config_from_file()) username = _get_username(cli_args, config) if username is None: sys.exit("Please set a username (run `osf -h` for details).") else: sys.exit("You are not authorized to access this project.") return return_value return wrapper
[ "Decorate", "a", "CLI", "function", "that", "might", "require", "authentication", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L82-L103
[ "def", "might_need_auth", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "cli_args", ")", ":", "try", ":", "return_value", "=", "f", "(", "cli_args", ")", "except", "UnauthorizedException", "as", "e", ":", "config", "=", "config_from_env", "(", "config_from_file", "(", ")", ")", "username", "=", "_get_username", "(", "cli_args", ",", "config", ")", "if", "username", "is", "None", ":", "sys", ".", "exit", "(", "\"Please set a username (run `osf -h` for details).\"", ")", "else", ":", "sys", ".", "exit", "(", "\"You are not authorized to access this project.\"", ")", "return", "return_value", "return", "wrapper" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
init
Initialize or edit an existing .osfcli.config file.
osfclient/cli.py
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', 'username', '') else: config_.set('osf', 'username', config['username']) if 'project' not in config.keys(): config_.set('osf', 'project', '') else: config_.set('osf', 'project', config['project']) # now we can start asking for new values print('Provide a username for the config file [current username: {}]:'.format( config_.get('osf', 'username'))) username = input() if username: config_.set('osf', 'username', username) print('Provide a project for the config file [current project: {}]:'.format( config_.get('osf', 'project'))) project = input() if project: config_.set('osf', 'project', project) cfgfile = open(".osfcli.config", "w") config_.write(cfgfile) cfgfile.close()
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', 'username', '') else: config_.set('osf', 'username', config['username']) if 'project' not in config.keys(): config_.set('osf', 'project', '') else: config_.set('osf', 'project', config['project']) # now we can start asking for new values print('Provide a username for the config file [current username: {}]:'.format( config_.get('osf', 'username'))) username = input() if username: config_.set('osf', 'username', username) print('Provide a project for the config file [current project: {}]:'.format( config_.get('osf', 'project'))) project = input() if project: config_.set('osf', 'project', project) cfgfile = open(".osfcli.config", "w") config_.write(cfgfile) cfgfile.close()
[ "Initialize", "or", "edit", "an", "existing", ".", "osfcli", ".", "config", "file", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L106-L136
[ "def", "init", "(", "args", ")", ":", "# 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'", ",", "'username'", ",", "''", ")", "else", ":", "config_", ".", "set", "(", "'osf'", ",", "'username'", ",", "config", "[", "'username'", "]", ")", "if", "'project'", "not", "in", "config", ".", "keys", "(", ")", ":", "config_", ".", "set", "(", "'osf'", ",", "'project'", ",", "''", ")", "else", ":", "config_", ".", "set", "(", "'osf'", ",", "'project'", ",", "config", "[", "'project'", "]", ")", "# now we can start asking for new values", "print", "(", "'Provide a username for the config file [current username: {}]:'", ".", "format", "(", "config_", ".", "get", "(", "'osf'", ",", "'username'", ")", ")", ")", "username", "=", "input", "(", ")", "if", "username", ":", "config_", ".", "set", "(", "'osf'", ",", "'username'", ",", "username", ")", "print", "(", "'Provide a project for the config file [current project: {}]:'", ".", "format", "(", "config_", ".", "get", "(", "'osf'", ",", "'project'", ")", ")", ")", "project", "=", "input", "(", ")", "if", "project", ":", "config_", ".", "set", "(", "'osf'", ",", "'project'", ",", "project", ")", "cfgfile", "=", "open", "(", "\".osfcli.config\"", ",", "\"w\"", ")", "config_", ".", "write", "(", "cfgfile", ")", "cfgfile", ".", "close", "(", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
clone
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.
osfclient/cli.py
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 = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output with tqdm(unit='files') as pbar: for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) if os.path.exists(path) and args.update: if checksum(path) == file_.hashes.get('md5'): continue directory, _ = os.path.split(path) makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) pbar.update()
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 = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output with tqdm(unit='files') as pbar: for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) if os.path.exists(path) and args.update: if checksum(path) == file_.hashes.get('md5'): continue directory, _ = os.path.split(path) makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) pbar.update()
[ "Copy", "all", "files", "from", "all", "storages", "of", "a", "project", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L140-L175
[ "def", "clone", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "output_dir", "=", "args", ".", "project", "if", "args", ".", "output", "is", "not", "None", ":", "output_dir", "=", "args", ".", "output", "with", "tqdm", "(", "unit", "=", "'files'", ")", "as", "pbar", ":", "for", "store", "in", "project", ".", "storages", ":", "prefix", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "store", ".", "name", ")", "for", "file_", "in", "store", ".", "files", ":", "path", "=", "file_", ".", "path", "if", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "path", "[", "1", ":", "]", "path", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "args", ".", "update", ":", "if", "checksum", "(", "path", ")", "==", "file_", ".", "hashes", ".", "get", "(", "'md5'", ")", ":", "continue", "directory", ",", "_", "=", "os", ".", "path", ".", "split", "(", "path", ")", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "f", ":", "file_", ".", "write_to", "(", "f", ")", "pbar", ".", "update", "(", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
fetch
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 to specify a username. If args.force is True, write local file even if that file already exists. If args.force is False but args.update is True, overwrite an existing local file only if local and remote files differ.
osfclient/cli.py
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 to specify a username. If args.force is True, write local file even if that file already exists. If args.force is False but args.update is True, overwrite an existing local file only if local and remote files differ. """ storage, remote_path = split_storage(args.remote) local_path = args.local if local_path is None: _, local_path = os.path.split(remote_path) local_path_exists = os.path.exists(local_path) if local_path_exists and not args.force and not args.update: sys.exit("Local file %s already exists, not overwriting." % local_path) directory, _ = os.path.split(local_path) if directory: makedirs(directory, exist_ok=True) osf = _setup_osf(args) project = osf.project(args.project) store = project.storage(storage) for file_ in store.files: if norm_remote_path(file_.path) == remote_path: if local_path_exists and not args.force and args.update: if file_.hashes.get('md5') == checksum(local_path): print("Local file %s already matches remote." % local_path) break with open(local_path, 'wb') as fp: file_.write_to(fp) # only fetching one file so we are done break
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 to specify a username. If args.force is True, write local file even if that file already exists. If args.force is False but args.update is True, overwrite an existing local file only if local and remote files differ. """ storage, remote_path = split_storage(args.remote) local_path = args.local if local_path is None: _, local_path = os.path.split(remote_path) local_path_exists = os.path.exists(local_path) if local_path_exists and not args.force and not args.update: sys.exit("Local file %s already exists, not overwriting." % local_path) directory, _ = os.path.split(local_path) if directory: makedirs(directory, exist_ok=True) osf = _setup_osf(args) project = osf.project(args.project) store = project.storage(storage) for file_ in store.files: if norm_remote_path(file_.path) == remote_path: if local_path_exists and not args.force and args.update: if file_.hashes.get('md5') == checksum(local_path): print("Local file %s already matches remote." % local_path) break with open(local_path, 'wb') as fp: file_.write_to(fp) # only fetching one file so we are done break
[ "Fetch", "an", "individual", "file", "from", "a", "project", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L179-L222
[ "def", "fetch", "(", "args", ")", ":", "storage", ",", "remote_path", "=", "split_storage", "(", "args", ".", "remote", ")", "local_path", "=", "args", ".", "local", "if", "local_path", "is", "None", ":", "_", ",", "local_path", "=", "os", ".", "path", ".", "split", "(", "remote_path", ")", "local_path_exists", "=", "os", ".", "path", ".", "exists", "(", "local_path", ")", "if", "local_path_exists", "and", "not", "args", ".", "force", "and", "not", "args", ".", "update", ":", "sys", ".", "exit", "(", "\"Local file %s already exists, not overwriting.\"", "%", "local_path", ")", "directory", ",", "_", "=", "os", ".", "path", ".", "split", "(", "local_path", ")", "if", "directory", ":", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "osf", "=", "_setup_osf", "(", "args", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "store", "=", "project", ".", "storage", "(", "storage", ")", "for", "file_", "in", "store", ".", "files", ":", "if", "norm_remote_path", "(", "file_", ".", "path", ")", "==", "remote_path", ":", "if", "local_path_exists", "and", "not", "args", ".", "force", "and", "args", ".", "update", ":", "if", "file_", ".", "hashes", ".", "get", "(", "'md5'", ")", "==", "checksum", "(", "local_path", ")", ":", "print", "(", "\"Local file %s already matches remote.\"", "%", "local_path", ")", "break", "with", "open", "(", "local_path", ",", "'wb'", ")", "as", "fp", ":", "file_", ".", "write_to", "(", "fp", ")", "# only fetching one file so we are done", "break" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
list_
List all files from all storages for project. If the project is private you need to specify a username.
osfclient/cli.py
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: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path))
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: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path))
[ "List", "all", "files", "from", "all", "storages", "for", "project", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L226-L242
[ "def", "list_", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "for", "store", "in", "project", ".", "storages", ":", "prefix", "=", "store", ".", "name", "for", "file_", "in", "store", ".", "files", ":", "path", "=", "file_", ".", "path", "if", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "path", "[", "1", ":", "]", "print", "(", "os", ".", "path", ".", "join", "(", "prefix", ",", "path", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
upload
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 (and all its sub-directories) use the `-r` command-line option. If your source directory name ends in a / then files will be created directly in the remote directory. If it does not end in a slash an extra sub-directory with the name of the local directory will be created. To place contents of local directory `foo` in remote directory `bar/foo`: $ osf upload -r foo bar To place contents of local directory `foo` in remote directory `bar`: $ osf upload -r foo/ bar
osfclient/cli.py
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 (and all its sub-directories) use the `-r` command-line option. If your source directory name ends in a / then files will be created directly in the remote directory. If it does not end in a slash an extra sub-directory with the name of the local directory will be created. To place contents of local directory `foo` in remote directory `bar/foo`: $ osf upload -r foo bar To place contents of local directory `foo` in remote directory `bar`: $ osf upload -r foo/ bar """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys.exit('To upload a file you need to provide a username and' ' password.') project = osf.project(args.project) storage, remote_path = split_storage(args.destination) store = project.storage(storage) if args.recursive: if not os.path.isdir(args.source): raise RuntimeError("Expected source ({}) to be a directory when " "using recursive mode.".format(args.source)) # local name of the directory that is being uploaded _, dir_name = os.path.split(args.source) for root, _, files in os.walk(args.source): subdir_path = os.path.relpath(root, args.source) for fname in files: local_path = os.path.join(root, fname) with open(local_path, 'rb') as fp: # build the remote path + fname name = os.path.join(remote_path, dir_name, subdir_path, fname) store.create_file(name, fp, force=args.force, update=args.update) else: with open(args.source, 'rb') as fp: store.create_file(remote_path, fp, force=args.force, update=args.update)
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 (and all its sub-directories) use the `-r` command-line option. If your source directory name ends in a / then files will be created directly in the remote directory. If it does not end in a slash an extra sub-directory with the name of the local directory will be created. To place contents of local directory `foo` in remote directory `bar/foo`: $ osf upload -r foo bar To place contents of local directory `foo` in remote directory `bar`: $ osf upload -r foo/ bar """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys.exit('To upload a file you need to provide a username and' ' password.') project = osf.project(args.project) storage, remote_path = split_storage(args.destination) store = project.storage(storage) if args.recursive: if not os.path.isdir(args.source): raise RuntimeError("Expected source ({}) to be a directory when " "using recursive mode.".format(args.source)) # local name of the directory that is being uploaded _, dir_name = os.path.split(args.source) for root, _, files in os.walk(args.source): subdir_path = os.path.relpath(root, args.source) for fname in files: local_path = os.path.join(root, fname) with open(local_path, 'rb') as fp: # build the remote path + fname name = os.path.join(remote_path, dir_name, subdir_path, fname) store.create_file(name, fp, force=args.force, update=args.update) else: with open(args.source, 'rb') as fp: store.create_file(remote_path, fp, force=args.force, update=args.update)
[ "Upload", "a", "new", "file", "to", "an", "existing", "project", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L246-L297
[ "def", "upload", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "if", "osf", ".", "username", "is", "None", "or", "osf", ".", "password", "is", "None", ":", "sys", ".", "exit", "(", "'To upload a file you need to provide a username and'", "' password.'", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "storage", ",", "remote_path", "=", "split_storage", "(", "args", ".", "destination", ")", "store", "=", "project", ".", "storage", "(", "storage", ")", "if", "args", ".", "recursive", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "args", ".", "source", ")", ":", "raise", "RuntimeError", "(", "\"Expected source ({}) to be a directory when \"", "\"using recursive mode.\"", ".", "format", "(", "args", ".", "source", ")", ")", "# local name of the directory that is being uploaded", "_", ",", "dir_name", "=", "os", ".", "path", ".", "split", "(", "args", ".", "source", ")", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "args", ".", "source", ")", ":", "subdir_path", "=", "os", ".", "path", ".", "relpath", "(", "root", ",", "args", ".", "source", ")", "for", "fname", "in", "files", ":", "local_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", "with", "open", "(", "local_path", ",", "'rb'", ")", "as", "fp", ":", "# build the remote path + fname", "name", "=", "os", ".", "path", ".", "join", "(", "remote_path", ",", "dir_name", ",", "subdir_path", ",", "fname", ")", "store", ".", "create_file", "(", "name", ",", "fp", ",", "force", "=", "args", ".", "force", ",", "update", "=", "args", ".", "update", ")", "else", ":", "with", "open", "(", "args", ".", "source", ",", "'rb'", ")", "as", "fp", ":", "store", ".", "create_file", "(", "remote_path", ",", "fp", ",", "force", "=", "args", ".", "force", ",", "update", "=", "args", ".", "update", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
remove
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.
osfclient/cli.py
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.exit('To remove a file you need to provide a username and' ' password.') project = osf.project(args.project) storage, remote_path = split_storage(args.target) store = project.storage(storage) for f in store.files: if norm_remote_path(f.path) == remote_path: f.remove()
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.exit('To remove a file you need to provide a username and' ' password.') project = osf.project(args.project) storage, remote_path = split_storage(args.target) store = project.storage(storage) for f in store.files: if norm_remote_path(f.path) == remote_path: f.remove()
[ "Remove", "a", "file", "from", "the", "project", "s", "storage", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/cli.py#L301-L320
[ "def", "remove", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "if", "osf", ".", "username", "is", "None", "or", "osf", ".", "password", "is", "None", ":", "sys", ".", "exit", "(", "'To remove a file you need to provide a username and'", "' password.'", ")", "project", "=", "osf", ".", "project", "(", "args", ".", "project", ")", "storage", ",", "remote_path", "=", "split_storage", "(", "args", ".", "target", ")", "store", "=", "project", ".", "storage", "(", "storage", ")", "for", "f", "in", "store", ".", "files", ":", "if", "norm_remote_path", "(", "f", ".", "path", ")", "==", "remote_path", ":", "f", ".", "remove", "(", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
OSF.login
Login user for protected API calls.
osfclient/api.py
def login(self, username, password=None, token=None): """Login user for protected API calls.""" self.session.basic_auth(username, password)
def login(self, username, password=None, token=None): """Login user for protected API calls.""" self.session.basic_auth(username, password)
[ "Login", "user", "for", "protected", "API", "calls", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L18-L20
[ "def", "login", "(", "self", ",", "username", ",", "password", "=", "None", ",", "token", "=", "None", ")", ":", "self", ".", "session", ".", "basic_auth", "(", "username", ",", "password", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
OSF.project
Fetch project `project_id`.
osfclient/api.py
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 type {}. Clone supports projects and registrations'.format(project_id, type_))
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 type {}. Clone supports projects and registrations'.format(project_id, type_))
[ "Fetch", "project", "project_id", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L22-L28
[ "def", "project", "(", "self", ",", "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 type {}. Clone supports projects and registrations'", ".", "format", "(", "project_id", ",", "type_", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
OSF.guid
Determines JSONAPI type for provided GUID
osfclient/api.py
def guid(self, guid): """Determines JSONAPI type for provided GUID""" return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']
def guid(self, guid): """Determines JSONAPI type for provided GUID""" return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']
[ "Determines", "JSONAPI", "type", "for", "provided", "GUID" ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L30-L32
[ "def", "guid", "(", "self", ",", "guid", ")", ":", "return", "self", ".", "_json", "(", "self", ".", "_get", "(", "self", ".", "_build_url", "(", "'guids'", ",", "guid", ")", ")", ",", "200", ")", "[", "'data'", "]", "[", "'type'", "]" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
OSFCore._json
Extract JSON from response if `status_code` matches.
osfclient/models/core.py
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 RuntimeError("Response has status " "code {} not {}".format(response.status_code, status_code))
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 RuntimeError("Response has status " "code {} not {}".format(response.status_code, status_code))
[ "Extract", "JSON", "from", "response", "if", "status_code", "matches", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/core.py#L50-L60
[ "def", "_json", "(", "self", ",", "response", ",", "status_code", ")", ":", "if", "isinstance", "(", "status_code", ",", "numbers", ".", "Integral", ")", ":", "status_code", "=", "(", "status_code", ",", ")", "if", "response", ".", "status_code", "in", "status_code", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"Response has status \"", "\"code {} not {}\"", ".", "format", "(", "response", ".", "status_code", ",", "status_code", ")", ")" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
OSFCore._follow_next
Follow the 'next' link on paginated results.
osfclient/models/core.py
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(next_url), 200) data.extend(response['data']) next_url = self._get_attribute(response, 'links', 'next') return data
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(next_url), 200) data.extend(response['data']) next_url = self._get_attribute(response, 'links', 'next') return data
[ "Follow", "the", "next", "link", "on", "paginated", "results", "." ]
osfclient/osfclient
python
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/core.py#L62-L73
[ "def", "_follow_next", "(", "self", ",", "url", ")", ":", "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", "(", "next_url", ")", ",", "200", ")", "data", ".", "extend", "(", "response", "[", "'data'", "]", ")", "next_url", "=", "self", ".", "_get_attribute", "(", "response", ",", "'links'", ",", "'next'", ")", "return", "data" ]
44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf
valid
project
Make a new project, using recursion and alias resolution. Use this function in preference to calling Project() directly.
bibliopixel/project/project.py
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: project_path = os.path.dirname(root_file) if path: path += ':' + project_path else: path = project_path with load.extender(path): desc = recurse.recurse(desc) project = construct.construct(**desc) project.desc = desc return project
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: project_path = os.path.dirname(root_file) if path: path += ':' + project_path else: path = project_path with load.extender(path): desc = recurse.recurse(desc) project = construct.construct(**desc) project.desc = desc return project
[ "Make", "a", "new", "project", "using", "recursion", "and", "alias", "resolution", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/project.py#L168-L191
[ "def", "project", "(", "*", "descs", ",", "root_file", "=", "None", ")", ":", "load", ".", "ROOT_FILE", "=", "root_file", "desc", "=", "merge", ".", "merge", "(", "merge", ".", "DEFAULT_PROJECT", ",", "*", "descs", ")", "path", "=", "desc", ".", "get", "(", "'path'", ",", "''", ")", "if", "root_file", ":", "project_path", "=", "os", ".", "path", ".", "dirname", "(", "root_file", ")", "if", "path", ":", "path", "+=", "':'", "+", "project_path", "else", ":", "path", "=", "project_path", "with", "load", ".", "extender", "(", "path", ")", ":", "desc", "=", "recurse", ".", "recurse", "(", "desc", ")", "project", "=", "construct", ".", "construct", "(", "*", "*", "desc", ")", "project", ".", "desc", "=", "desc", "return", "project" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Description.clear
Clear description to default values
bibliopixel/builder/description.py
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 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)()
[ "Clear", "description", "to", "default", "values" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/description.py#L20-L25
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_desc", "=", "{", "}", "for", "key", ",", "value", "in", "merge", ".", "DEFAULT_PROJECT", ".", "items", "(", ")", ":", "if", "key", "not", "in", "self", ".", "_HIDDEN", ":", "self", ".", "_desc", "[", "key", "]", "=", "type", "(", "value", ")", "(", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Description.update
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 section to default" or "delete field".
bibliopixel/builder/description.py
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 section to default" or "delete field". """ sections.update(self._desc, desc, **kwds)
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 section to default" or "delete field". """ sections.update(self._desc, desc, **kwds)
[ "This", "method", "updates", "the", "description", "much", "like", "dict", ".", "update", "()", "*", "except", "*", ":" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/description.py#L31-L40
[ "def", "update", "(", "self", ",", "desc", "=", "None", ",", "*", "*", "kwds", ")", ":", "sections", ".", "update", "(", "self", ".", "_desc", ",", "desc", ",", "*", "*", "kwds", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
SPI
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:class:`bibliopixel.drivers.SPI.SPIBase` as well as those below: :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102
bibliopixel/drivers/SPI/driver.py
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:class:`bibliopixel.drivers.SPI.SPIBase` as well as those below: :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102 """ from ...project.types.ledtype import make if ledtype is None: raise ValueError('Must provide ledtype value!') ledtype = make(ledtype) if num == 0: raise ValueError('Must provide num value >0!') if ledtype not in SPI_DRIVERS.keys(): raise ValueError('{} is not a valid LED type.'.format(ledtype)) return SPI_DRIVERS[ledtype](num, **kwargs)
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:class:`bibliopixel.drivers.SPI.SPIBase` as well as those below: :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102 """ from ...project.types.ledtype import make if ledtype is None: raise ValueError('Must provide ledtype value!') ledtype = make(ledtype) if num == 0: raise ValueError('Must provide num value >0!') if ledtype not in SPI_DRIVERS.keys(): raise ValueError('{} is not a valid LED type.'.format(ledtype)) return SPI_DRIVERS[ledtype](num, **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", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/SPI/driver.py#L23-L46
[ "def", "SPI", "(", "ledtype", "=", "None", ",", "num", "=", "0", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", ".", "project", ".", "types", ".", "ledtype", "import", "make", "if", "ledtype", "is", "None", ":", "raise", "ValueError", "(", "'Must provide ledtype value!'", ")", "ledtype", "=", "make", "(", "ledtype", ")", "if", "num", "==", "0", ":", "raise", "ValueError", "(", "'Must provide num value >0!'", ")", "if", "ledtype", "not", "in", "SPI_DRIVERS", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "'{} is not a valid LED type.'", ".", "format", "(", "ledtype", ")", ")", "return", "SPI_DRIVERS", "[", "ledtype", "]", "(", "num", ",", "*", "*", "kwargs", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
EditQueue.put_edit
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 full
bibliopixel/project/edit_queue.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 full """ self.put_nowait(functools.partial(f, *args, **kwds))
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 full """ self.put_nowait(functools.partial(f, *args, **kwds))
[ "Defer", "an", "edit", "to", "run", "on", "the", "EditQueue", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/edit_queue.py#L15-L24
[ "def", "put_edit", "(", "self", ",", "f", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "self", ".", "put_nowait", "(", "functools", ".", "partial", "(", "f", ",", "*", "args", ",", "*", "*", "kwds", ")", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
EditQueue.get_and_run_edits
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 end of ``run_edits``, because new edits might have entered the queue while the previous edits are being executed. This has the advantage that if edits enter the queue faster than they can be processed, ``get_and_run_edits`` won't go into an infinite loop, but rather the queue will grow unboundedly, which that can be detected, and mitigated and reported on - or if Queue.maxsize is set, ``bp`` will report a fairly clear error and just dump the edits on the ground.
bibliopixel/project/edit_queue.py
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 end of ``run_edits``, because new edits might have entered the queue while the previous edits are being executed. This has the advantage that if edits enter the queue faster than they can be processed, ``get_and_run_edits`` won't go into an infinite loop, but rather the queue will grow unboundedly, which that can be detected, and mitigated and reported on - or if Queue.maxsize is set, ``bp`` will report a fairly clear error and just dump the edits on the ground. """ if self.empty(): return edits = [] while True: try: edits.append(self.get_nowait()) except queue.Empty: break for e in edits: try: e() except: log.error('Error on edit %s', e) traceback.print_exc()
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 end of ``run_edits``, because new edits might have entered the queue while the previous edits are being executed. This has the advantage that if edits enter the queue faster than they can be processed, ``get_and_run_edits`` won't go into an infinite loop, but rather the queue will grow unboundedly, which that can be detected, and mitigated and reported on - or if Queue.maxsize is set, ``bp`` will report a fairly clear error and just dump the edits on the ground. """ if self.empty(): return edits = [] while True: try: edits.append(self.get_nowait()) except queue.Empty: break for e in edits: try: e() except: log.error('Error on edit %s', e) traceback.print_exc()
[ "Get", "all", "the", "edits", "in", "the", "queue", "then", "execute", "them", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/edit_queue.py#L26-L58
[ "def", "get_and_run_edits", "(", "self", ")", ":", "if", "self", ".", "empty", "(", ")", ":", "return", "edits", "=", "[", "]", "while", "True", ":", "try", ":", "edits", ".", "append", "(", "self", ".", "get_nowait", "(", ")", ")", "except", "queue", ".", "Empty", ":", "break", "for", "e", "in", "edits", ":", "try", ":", "e", "(", ")", "except", ":", "log", ".", "error", "(", "'Error on edit %s'", ",", "e", ")", "traceback", ".", "print_exc", "(", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
SpiBaseInterface.error
SHOULD BE PRIVATE
bibliopixel/drivers/SPI/interfaces.py
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 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)
[ "SHOULD", "BE", "PRIVATE" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/SPI/interfaces.py#L23-L28
[ "def", "error", "(", "self", ",", "text", ")", ":", "msg", "=", "'Error with dev: {}, spi_speed: {} - {}'", ".", "format", "(", "self", ".", "_dev", ",", "self", ".", "_spi_speed", ",", "text", ")", "log", ".", "error", "(", "msg", ")", "raise", "IOError", "(", "msg", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
SpiFileInterface.send_packet
SHOULD BE PRIVATE
bibliopixel/drivers/SPI/interfaces.py
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]) self._spi.flush()
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]) self._spi.flush()
[ "SHOULD", "BE", "PRIVATE" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/SPI/interfaces.py#L43-L50
[ "def", "send_packet", "(", "self", ",", "data", ")", ":", "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", "]", ")", "self", ".", "_spi", ".", "flush", "(", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
DevicesImpl.find_serial_devices
Scan and report all compatible serial devices on system. :returns: List of discovered devices
bibliopixel/drivers/serial/devices.py
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 insensitive for ports in serial.tools.list_ports.grep(hardware_id): port = ports[0] try: id = self.get_device_id(port) ver = self._get_device_version(port) except: log.debug('Error getting device_id for %s, %s', port, self.baudrate) if True: raise continue if getattr(ports, '__len__', lambda: 0)(): log.debug('Multi-port device %s:%s:%s with %s ports found', self.hardware_id, id, ver, len(ports)) if id < 0: log.debug('Serial device %s:%s:%s with id %s < 0', self.hardware_id, id, ver) else: self.devices[id] = port, ver return self.devices
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 insensitive for ports in serial.tools.list_ports.grep(hardware_id): port = ports[0] try: id = self.get_device_id(port) ver = self._get_device_version(port) except: log.debug('Error getting device_id for %s, %s', port, self.baudrate) if True: raise continue if getattr(ports, '__len__', lambda: 0)(): log.debug('Multi-port device %s:%s:%s with %s ports found', self.hardware_id, id, ver, len(ports)) if id < 0: log.debug('Serial device %s:%s:%s with id %s < 0', self.hardware_id, id, ver) else: self.devices[id] = port, ver return self.devices
[ "Scan", "and", "report", "all", "compatible", "serial", "devices", "on", "system", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L37-L69
[ "def", "find_serial_devices", "(", "self", ")", ":", "if", "self", ".", "devices", "is", "not", "None", ":", "return", "self", ".", "devices", "self", ".", "devices", "=", "{", "}", "hardware_id", "=", "\"(?i)\"", "+", "self", ".", "hardware_id", "# forces case insensitive", "for", "ports", "in", "serial", ".", "tools", ".", "list_ports", ".", "grep", "(", "hardware_id", ")", ":", "port", "=", "ports", "[", "0", "]", "try", ":", "id", "=", "self", ".", "get_device_id", "(", "port", ")", "ver", "=", "self", ".", "_get_device_version", "(", "port", ")", "except", ":", "log", ".", "debug", "(", "'Error getting device_id for %s, %s'", ",", "port", ",", "self", ".", "baudrate", ")", "if", "True", ":", "raise", "continue", "if", "getattr", "(", "ports", ",", "'__len__'", ",", "lambda", ":", "0", ")", "(", ")", ":", "log", ".", "debug", "(", "'Multi-port device %s:%s:%s with %s ports found'", ",", "self", ".", "hardware_id", ",", "id", ",", "ver", ",", "len", "(", "ports", ")", ")", "if", "id", "<", "0", ":", "log", ".", "debug", "(", "'Serial device %s:%s:%s with id %s < 0'", ",", "self", ".", "hardware_id", ",", "id", ",", "ver", ")", "else", ":", "self", ".", "devices", "[", "id", "]", "=", "port", ",", "ver", "return", "self", ".", "devices" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
DevicesImpl.get_device
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
bibliopixel/drivers/serial/devices.py
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: if not self.devices: raise ValueError('No default device for %s' % self.hardware_id) id, (device, version) = sorted(self.devices.items())[0] elif id in self.devices: device, version = self.devices[id] else: error = 'Unable to find device with ID %s' % id log.error(error) raise ValueError(error) log.info("Using COM Port: %s, Device ID: %s, Device Ver: %s", device, id, version) return id, device, version
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: if not self.devices: raise ValueError('No default device for %s' % self.hardware_id) id, (device, version) = sorted(self.devices.items())[0] elif id in self.devices: device, version = self.devices[id] else: error = 'Unable to find device with ID %s' % id log.error(error) raise ValueError(error) log.info("Using COM Port: %s, Device ID: %s, Device Ver: %s", device, id, version) return id, device, version
[ "Returns", "details", "of", "either", "the", "first", "or", "specified", "device" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L71-L94
[ "def", "get_device", "(", "self", ",", "id", "=", "None", ")", ":", "if", "id", "is", "None", ":", "if", "not", "self", ".", "devices", ":", "raise", "ValueError", "(", "'No default device for %s'", "%", "self", ".", "hardware_id", ")", "id", ",", "(", "device", ",", "version", ")", "=", "sorted", "(", "self", ".", "devices", ".", "items", "(", ")", ")", "[", "0", "]", "elif", "id", "in", "self", ".", "devices", ":", "device", ",", "version", "=", "self", ".", "devices", "[", "id", "]", "else", ":", "error", "=", "'Unable to find device with ID %s'", "%", "id", "log", ".", "error", "(", "error", ")", "raise", "ValueError", "(", "error", ")", "log", ".", "info", "(", "\"Using COM Port: %s, Device ID: %s, Device Ver: %s\"", ",", "device", ",", "id", ",", "version", ")", "return", "id", ",", "device", ",", "version" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
DevicesImpl.error
SHOULD BE PRIVATE METHOD
bibliopixel/drivers/serial/devices.py
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 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)
[ "SHOULD", "BE", "PRIVATE", "METHOD" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L96-L105
[ "def", "error", "(", "self", ",", "fail", "=", "True", ",", "action", "=", "''", ")", ":", "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", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
DevicesImpl.set_device_id
Set device ID to new value. :param str dev: Serial device address/path :param id: Device ID to set
bibliopixel/drivers/serial/devices.py
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( CMDTYPE.SETID, 1, dev, self.baudrate, 5, id) if not ok: raise_error(code)
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( CMDTYPE.SETID, 1, dev, self.baudrate, 5, id) if not ok: raise_error(code)
[ "Set", "device", "ID", "to", "new", "value", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L107-L118
[ "def", "set_device_id", "(", "self", ",", "dev", ",", "id", ")", ":", "if", "id", "<", "0", "or", "id", ">", "255", ":", "raise", "ValueError", "(", "\"ID must be an unsigned byte!\"", ")", "com", ",", "code", ",", "ok", "=", "io", ".", "send_packet", "(", "CMDTYPE", ".", "SETID", ",", "1", ",", "dev", ",", "self", ".", "baudrate", ",", "5", ",", "id", ")", "if", "not", "ok", ":", "raise_error", "(", "code", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
DevicesImpl.get_device_id
Get device ID at given address/path. :param str dev: Serial device address/path :param baudrate: Baudrate to use when connecting (optional)
bibliopixel/drivers/serial/devices.py
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: self.error(action='get_device_id') return code
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: self.error(action='get_device_id') return code
[ "Get", "device", "ID", "at", "given", "address", "/", "path", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/serial/devices.py#L120-L129
[ "def", "get_device_id", "(", "self", ",", "dev", ")", ":", "com", ",", "code", ",", "ok", "=", "io", ".", "send_packet", "(", "CMDTYPE", ".", "GETID", ",", "0", ",", "dev", ",", "self", ".", "baudrate", ",", "5", ")", "if", "code", "is", "None", ":", "self", ".", "error", "(", "action", "=", "'get_device_id'", ")", "return", "code" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
get
Return a named Palette, or None if no such name exists. If ``name`` is omitted, the default value is used.
bibliopixel/colors/palettes.py
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.get(name)
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.get(name)
[ "Return", "a", "named", "Palette", "or", "None", "if", "no", "such", "name", "exists", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/palettes.py#L17-L27
[ "def", "get", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", "or", "name", "==", "'default'", ":", "return", "_DEFAULT_PALETTE", "if", "isinstance", "(", "name", ",", "str", ")", ":", "return", "PROJECT_PALETTES", ".", "get", "(", "name", ")", "or", "BUILT_IN_PALETTES", ".", "get", "(", "name", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
crop
Return an image cropped on top, bottom, left or right.
bibliopixel/util/image/reshape.py
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_offset, height - bottom_offset) image = image.crop(box=box) return image
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_offset, height - bottom_offset) image = image.crop(box=box) return image
[ "Return", "an", "image", "cropped", "on", "top", "bottom", "left", "or", "right", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/reshape.py#L4-L12
[ "def", "crop", "(", "image", ",", "top_offset", "=", "0", ",", "left_offset", "=", "0", ",", "bottom_offset", "=", "0", ",", "right_offset", "=", "0", ")", ":", "if", "bottom_offset", "or", "top_offset", "or", "left_offset", "or", "right_offset", ":", "width", ",", "height", "=", "image", ".", "size", "box", "=", "(", "left_offset", ",", "top_offset", ",", "width", "-", "right_offset", ",", "height", "-", "bottom_offset", ")", "image", "=", "image", ".", "crop", "(", "box", "=", "box", ")", "return", "image" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
resize
Return an image resized.
bibliopixel/util/image/reshape.py
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 = Image.ANTIALIAS if resample is None else resample if not isinstance(resample, numbers.Number): try: resample = getattr(Image, resample.upper()) except: raise ValueError("(1) Didn't understand resample=%s" % resample) if not isinstance(resample, numbers.Number): raise ValueError("(2) Didn't understand resample=%s" % resample) size = x, y if stretch: return image.resize(size, resample=resample) result = Image.new(mode, size) ratios = [d1 / d2 for d1, d2 in zip(size, image.size)] if ratios[0] < ratios[1]: new_size = (size[0], int(image.size[1] * ratios[0])) else: new_size = (int(image.size[0] * ratios[1]), size[1]) image = image.resize(new_size, resample=resample) if left is None: box_x = int((x - new_size[0]) / 2) elif left: box_x = 0 else: box_x = x - new_size[0] if top is None: box_y = int((y - new_size[1]) / 2) elif top: box_y = 0 else: box_y = y - new_size[1] result.paste(image, box=(box_x, box_y)) return result
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 = Image.ANTIALIAS if resample is None else resample if not isinstance(resample, numbers.Number): try: resample = getattr(Image, resample.upper()) except: raise ValueError("(1) Didn't understand resample=%s" % resample) if not isinstance(resample, numbers.Number): raise ValueError("(2) Didn't understand resample=%s" % resample) size = x, y if stretch: return image.resize(size, resample=resample) result = Image.new(mode, size) ratios = [d1 / d2 for d1, d2 in zip(size, image.size)] if ratios[0] < ratios[1]: new_size = (size[0], int(image.size[1] * ratios[0])) else: new_size = (int(image.size[0] * ratios[1]), size[1]) image = image.resize(new_size, resample=resample) if left is None: box_x = int((x - new_size[0]) / 2) elif left: box_x = 0 else: box_x = x - new_size[0] if top is None: box_y = int((y - new_size[1]) / 2) elif top: box_y = 0 else: box_y = y - new_size[1] result.paste(image, box=(box_x, box_y)) return result
[ "Return", "an", "image", "resized", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/reshape.py#L15-L61
[ "def", "resize", "(", "image", ",", "x", ",", "y", ",", "stretch", "=", "False", ",", "top", "=", "None", ",", "left", "=", "None", ",", "mode", "=", "'RGB'", ",", "resample", "=", "None", ")", ":", "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", "=", "Image", ".", "ANTIALIAS", "if", "resample", "is", "None", "else", "resample", "if", "not", "isinstance", "(", "resample", ",", "numbers", ".", "Number", ")", ":", "try", ":", "resample", "=", "getattr", "(", "Image", ",", "resample", ".", "upper", "(", ")", ")", "except", ":", "raise", "ValueError", "(", "\"(1) Didn't understand resample=%s\"", "%", "resample", ")", "if", "not", "isinstance", "(", "resample", ",", "numbers", ".", "Number", ")", ":", "raise", "ValueError", "(", "\"(2) Didn't understand resample=%s\"", "%", "resample", ")", "size", "=", "x", ",", "y", "if", "stretch", ":", "return", "image", ".", "resize", "(", "size", ",", "resample", "=", "resample", ")", "result", "=", "Image", ".", "new", "(", "mode", ",", "size", ")", "ratios", "=", "[", "d1", "/", "d2", "for", "d1", ",", "d2", "in", "zip", "(", "size", ",", "image", ".", "size", ")", "]", "if", "ratios", "[", "0", "]", "<", "ratios", "[", "1", "]", ":", "new_size", "=", "(", "size", "[", "0", "]", ",", "int", "(", "image", ".", "size", "[", "1", "]", "*", "ratios", "[", "0", "]", ")", ")", "else", ":", "new_size", "=", "(", "int", "(", "image", ".", "size", "[", "0", "]", "*", "ratios", "[", "1", "]", ")", ",", "size", "[", "1", "]", ")", "image", "=", "image", ".", "resize", "(", "new_size", ",", "resample", "=", "resample", ")", "if", "left", "is", "None", ":", "box_x", "=", "int", "(", "(", "x", "-", "new_size", "[", "0", "]", ")", "/", "2", ")", "elif", "left", ":", "box_x", "=", "0", "else", ":", "box_x", "=", "x", "-", "new_size", "[", "0", "]", "if", "top", "is", "None", ":", "box_y", "=", "int", "(", "(", "y", "-", "new_size", "[", "1", "]", ")", "/", "2", ")", "elif", "top", ":", "box_y", "=", "0", "else", ":", "box_y", "=", "y", "-", "new_size", "[", "1", "]", "result", ".", "paste", "(", "image", ",", "box", "=", "(", "box_x", ",", "box_y", ")", ")", "return", "result" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Extractor.extract
Yield an ordered dictionary if msg['type'] is in keys_by_type.
bibliopixel/control/extractor.py
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 odict(keys): return collections.OrderedDict((k, normal(k)) for k in keys) def match(m): return (msg.get(k) in v for k, v in m.items()) if m else () accept = all(match(self.accept)) reject = any(match(self.reject)) if reject or not accept: keys = () elif self.keys_by_type is None: keys = [k for k in msg.keys() if k not in self.omit] else: keys = self.keys_by_type.get(msg.get('type')) return odict(keys)
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 odict(keys): return collections.OrderedDict((k, normal(k)) for k in keys) def match(m): return (msg.get(k) in v for k, v in m.items()) if m else () accept = all(match(self.accept)) reject = any(match(self.reject)) if reject or not accept: keys = () elif self.keys_by_type is None: keys = [k for k in msg.keys() if k not in self.omit] else: keys = self.keys_by_type.get(msg.get('type')) return odict(keys)
[ "Yield", "an", "ordered", "dictionary", "if", "msg", "[", "type", "]", "is", "in", "keys_by_type", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/control/extractor.py#L66-L90
[ "def", "extract", "(", "self", ",", "msg", ")", ":", "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", "odict", "(", "keys", ")", ":", "return", "collections", ".", "OrderedDict", "(", "(", "k", ",", "normal", "(", "k", ")", ")", "for", "k", "in", "keys", ")", "def", "match", "(", "m", ")", ":", "return", "(", "msg", ".", "get", "(", "k", ")", "in", "v", "for", "k", ",", "v", "in", "m", ".", "items", "(", ")", ")", "if", "m", "else", "(", ")", "accept", "=", "all", "(", "match", "(", "self", ".", "accept", ")", ")", "reject", "=", "any", "(", "match", "(", "self", ".", "reject", ")", ")", "if", "reject", "or", "not", "accept", ":", "keys", "=", "(", ")", "elif", "self", ".", "keys_by_type", "is", "None", ":", "keys", "=", "[", "k", "for", "k", "in", "msg", ".", "keys", "(", ")", "if", "k", "not", "in", "self", ".", "omit", "]", "else", ":", "keys", "=", "self", ".", "keys_by_type", ".", "get", "(", "msg", ".", "get", "(", "'type'", ")", ")", "return", "odict", "(", "keys", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Matrix.get
Return the pixel color at position (x, y), or Colors.black if that position is out-of-bounds.
bibliopixel/layout/matrix.py
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 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
[ "Return", "the", "pixel", "color", "at", "position", "(", "x", "y", ")", "or", "Colors", ".", "black", "if", "that", "position", "is", "out", "-", "of", "-", "bounds", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L128-L137
[ "def", "get", "(", "self", ",", "x", ",", "y", ")", ":", "try", ":", "pixel", "=", "self", ".", "coord_map", "[", "y", "]", "[", "x", "]", "return", "self", ".", "_get_base", "(", "pixel", ")", "except", "IndexError", ":", "return", "colors", ".", "COLORS", ".", "Black" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Matrix.drawCircle
Draw a circle in an RGB color, with center x0, y0 and radius r.
bibliopixel/layout/matrix.py
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 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)
[ "Draw", "a", "circle", "in", "an", "RGB", "color", "with", "center", "x0", "y0", "and", "radius", "r", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L222-L226
[ "def", "drawCircle", "(", "self", ",", "x0", ",", "y0", ",", "r", ",", "color", "=", "None", ")", ":", "md", ".", "draw_circle", "(", "self", ".", "set", ",", "x0", ",", "y0", ",", "r", ",", "color", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Matrix.fillCircle
Draw a filled circle in an RGB color, with center x0, y0 and radius r.
bibliopixel/layout/matrix.py
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)
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)
[ "Draw", "a", "filled", "circle", "in", "an", "RGB", "color", "with", "center", "x0", "y0", "and", "radius", "r", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix.py#L228-L232
[ "def", "fillCircle", "(", "self", ",", "x0", ",", "y0", ",", "r", ",", "color", "=", "None", ")", ":", "md", ".", "fill_circle", "(", "self", ".", "set", ",", "x0", ",", "y0", ",", "r", ",", "color", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c