_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q256200
AccessControlList.deny
validation
def deny(self, role, method, resource, with_children=False): """Add denying rules. :param role: Role of this rule. :param method: Method to deny in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Deny role's children in rule as well if with_children is `True` """ if with_children: for r in role.get_children():
python
{ "resource": "" }
q256201
AccessControlList.exempt
validation
def exempt(self, resource): """Exempt a view function from being checked permission :param resource: The view function exempt from checking. """
python
{ "resource": "" }
q256202
AccessControlList.is_allowed
validation
def is_allowed(self, role, method, resource): """Check whether role is allowed to access resource :param role: Role to be checked. :param method: Method to be checked.
python
{ "resource": "" }
q256203
AccessControlList.is_denied
validation
def is_denied(self, role, method, resource): """Check wherther role is denied to access resource :param role: Role to be checked. :param method: Method to be checked.
python
{ "resource": "" }
q256204
RBAC.allow
validation
def allow(self, roles, methods, with_children=True): """This is a decorator function. You can allow roles to access the view func with it. An example:: @app.route('/website/setting', methods=['GET', 'POST']) @rbac.allow(['administrator', 'super_user'], ['GET', 'POST']) def website_setting(): return Response('Setting page.') :param roles: List, each name of roles. Please note that, `anonymous` is refered to anonymous. If you add `anonymous` to the rule, everyone can access the resource, unless you deny other roles. :param methods: List, each name of methods. methods is valid in ['GET', 'POST', 'PUT', 'DELETE'] :param with_children: Whether allow
python
{ "resource": "" }
q256205
remove_binaries
validation
def remove_binaries(): """Remove all binary files in the adslib directory.""" patterns = ( "adslib/*.a", "adslib/*.o", "adslib/obj/*.o", "adslib/*.bin", "adslib/*.so", )
python
{ "resource": "" }
q256206
router_function
validation
def router_function(fn): # type: (Callable) -> Callable """Raise a runtime error if on Win32 systems. Decorator. Decorator for functions that interact with the router for the Linux implementation of the ADS library. Unlike the Windows implementation which uses a separate router daemon, the Linux library manages AMS routing in-process. As such, routing must be configured programatically via. the provided API. These endpoints are invalid on Win32 systems, so an exception will be raised. """ @wraps(fn) def wrapper(*args, **kwargs): # type: (Any, Any) -> Callable if platform_is_windows():
python
{ "resource": "" }
q256207
adsAddRoute
validation
def adsAddRoute(net_id, ip_address): # type: (SAmsNetId, str) -> None """Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint """ add_route = _adsDLL.AdsAddRoute add_route.restype = ctypes.c_long # Convert ip address to bytes (PY3)
python
{ "resource": "" }
q256208
adsPortCloseEx
validation
def adsPortCloseEx(port): # type: (int) -> None """Close the connection to the TwinCAT message router."""
python
{ "resource": "" }
q256209
adsGetLocalAddressEx
validation
def adsGetLocalAddressEx(port): # type: (int) -> AmsAddr """Return the local AMS-address and the port number. :rtype: pyads.structs.AmsAddr :return: AMS-address """ get_local_address_ex = _adsDLL.AdsGetLocalAddressEx ams_address_struct = SAmsAddr() error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))
python
{ "resource": "" }
q256210
adsSyncReadStateReqEx
validation
def adsSyncReadStateReqEx(port, address): # type: (int, AmsAddr) -> Tuple[int, int] """Read the current ADS-state and the machine-state. Read the current ADS-state and the machine-state from the ADS-server. :param pyads.structs.AmsAddr address: local or remote AmsAddr :rtype: (int, int) :return: ads_state, device_state """ sync_read_state_request = _adsDLL.AdsSyncReadStateReqEx # C pointer to ams address struct ams_address_pointer = ctypes.pointer(address.amsAddrStruct()) # Current ADS status and corresponding pointer ads_state
python
{ "resource": "" }
q256211
adsSyncReadDeviceInfoReqEx
validation
def adsSyncReadDeviceInfoReqEx(port, address): # type: (int, AmsAddr) -> Tuple[str, AdsVersion] """Read the name and the version number of the ADS-server. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :rtype: string, AdsVersion :return: device name, version """ sync_read_device_info_request = _adsDLL.AdsSyncReadDeviceInfoReqEx # Get pointer to the target AMS address ams_address_pointer = ctypes.pointer(address.amsAddrStruct()) # Create buffer to be filled with device name, get pointer to said buffer device_name_buffer
python
{ "resource": "" }
q256212
adsSyncWriteControlReqEx
validation
def adsSyncWriteControlReqEx( port, address, ads_state, device_state, data, plc_data_type ): # type: (int, AmsAddr, int, int, Any, Type) -> None """Change the ADS state and the machine-state of the ADS-server. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr adr: local or remote AmsAddr :param int ads_state: new ADS-state, according to ADSTATE constants :param int device_state: new machine-state :param data: additional data :param int plc_data_type: plc datatype, according to PLCTYPE constants """ sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx ams_address_pointer = ctypes.pointer(address.amsAddrStruct()) ads_state_c = ctypes.c_ulong(ads_state) device_state_c = ctypes.c_ulong(device_state) if plc_data_type == PLCTYPE_STRING: data = ctypes.c_char_p(data.encode("utf-8")) data_pointer = data
python
{ "resource": "" }
q256213
adsSyncWriteReqEx
validation
def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type): # type: (int, AmsAddr, int, int, Any, Type) -> None """Send data synchronous to an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param int indexGroup: PLC storage area, according to the INDEXGROUP constants :param int index_offset: PLC storage address :param value: value to write to the storage address of the PLC :param int plc_data_type: type of the data given to the PLC, according to PLCTYPE constants """ sync_write_request = _adsDLL.AdsSyncWriteReqEx ams_address_pointer = ctypes.pointer(address.amsAddrStruct()) index_group_c = ctypes.c_ulong(index_group) index_offset_c = ctypes.c_ulong(index_offset) if plc_data_type == PLCTYPE_STRING: data = ctypes.c_char_p(value.encode("utf-8")) data_pointer = data # type: Union[ctypes.c_char_p, ctypes.pointer]
python
{ "resource": "" }
q256214
adsSyncReadReqEx2
validation
def adsSyncReadReqEx2( port, address, index_group, index_offset, data_type, return_ctypes=False ): # type: (int, AmsAddr, int, int, Type, bool) -> Any """Read data synchronous from an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param int index_group: PLC storage area, according to the INDEXGROUP constants :param int index_offset: PLC storage address :param Type data_type: type of the data given to the PLC, according to PLCTYPE constants :param bool return_ctypes: return ctypes instead of python types if True (default: False) :rtype: data_type :return: value: **value** """ sync_read_request = _adsDLL.AdsSyncReadReqEx2 ams_address_pointer = ctypes.pointer(address.amsAddrStruct()) index_group_c = ctypes.c_ulong(index_group) index_offset_c = ctypes.c_ulong(index_offset) if data_type == PLCTYPE_STRING: data = (STRING_BUFFER * PLCTYPE_STRING)() else: data = data_type() data_pointer = ctypes.pointer(data) data_length = ctypes.c_ulong(ctypes.sizeof(data)) bytes_read = ctypes.c_ulong() bytes_read_pointer = ctypes.pointer(bytes_read) error_code = sync_read_request( port, ams_address_pointer, index_group_c, index_offset_c, data_length, data_pointer,
python
{ "resource": "" }
q256215
adsSyncReadByNameEx
validation
def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False): # type: (int, AmsAddr, str, Type, bool) -> Any """Read data synchronous from an ADS-device from data name. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param string data_name: data name :param Type data_type: type of the data given to the PLC, according to PLCTYPE constants :param bool return_ctypes: return ctypes instead of python types if True (default: False) :rtype: data_type :return: value: **value** """ # Get the handle of the PLC-variable handle = adsSyncReadWriteReqEx2( port,
python
{ "resource": "" }
q256216
adsSyncWriteByNameEx
validation
def adsSyncWriteByNameEx(port, address, data_name, value, data_type): # type: (int, AmsAddr, str, Any, Type) -> None """Send data synchronous to an ADS-device from data name. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param string data_name: PLC storage address :param value: value to write to the storage address of the PLC :param Type data_type: type of the data given to the PLC, according to PLCTYPE constants """ # Get the handle of the PLC-variable handle = adsSyncReadWriteReqEx2( port, address,
python
{ "resource": "" }
q256217
adsSyncAddDeviceNotificationReqEx
validation
def adsSyncAddDeviceNotificationReqEx( port, adr, data_name, pNoteAttrib, callback, user_handle=None ): # type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int] """Add a device notification. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr adr: local or remote AmsAddr :param string data_name: PLC storage address :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes :param callback: Callback function to handle notification :param user_handle: User Handle :rtype: (int, int) :returns: notification handle, user handle """ global callback_store if NOTEFUNC is None: raise TypeError("Callback function type can't be None") adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx pAmsAddr = ctypes.pointer(adr.amsAddrStruct()) hnl = adsSyncReadWriteReqEx2( port, adr, ADSIGRP_SYM_HNDBYNAME, 0x0, PLCTYPE_UDINT, data_name, PLCTYPE_STRING ) nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND) nIndexOffset = ctypes.c_ulong(hnl) attrib = pNoteAttrib.notificationAttribStruct() pNotification = ctypes.c_ulong() nHUser = ctypes.c_ulong(hnl) if user_handle is not None: nHUser = ctypes.c_ulong(user_handle) adsSyncAddDeviceNotificationReqFct.argtypes = [ ctypes.c_ulong, ctypes.POINTER(SAmsAddr), ctypes.c_ulong, ctypes.c_ulong, ctypes.POINTER(SAdsNotificationAttrib), NOTEFUNC,
python
{ "resource": "" }
q256218
adsSyncDelDeviceNotificationReqEx
validation
def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle): # type: (int, AmsAddr, int, int) -> None """Remove a device notification. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr adr: local or remote AmsAddr :param int notification_handle: Notification Handle :param int user_handle: User Handle """ adsSyncDelDeviceNotificationReqFct = _adsDLL.AdsSyncDelDeviceNotificationReqEx pAmsAddr = ctypes.pointer(adr.amsAddrStruct()) nHNotification =
python
{ "resource": "" }
q256219
adsSyncSetTimeoutEx
validation
def adsSyncSetTimeoutEx(port, nMs): # type: (int, int) -> None """Set Timeout. :param int port: local AMS port as returned by adsPortOpenEx() :param int nMs: timeout in ms """
python
{ "resource": "" }
q256220
OfficialMissionsDataset._generate_ranges
validation
def _generate_ranges(start_date, end_date): """ Generate a list of 2 month ranges for the range requested with an intersection between months. This is necessary because we can't search for ranges longer than 3 months and the period searched has to encompass
python
{ "resource": "" }
q256221
DeputiesDataset.fetch
validation
def fetch(self): """ Fetches the list of deputies for the current term. """ xml = urllib.request.urlopen(self.URL) tree = ET.ElementTree(file=xml) records = self._parse_deputies(tree.getroot()) df = pd.DataFrame(records, columns=( 'congressperson_id', 'budget_id', 'condition', 'congressperson_document', 'civil_name',
python
{ "resource": "" }
q256222
HashRing.remove_node
validation
def remove_node(self, node): """Removes `node` from the hash ring and its replicas. """ self.nodes.remove(node) for x in xrange(self.replicas):
python
{ "resource": "" }
q256223
RedisShardAPI.mget
validation
def mget(self, keys, *args): """ Returns a list of values ordered identically to ``keys`` """ args = list_or_args(keys, args) server_keys = {} ret_dict = {} for key in args: server_name = self.get_server_name(key) server_keys[server_name] = server_keys.get(server_name, []) server_keys[server_name].append(key)
python
{ "resource": "" }
q256224
RedisShardAPI.lock
validation
def lock(self, name, timeout=None, sleep=0.1): """ Return a new Lock object using key ``name`` that mimics the behavior of threading.Lock. If specified, ``timeout`` indicates a maximum life for the lock. By default, it will remain locked until release() is called. ``sleep`` indicates the amount of time
python
{ "resource": "" }
q256225
parse_line
validation
def parse_line(line, document=None): ''' Return a language-server diagnostic from a line of the Mypy error report; optionally, use the whole document to provide more context on it. ''' result = re.match(line_pattern, line) if result: _, lineno, offset, severity, msg = result.groups() lineno = int(lineno or 1) offset = int(offset or 0) errno = 2 if severity == 'error': errno = 1 diag = { 'source': 'mypy', 'range': { 'start': {'line': lineno - 1, 'character': offset}, # There may be a better solution, but mypy does not provide end 'end': {'line': lineno - 1, 'character': offset + 1} }, 'message': msg, 'severity': errno }
python
{ "resource": "" }
q256226
WebSocket.connect
validation
async def connect(self): """ Establishes a connection to the Lavalink server. """ await self._lavalink.bot.wait_until_ready() if self._ws and self._ws.open: log.debug('WebSocket still open, closing...') await self._ws.close() user_id = self._lavalink.bot.user.id shard_count = self._lavalink.bot.shard_count or self._shards headers = { 'Authorization': self._password, 'Num-Shards': shard_count, 'User-Id': str(user_id) } log.debug('Preparing to connect to Lavalink') log.debug(' with URI: {}'.format(self._uri))
python
{ "resource": "" }
q256227
WebSocket.listen
validation
async def listen(self): """ Waits to receive a payload from the Lavalink server and processes it. """ while not self._shutdown: try: data = json.loads(await self._ws.recv()) except websockets.ConnectionClosed as error: log.warning('Disconnected from Lavalink: {}'.format(str(error))) for g in self._lavalink.players._players.copy().keys(): ws = self._lavalink.bot._connection._get_websocket(int(g)) await ws.voice_state(int(g), None) self._lavalink.players.clear() if self._shutdown: break if await self._attempt_reconnect(): return log.warning('Unable to reconnect to Lavalink!') break op = data.get('op', None) log.debug('Received WebSocket data {}'.format(str(data))) if not op: return log.debug('Received WebSocket message without op {}'.format(str(data))) if op == 'event': log.debug('Received event of type {}'.format(data['type'])) player = self._lavalink.players[int(data['guildId'])] event = None
python
{ "resource": "" }
q256228
DefaultPlayer.connected_channel
validation
def connected_channel(self): """ Returns the voice channel the player is connected to. """ if not self.channel_id:
python
{ "resource": "" }
q256229
DefaultPlayer.connect
validation
async def connect(self, channel_id: int): """ Connects to a voice channel. """
python
{ "resource": "" }
q256230
DefaultPlayer.disconnect
validation
async def disconnect(self): """ Disconnects from the voice channel, if any. """ if not self.is_connected:
python
{ "resource": "" }
q256231
DefaultPlayer.store
validation
def store(self, key: object, value: object): """ Stores custom user data. """
python
{ "resource": "" }
q256232
DefaultPlayer.fetch
validation
def fetch(self, key: object, default=None): """ Retrieves
python
{ "resource": "" }
q256233
DefaultPlayer.add
validation
def add(self, requester: int, track: dict): """ Adds a track to the queue. """
python
{ "resource": "" }
q256234
DefaultPlayer.add_next
validation
def add_next(self, requester: int, track: dict): """ Adds a track
python
{ "resource": "" }
q256235
DefaultPlayer.add_at
validation
def add_at(self, index: int, requester: int, track: dict): """ Adds a track at a specific index in the queue. """
python
{ "resource": "" }
q256236
DefaultPlayer.play
validation
async def play(self, track_index: int = 0, ignore_shuffle: bool = False): """ Plays the first track in the queue, if any or plays a track from the specified index in the queue. """ if self.repeat and self.current: self.queue.append(self.current) self.previous = self.current self.current = None self.position = 0 self.paused = False if not self.queue: await self.stop() await self._lavalink.dispatch_event(QueueEndEvent(self)) else: if self.shuffle and not ignore_shuffle:
python
{ "resource": "" }
q256237
DefaultPlayer.play_now
validation
async def play_now(self, requester: int, track: dict): """ Add track and play it. """
python
{ "resource": "" }
q256238
DefaultPlayer.play_at
validation
async def play_at(self, index: int): """ Play the queue from a specific point. Disregards tracks before
python
{ "resource": "" }
q256239
DefaultPlayer.play_previous
validation
async def play_previous(self): """ Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. """
python
{ "resource": "" }
q256240
DefaultPlayer.stop
validation
async def stop(self): """ Stops the player, if playing. """ await
python
{ "resource": "" }
q256241
DefaultPlayer.set_pause
validation
async def set_pause(self, pause: bool): """ Sets the player's paused state. """
python
{ "resource": "" }
q256242
DefaultPlayer.seek
validation
async def seek(self, pos: int): """ Seeks to a given position in the track. """
python
{ "resource": "" }
q256243
DefaultPlayer.handle_event
validation
async def handle_event(self, event): """ Makes the player play the next song from the queue if a song has finished or an issue occurred. """ if isinstance(event, (TrackStuckEvent, TrackExceptionEvent)) or \
python
{ "resource": "" }
q256244
PlayerManager.get
validation
def get(self, guild_id): """ Returns a player from the cache, or creates one if it does not exist. """ if guild_id not in self._players: p = self._player(lavalink=self.lavalink,
python
{ "resource": "" }
q256245
PlayerManager.remove
validation
def remove(self, guild_id): """ Removes a player from the current players. """ if guild_id in self._players:
python
{ "resource": "" }
q256246
Music._play
validation
async def _play(self, ctx, *, query: str): """ Searches and plays a song from a given query. """ player = self.bot.lavalink.players.get(ctx.guild.id) query = query.strip('<>') if not url_rx.match(query): query = f'ytsearch:{query}' tracks = await self.bot.lavalink.get_tracks(query) if not tracks: return await ctx.send('Nothing found!') embed = discord.Embed(color=discord.Color.blurple()) if 'list' in query and 'ytsearch:' not in query: for track in tracks: player.add(requester=ctx.author.id, track=track) embed.title = 'Playlist enqueued!'
python
{ "resource": "" }
q256247
Music._seek
validation
async def _seek(self, ctx, *, time: str): """ Seeks to a given position in a track. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send('Not playing.') seconds = time_rx.search(time) if not seconds: return await ctx.send('You need to specify the amount of seconds to skip!')
python
{ "resource": "" }
q256248
Music._now
validation
async def _now(self, ctx): """ Shows some stats about the currently playing song. """ player = self.bot.lavalink.players.get(ctx.guild.id) song = 'Nothing' if player.current: position = lavalink.Utils.format_time(player.position) if player.current.stream: duration = '🔴 LIVE' else: duration = lavalink.Utils.format_time(player.current.duration)
python
{ "resource": "" }
q256249
Music._queue
validation
async def _queue(self, ctx, page: int = 1): """ Shows the player's queue. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send('There\'s nothing in the queue! Why not queue something?') items_per_page = 10 pages = math.ceil(len(player.queue) / items_per_page)
python
{ "resource": "" }
q256250
Music._remove
validation
async def _remove(self, ctx, index: int): """ Removes an item from the player's queue with the given index. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send('Nothing queued.') if index > len(player.queue) or index < 1:
python
{ "resource": "" }
q256251
Music.ensure_voice
validation
async def ensure_voice(self, ctx): """ A few checks to make sure the bot can join a voice channel. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_connected: if not ctx.author.voice or not ctx.author.voice.channel: await ctx.send('You aren\'t connected to any voice channel.') raise commands.CommandInvokeError('Author not connected to voice channel.') permissions = ctx.author.voice.channel.permissions_for(ctx.me) if not permissions.connect or not permissions.speak: await ctx.send('Missing permissions `CONNECT` and/or `SPEAK`.')
python
{ "resource": "" }
q256252
Client.unregister_hook
validation
def unregister_hook(self, func): """ Unregisters a hook. For further explanation, please have a look at ``register_hook``. """
python
{ "resource": "" }
q256253
Client.dispatch_event
validation
async def dispatch_event(self, event): """ Dispatches an event to all registered hooks. """ log.debug('Dispatching event of type {} to {} hooks'.format(event.__class__.__name__, len(self.hooks))) for hook in self.hooks: try: if asyncio.iscoroutinefunction(hook): await hook(event) else: hook(event) except Exception as e: # pylint: disable=broad-except
python
{ "resource": "" }
q256254
Client.update_state
validation
async def update_state(self, data): """ Updates a player's state when a payload with opcode ``playerUpdate`` is received. """ guild_id = int(data['guildId']) if guild_id in self.players: player = self.players.get(guild_id)
python
{ "resource": "" }
q256255
Client.get_tracks
validation
async def get_tracks(self, query): """ Returns a Dictionary containing search results for a given query. """ log.debug('Requesting tracks
python
{ "resource": "" }
q256256
Client.destroy
validation
def destroy(self): """ Destroys the Lavalink client. """ self.ws.destroy()
python
{ "resource": "" }
q256257
AudioTrack.build
validation
def build(self, track, requester): """ Returns an optional AudioTrack. """ try: self.track = track['track'] self.identifier = track['info']['identifier'] self.can_seek = track['info']['isSeekable'] self.author = track['info']['author'] self.duration = track['info']['length'] self.stream = track['info']['isStream']
python
{ "resource": "" }
q256258
Music._previous
validation
async def _previous(self, ctx): """ Plays the previous song. """ player = self.bot.lavalink.players.get(ctx.guild.id)
python
{ "resource": "" }
q256259
Music._playnow
validation
async def _playnow(self, ctx, *, query: str): """ Plays immediately a song. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue and not player.is_playing: return await ctx.invoke(self._play, query=query) query = query.strip('<>') 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']
python
{ "resource": "" }
q256260
Music._playat
validation
async def _playat(self, ctx, index: int): """ Plays the queue from a specific point. Disregards tracks before the index. """ player = self.bot.lavalink.players.get(ctx.guild.id) if index < 1: return await ctx.send('Invalid specified index.')
python
{ "resource": "" }
q256261
Music._find
validation
async def _find(self, ctx, *, query): """ Lists the first 10 search results from a given query. """ if not query.startswith('ytsearch:') and not query.startswith('scsearch:'): query = 'ytsearch:' + query results = await self.bot.lavalink.get_tracks(query) if not 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):
python
{ "resource": "" }
q256262
AutoCompleter.add_suggestions
validation
def add_suggestions(self, *suggestions, **kwargs): """ Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string. If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores """ pipe = self.redis.pipeline() for sug in suggestions: args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score] if kwargs.get('increment'):
python
{ "resource": "" }
q256263
AutoCompleter.delete
validation
def delete(self, string): """ Delete a string from the AutoCompleter index. Returns 1 if the string was found and deleted, 0 otherwise
python
{ "resource": "" }
q256264
AutoCompleter.get_suggestions
validation
def get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False): """ Get a list of suggestions from the AutoCompleter, for a given prefix ### Parameters: - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8** - **fuzzy**: 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.
python
{ "resource": "" }
q256265
Client.create_index
validation
def create_index(self, fields, no_term_offsets=False, no_field_flags=False, stopwords = None): """ Create the search index. The index must not already exist. ### Parameters: - **fields**: a list of TextField or NumericField objects - **no_term_offsets**: If 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:
python
{ "resource": "" }
q256266
Client._add_document
validation
def _add_document(self, doc_id, conn=None, nosave=False, score=1.0, payload=None, replace=False, partial=False, language=None, **fields): """ Internal add_document used for both batch and single doc indexing """ if conn is None: conn = self.redis 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')
python
{ "resource": "" }
q256267
Client.add_document
validation
def add_document(self, doc_id, nosave=False, score=1.0, payload=None, replace=False, partial=False, language=None, **fields): """ Add a single document to the index. ### Parameters - **doc_id**: the id of the saved document. - **nosave**: if set to true, we 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
python
{ "resource": "" }
q256268
Client.delete_document
validation
def delete_document(self, doc_id, conn=None): """ Delete a document from index Returns 1 if the document was deleted, 0 if not """ if conn is None:
python
{ "resource": "" }
q256269
Client.load_document
validation
def load_document(self, id): """ Load a single document by id """ fields = self.redis.hgetall(id) if six.PY3: f2 = {to_string(k): to_string(v) for k, v in fields.items()} fields = f2
python
{ "resource": "" }
q256270
Client.info
validation
def info(self): """ Get info an stats about the the current index, including the number of documents, memory consumption, etc """
python
{ "resource": "" }
q256271
Client.search
validation
def search(self, query): """ Search the index for a given query, and return a result of documents ### Parameters - **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries. See RediSearch's documentation on query format
python
{ "resource": "" }
q256272
Client.aggregate
validation
def aggregate(self, query): """ Issue an aggregation query ### Parameters **query**: This can be either an `AggeregateRequest`, or a `Cursor` An `AggregateResult` object is returned. You can access the rows from its `rows` property, which will always yield the rows of 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()
python
{ "resource": "" }
q256273
Reducer.alias
validation
def alias(self, alias): """ Set the alias for this reducer. ### Parameters - **alias**: The value of the alias for this reducer. If this is the special value `aggregation.FIELDNAME` then this reducer will be aliased using the same name as the field upon which it 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.
python
{ "resource": "" }
q256274
AggregateRequest.group_by
validation
def group_by(self, fields, *reducers): """ Specify by which fields to group the aggregation. ### Parameters - **fields**: Fields to group by. This can either be a single string, or a list of strings. both cases, the field should be specified as
python
{ "resource": "" }
q256275
AggregateRequest.apply
validation
def apply(self, **kwexpr): """ Specify one or more projection expressions to add to each result ### Parameters - **kwexpr**: One or more key-value pairs for a projection. The key is the alias for the projection, and the value is the projection
python
{ "resource": "" }
q256276
AggregateRequest.limit
validation
def limit(self, offset, num): """ Sets the limit for the most recent group or query. If no group has been defined yet (via `group_by()`) then this sets the limit for the initial pool of results from the query. Otherwise, this limits the number of items operated on from the 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,
python
{ "resource": "" }
q256277
Query.get_args
validation
def get_args(self): """ Format the redis arguments for this query and return them """ args = [self._query_string] if self._no_content: args.append('NOCONTENT') if self._fields: args.append('INFIELDS') args.append(len(self._fields)) 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:
python
{ "resource": "" }
q256278
Query.sort_by
validation
def sort_by(self, field, asc=True): """ Add a sortby field to the query - **field** - the name of the field to sort by - **asc** - when
python
{ "resource": "" }
q256279
between
validation
def between(a, b, inclusive_min=True, inclusive_max=True): """ Indicate that value is a numeric range """ return RangeValue(a, b,
python
{ "resource": "" }
q256280
geo
validation
def geo(lat, lon, radius, unit='km'): """ Indicate that value is a geo region
python
{ "resource": "" }
q256281
Bypass.transform
validation
def transform(self, jam): '''Bypass transformations. Parameters ---------- jam : pyjams.JAMS A muda-enabled JAMS object Yields ------ jam_out : pyjams.JAMS iterator The first result is `jam` (unmodified), by reference All subsequent results are
python
{ "resource": "" }
q256282
transpose
validation
def transpose(label, n_semitones): '''Transpose a chord label by some number of semitones Parameters ---------- label : str A chord string n_semitones : float The number of semitones to move `label` Returns ------- label_transpose : str The transposed chord label ''' # Otherwise, split off the note from the modifier match = re.match(six.text_type('(?P<note>[A-G][b#]*)(?P<mod>.*)'),
python
{ "resource": "" }
q256283
jam_pack
validation
def jam_pack(jam, **kwargs): '''Pack data into a jams sandbox. If not already present, this creates a `muda` field within `jam.sandbox`, along with `history`, `state`, and version arrays which are populated by deformation objects. Any additional fields can be added to the `muda` sandbox by 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=[],
python
{ "resource": "" }
q256284
load_jam_audio
validation
def load_jam_audio(jam_in, audio_file, validate=True, strict=True, fmt='auto', **kwargs): '''Load a jam and pack it with audio. Parameters ---------- jam_in : str, file descriptor, or jams.JAMS JAMS filename, open file-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
python
{ "resource": "" }
q256285
save
validation
def save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs): '''Save a muda jam to disk Parameters ---------- filename_audio: str The path to store the audio file filename_jam: str The path to store the jams object strict: bool
python
{ "resource": "" }
q256286
__reconstruct
validation
def __reconstruct(params): '''Reconstruct a transformation or pipeline given a parameter dump.''' if isinstance(params, dict): if '__class__' in params: cls = params['__class__'] data = __reconstruct(params['params'])
python
{ "resource": "" }
q256287
serialize
validation
def serialize(transform, **kwargs): '''Serialize a transformation object or pipeline. Parameters ---------- transform : BaseTransform or Pipeline The transformation object to be serialized kwargs Additional keyword arguments to `jsonpickle.encode()`
python
{ "resource": "" }
q256288
deserialize
validation
def deserialize(encoded, **kwargs): '''Construct a muda transformation from a JSON encoded string. Parameters ---------- encoded : str JSON encoding of the transformation or pipeline kwargs Additional keyword arguments to `jsonpickle.decode()`
python
{ "resource": "" }
q256289
_pprint
validation
def _pprint(params, offset=0, printer=repr): """Pretty print the dictionary 'params' Parameters ---------- params: dict The dictionary to pretty print offset: int The offset in characters to add at the begin of each line. printer: The function to convert entries to 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:
python
{ "resource": "" }
q256290
BaseTransformer._get_param_names
validation
def _get_param_names(cls): '''Get the list of parameter names for the object''' init = cls.__init__ args, varargs = inspect.getargspec(init)[:2] if varargs is not None:
python
{ "resource": "" }
q256291
BaseTransformer._transform
validation
def _transform(self, jam, state): '''Apply the transformation to audio and annotations. The input jam is copied and modified, and returned contained in a list. Parameters ---------- jam : jams.JAMS A single jam object to modify Returns ------- 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.')
python
{ "resource": "" }
q256292
BaseTransformer.transform
validation
def transform(self, jam): '''Iterative transformation generator Applies the deformation to an input jams object. This generates a sequence of deformed output JAMS. Parameters
python
{ "resource": "" }
q256293
Pipeline.__recursive_transform
validation
def __recursive_transform(self, jam, steps): '''A recursive transformation pipeline''' if len(steps) > 0: head_transformer = steps[0][1] for t_jam in head_transformer.transform(jam): for q
python
{ "resource": "" }
q256294
Union.__serial_transform
validation
def __serial_transform(self, jam, steps): '''A serial transformation union''' # This uses the round-robin itertools recipe if six.PY2: attr = 'next' else: attr = '__next__' pending = len(steps) nexts = itertools.cycle(getattr(iter(D.transform(jam)), attr) for (name, D) in steps) while pending: try:
python
{ "resource": "" }
q256295
sample_clip_indices
validation
def sample_clip_indices(filename, n_samples, sr): '''Calculate the indices at which to sample a fragment of audio from a file. Parameters ---------- filename : str Path to the input file n_samples : int > 0 The number of samples to load sr : int > 0 The target sampling 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
python
{ "resource": "" }
q256296
slice_clip
validation
def slice_clip(filename, start, stop, n_samples, sr, mono=True): '''Slice a fragment of audio from a file. This uses pysoundfile to efficiently seek without loading the entire stream. Parameters ---------- filename : str Path to the input file start : int The sample index 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
python
{ "resource": "" }
q256297
norm_remote_path
validation
def norm_remote_path(path): """Normalize `path`. All remote paths are absolute.
python
{ "resource": "" }
q256298
split_storage
validation
def split_storage(path, default='osfstorage'): """Extract storage name from file path. If a path begins with a known storage provider the name is removed from the path. Otherwise the `default` storage provider is returned and the path is not modified. """ path = norm_remote_path(path) for provider in KNOWN_PROVIDERS:
python
{ "resource": "" }
q256299
file_empty
validation
def file_empty(fp): """Determine if a file is empty or not.""" # for python 2 we need to use a homemade peek() if six.PY2: contents =
python
{ "resource": "" }