sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def do_folder_update_metadata(client, args): """Update file metadata""" client.update_folder_metadata(args.uri, foldername=args.foldername, description=args.description, mtime=args.mtime, privacy=args.privacy, ...
Update file metadata
entailment
def main(): # pylint: disable=too-many-statements """Main entry point""" parser = argparse.ArgumentParser(prog='mediafire-cli', description=__doc__) parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Enable de...
Main entry point
entailment
def pub(self, topic, message): '''Publish a message to a topic''' return self.post('pub', params={'topic': topic}, data=message)
Publish a message to a topic
entailment
def mpub(self, topic, messages, binary=True): '''Send multiple messages to a topic. Optionally pack the messages''' if binary: # Pack and ship the data return self.post('mpub', data=pack(messages)[4:], params={'topic': topic, 'binary': True}) elif any('\n'...
Send multiple messages to a topic. Optionally pack the messages
entailment
def clean_stats(self): '''Stats with topics and channels keyed on topic and channel names''' stats = self.stats() if 'topics' in stats: # pragma: no branch topics = stats['topics'] topics = dict((t.pop('topic_name'), t) for t in topics) for topic, data in top...
Stats with topics and channels keyed on topic and channel names
entailment
def execute_add(args, root_dir=None): """Add a new command to the daemon queue. Args: args['command'] (list(str)): The actual programm call. Something like ['ls', '-a'] or ['ls -al'] root_dir (string): The path to the root directory the daemon is running in. """ # We accept a list of s...
Add a new command to the daemon queue. Args: args['command'] (list(str)): The actual programm call. Something like ['ls', '-a'] or ['ls -al'] root_dir (string): The path to the root directory the daemon is running in.
entailment
def execute_edit(args, root_dir=None): """Edit a existing queue command in the daemon. Args: args['key'] int: The key of the queue entry to be edited root_dir (string): The path to the root directory the daemon is running in. """ # Get editor EDITOR = os.environ.get('EDITOR', 'vim')...
Edit a existing queue command in the daemon. Args: args['key'] int: The key of the queue entry to be edited root_dir (string): The path to the root directory the daemon is running in.
entailment
def command_factory(command): """A factory which returns functions for direct daemon communication. This factory will create a function which sends a payload to the daemon and returns the unpickled object which is returned by the daemon. Args: command (string): The type of payload this should ...
A factory which returns functions for direct daemon communication. This factory will create a function which sends a payload to the daemon and returns the unpickled object which is returned by the daemon. Args: command (string): The type of payload this should be. This determines as wh...
entailment
def get_descriptor(self, number): """Create file descriptors for process output.""" # Create stdout file and get file descriptor stdout_path = os.path.join(self.config_dir, 'pueue_process_{}.stdout'.format(number)) if os.path.exists(stdout_path): ...
Create file descriptors for process output.
entailment
def clean_descriptor(self, number): """Close file descriptor and remove underlying files.""" self.descriptors[number]['stdout'].close() self.descriptors[number]['stderr'].close() if os.path.exists(self.descriptors[number]['stdout_path']): os.remove(self.descriptors[number]['...
Close file descriptor and remove underlying files.
entailment
def check_finished(self): """Poll all processes and handle any finished processes.""" changed = False for key in list(self.processes.keys()): # Poll process and check if it finshed process = self.processes[key] process.poll() if process.returncode ...
Poll all processes and handle any finished processes.
entailment
def check_for_new(self): """Check if we can start a new process.""" free_slots = self.max_processes - len(self.processes) for item in range(free_slots): key = self.queue.next() if key is not None: self.spawn_new(key)
Check if we can start a new process.
entailment
def spawn_new(self, key): """Spawn a new task and save it to the queue.""" # Check if path exists if not os.path.exists(self.queue[key]['path']): self.queue[key]['status'] = 'failed' error_msg = "The directory for this command doesn't exist anymore: {}".format(self.queue[...
Spawn a new task and save it to the queue.
entailment
def kill_all(self, kill_signal, kill_shell=False): """Kill all running processes.""" for key in self.processes.keys(): self.kill_process(key, kill_signal, kill_shell)
Kill all running processes.
entailment
def start_process(self, key): """Start a specific processes.""" if key in self.processes and key in self.paused: os.killpg(os.getpgid(self.processes[key].pid), signal.SIGCONT) self.queue[key]['status'] = 'running' self.paused.remove(key) return True ...
Start a specific processes.
entailment
def pause_process(self, key): """Pause a specific processes.""" if key in self.processes and key not in self.paused: os.killpg(os.getpgid(self.processes[key].pid), signal.SIGSTOP) self.queue[key]['status'] = 'paused' self.paused.append(key) return True ...
Pause a specific processes.
entailment
def daemon_factory(path): """Create a closure which creates a running daemon. We need to create a closure that contains the correct path the daemon should be started with. This is needed as the `Daemonize` library requires a callable function for daemonization and doesn't accept any arguments. This...
Create a closure which creates a running daemon. We need to create a closure that contains the correct path the daemon should be started with. This is needed as the `Daemonize` library requires a callable function for daemonization and doesn't accept any arguments. This function cleans up sockets and o...
entailment
def main(): """Execute entry function.""" args = parser.parse_args() args_dict = vars(args) root_dir = args_dict['root'] if 'root' in args else None # If a root directory is specified, get the absolute path and # check if it exists. Abort if it doesn't exist! if root_dir: root_dir =...
Execute entry function.
entailment
def register(host=DFLT_ADDRESS[0], port=DFLT_ADDRESS[1], signum=signal.SIGUSR1): """Register a pdb handler for signal 'signum'. The handler sets pdb to listen on the ('host', 'port') internet address and to start a remote debugging session on accepting a socket connection. """ _pdbhand...
Register a pdb handler for signal 'signum'. The handler sets pdb to listen on the ('host', 'port') internet address and to start a remote debugging session on accepting a socket connection.
entailment
def get_handler(): """Return the handler as a named tuple. The named tuple attributes are 'host', 'port', 'signum'. Return None when no handler has been registered. """ host, port, signum = _pdbhandler._registered() if signum: return Handler(host if host else DFLT_ADDRESS[0].encode(), ...
Return the handler as a named tuple. The named tuple attributes are 'host', 'port', 'signum'. Return None when no handler has been registered.
entailment
def wait(self, timeout): '''Wait for the provided time to elapse''' logger.debug('Waiting for %fs', timeout) return self._event.wait(timeout)
Wait for the provided time to elapse
entailment
def delay(self): '''How long to wait before the next check''' if self._last_checked: return self._interval - (time.time() - self._last_checked) return self._interval
How long to wait before the next check
entailment
def callback(self): '''Run the callback''' self._callback(*self._args, **self._kwargs) self._last_checked = time.time()
Run the callback
entailment
def run(self): '''Run the callback periodically''' while not self.wait(self.delay()): try: logger.info('Invoking callback %s', self.callback) self.callback() except StandardError: logger.exception('Callback failed')
Run the callback periodically
entailment
def login(self, email=None, password=None, app_id=None, api_key=None): """Login to MediaFire account. Keyword arguments: email -- account email password -- account password app_id -- application ID api_key -- API Key (optional) """ session_token = self.ap...
Login to MediaFire account. Keyword arguments: email -- account email password -- account password app_id -- application ID api_key -- API Key (optional)
entailment
def get_resource_by_uri(self, uri): """Return resource described by MediaFire URI. uri -- MediaFire URI Examples: Folder (using folderkey): mf:r5g3p2z0sqs3j mf:r5g3p2z0sqs3j/folder/file.ext File (using quickkey): mf:xkr43dadqa3o2p2 ...
Return resource described by MediaFire URI. uri -- MediaFire URI Examples: Folder (using folderkey): mf:r5g3p2z0sqs3j mf:r5g3p2z0sqs3j/folder/file.ext File (using quickkey): mf:xkr43dadqa3o2p2 Path: mf:///Documents/f...
entailment
def get_resource_by_key(self, resource_key): """Return resource by quick_key/folder_key. key -- quick_key or folder_key """ # search for quick_key by default lookup_order = ["quick_key", "folder_key"] if len(resource_key) == FOLDER_KEY_LENGTH: lookup_order ...
Return resource by quick_key/folder_key. key -- quick_key or folder_key
entailment
def get_resource_by_path(self, path, folder_key=None): """Return resource by remote path. path -- remote path Keyword arguments: folder_key -- what to use as the root folder (None for root) """ logger.debug("resolving %s", path) # remove empty path components ...
Return resource by remote path. path -- remote path Keyword arguments: folder_key -- what to use as the root folder (None for root)
entailment
def _folder_get_content_iter(self, folder_key=None): """Iterator for api.folder_get_content""" lookup_params = [ {'content_type': 'folders', 'node': 'folders'}, {'content_type': 'files', 'node': 'files'} ] for param in lookup_params: more_chunks = Tr...
Iterator for api.folder_get_content
entailment
def get_folder_contents_iter(self, uri): """Return iterator for directory contents. uri -- mediafire URI Example: for item in get_folder_contents_iter('mf:///Documents'): print(item) """ resource = self.get_resource_by_uri(uri) if not isins...
Return iterator for directory contents. uri -- mediafire URI Example: for item in get_folder_contents_iter('mf:///Documents'): print(item)
entailment
def create_folder(self, uri, recursive=False): """Create folder. uri -- MediaFire URI Keyword arguments: recursive -- set to True to create intermediate folders. """ logger.info("Creating %s", uri) # check that folder exists already try: res...
Create folder. uri -- MediaFire URI Keyword arguments: recursive -- set to True to create intermediate folders.
entailment
def delete_folder(self, uri, purge=False): """Delete folder. uri -- MediaFire folder URI Keyword arguments: purge -- delete the folder without sending it to Trash """ try: resource = self.get_resource_by_uri(uri) except ResourceNotFoundError: ...
Delete folder. uri -- MediaFire folder URI Keyword arguments: purge -- delete the folder without sending it to Trash
entailment
def delete_file(self, uri, purge=False): """Delete file. uri -- MediaFire file URI Keyword arguments: purge -- delete the file without sending it to Trash. """ try: resource = self.get_resource_by_uri(uri) except ResourceNotFoundError: # ...
Delete file. uri -- MediaFire file URI Keyword arguments: purge -- delete the file without sending it to Trash.
entailment
def delete_resource(self, uri, purge=False): """Delete file or folder uri -- mediafire URI Keyword arguments: purge -- delete the resource without sending it to Trash. """ try: resource = self.get_resource_by_uri(uri) except ResourceNotFoundError: ...
Delete file or folder uri -- mediafire URI Keyword arguments: purge -- delete the resource without sending it to Trash.
entailment
def _prepare_upload_info(self, source, dest_uri): """Prepare Upload object, resolve paths""" try: dest_resource = self.get_resource_by_uri(dest_uri) except ResourceNotFoundError: dest_resource = None is_fh = hasattr(source, 'read') folder_key = None ...
Prepare Upload object, resolve paths
entailment
def upload_file(self, source, dest_uri): """Upload file to MediaFire. source -- path to the file or a file-like object (e.g. io.BytesIO) dest_uri -- MediaFire Resource URI """ folder_key, name = self._prepare_upload_info(source, dest_uri) is_fh = hasattr(source, 'read'...
Upload file to MediaFire. source -- path to the file or a file-like object (e.g. io.BytesIO) dest_uri -- MediaFire Resource URI
entailment
def download_file(self, src_uri, target): """Download file from MediaFire. src_uri -- MediaFire file URI to download target -- download path or file-like object in write mode """ resource = self.get_resource_by_uri(src_uri) if not isinstance(resource, File): ...
Download file from MediaFire. src_uri -- MediaFire file URI to download target -- download path or file-like object in write mode
entailment
def update_file_metadata(self, uri, filename=None, description=None, mtime=None, privacy=None): """Update file metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change the metadata on the server side: filename -- r...
Update file metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change the metadata on the server side: filename -- rename file description -- set file description string mtime -- set file modification time privacy -- set file pr...
entailment
def update_folder_metadata(self, uri, foldername=None, description=None, mtime=None, privacy=None, privacy_recursive=None): """Update folder metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change ...
Update folder metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change the metadata on the server side: filename -- rename file description -- set file description string mtime -- set file modification time privacy -- set file ...
entailment
def _parse_uri(uri): """Parse and validate MediaFire URI.""" tokens = urlparse(uri) if tokens.netloc != '': logger.error("Invalid URI: %s", uri) raise ValueError("MediaFire URI format error: " "host should be empty - mf:///path") if...
Parse and validate MediaFire URI.
entailment
def merged(self): '''The clean stats from all the hosts reporting to this host.''' stats = {} for topic in self.client.topics()['topics']: for producer in self.client.lookup(topic)['producers']: hostname = producer['broadcast_address'] port = producer[...
The clean stats from all the hosts reporting to this host.
entailment
def raw(self): '''All the raw, unaggregated stats (with duplicates).''' topic_keys = ( 'message_count', 'depth', 'backend_depth', 'paused' ) channel_keys = ( 'in_flight_count', 'timeout_count', 'paused',...
All the raw, unaggregated stats (with duplicates).
entailment
def stats(self): '''Stats that have been aggregated appropriately.''' data = Counter() for name, value, aggregated in self.raw: if aggregated: data['%s.max' % name] = max(data['%s.max' % name], value) data['%s.total' % name] += value else: ...
Stats that have been aggregated appropriately.
entailment
def get_curline(): """Return the current python source line.""" if Frame: frame = Frame.get_selected_python_frame() if frame: line = '' f = frame.get_pyop() if f and not f.is_optimized_out(): cwd = os.path.join(os.getcwd(), '') ...
Return the current python source line.
entailment
def reconnected(self, conn): '''Subscribe connection and manipulate its RDY state''' conn.sub(self._topic, self._channel) conn.rdy(1)
Subscribe connection and manipulate its RDY state
entailment
def distribute_ready(self): '''Distribute the ready state across all of the connections''' connections = [c for c in self.connections() if c.alive()] if len(connections) > self._max_in_flight: raise NotImplementedError( 'Max in flight must be greater than number of co...
Distribute the ready state across all of the connections
entailment
def needs_distribute_ready(self): '''Determine whether or not we need to redistribute the ready state''' # Try to pre-empty starvation by comparing current RDY against # the last value sent. alive = [c for c in self.connections() if c.alive()] if any(c.ready <= (c.last_ready_sent...
Determine whether or not we need to redistribute the ready state
entailment
def read(self): '''Read some number of messages''' found = Client.read(self) # Redistribute our ready state if necessary if self.needs_distribute_ready(): self.distribute_ready() # Finally, return all the results we've read return found
Read some number of messages
entailment
def profiler(): '''Profile the block''' import cProfile import pstats pr = cProfile.Profile() pr.enable() yield pr.disable() ps = pstats.Stats(pr).sort_stats('tottime') ps.print_stats()
Profile the block
entailment
def messages(count, size): '''Generator for count messages of the provided size''' import string # Make sure we have at least 'size' letters letters = islice(cycle(chain(string.lowercase, string.uppercase)), size) return islice(cycle(''.join(l) for l in permutations(letters, size)), count)
Generator for count messages of the provided size
entailment
def grouper(iterable, n): '''Collect data into fixed-length chunks or blocks''' args = [iter(iterable)] * n for group in izip_longest(fillvalue=None, *args): group = [g for g in group if g != None] yield group
Collect data into fixed-length chunks or blocks
entailment
def basic(topic='topic', channel='channel', count=1e6, size=10, gevent=False, max_in_flight=2500, profile=False): '''Basic benchmark''' if gevent: from gevent import monkey monkey.patch_all() # Check the types of the arguments count = int(count) size = int(size) max_in_fligh...
Basic benchmark
entailment
def stats(): '''Read a stream of floats and give summary statistics''' import re import sys import math values = [] for line in sys.stdin: values.extend(map(float, re.findall(r'\d+\.?\d+', line))) mean = sum(values) / len(values) variance = sum((val - mean) ** 2 for val in value...
Read a stream of floats and give summary statistics
entailment
def ready(self): '''Whether or not enough time has passed since the last failure''' if self._last_failed: delta = time.time() - self._last_failed return delta >= self.backoff() return True
Whether or not enough time has passed since the last failure
entailment
def execute_status(args, root_dir=None): """Print the status of the daemon. This function displays the current status of the daemon as well as the whole queue and all available information about every entry in the queue. `terminaltables` is used to format and display the queue contents. `colorc...
Print the status of the daemon. This function displays the current status of the daemon as well as the whole queue and all available information about every entry in the queue. `terminaltables` is used to format and display the queue contents. `colorclass` is used to color format the various items ...
entailment
def execute_log(args, root_dir): """Print the current log file. Args: args['keys'] (int): If given, we only look at the specified processes. root_dir (string): The path to the root directory the daemon is running in. """ # Print the logs of all specified processes if args.get('keys...
Print the current log file. Args: args['keys'] (int): If given, we only look at the specified processes. root_dir (string): The path to the root directory the daemon is running in.
entailment
def execute_show(args, root_dir): """Print stderr and stdout of the current running process. Args: args['watch'] (bool): If True, we open a curses session and tail the output live in the console. root_dir (string): The path to the root directory the daemon is runni...
Print stderr and stdout of the current running process. Args: args['watch'] (bool): If True, we open a curses session and tail the output live in the console. root_dir (string): The path to the root directory the daemon is running in.
entailment
def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches a song track by given ID. :param track_id: the track ID. :type track_id: str :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_id`. ''...
Fetches a song track by given ID. :param track_id: the track ID. :type track_id: str :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_id`.
entailment
def show(self, user, feed, id): """ Show a specific indicator by id :param user: feed username :param feed: feed name :param id: indicator endpoint id [INT] :return: dict Example: ret = Indicator.show('csirtgadgets','port-scanners', '1234') "...
Show a specific indicator by id :param user: feed username :param feed: feed name :param id: indicator endpoint id [INT] :return: dict Example: ret = Indicator.show('csirtgadgets','port-scanners', '1234')
entailment
def create(self): """ Submit action on the Indicator object :return: Indicator Object """ uri = '/users/{0}/feeds/{1}/indicators'\ .format(self.user, self.feed) data = { "indicator": json.loads(str(self.indicator)), "comment": self.co...
Submit action on the Indicator object :return: Indicator Object
entailment
def create_bulk(self, indicators, user, feed): from .constants import API_VERSION if API_VERSION == '1': print("create_bulk currently un-avail with APIv1") raise SystemExit """ Submit action against the IndicatorBulk endpoint :param indicators: list of I...
Submit action against the IndicatorBulk endpoint :param indicators: list of Indicator Objects :param user: feed username :param feed: feed name :return: list of Indicator Objects submitted from csirtgsdk.client import Client from csirtgsdk.indicator import Indicator ...
entailment
def bind_global_key(conn, event_type, key_string, cb): """ An alias for ``bind_key(event_type, ROOT_WINDOW, key_string, cb)``. :param event_type: Either 'KeyPress' or 'KeyRelease'. :type event_type: str :param key_string: A string of the form 'Mod1-Control-a'. Namely, a list o...
An alias for ``bind_key(event_type, ROOT_WINDOW, key_string, cb)``. :param event_type: Either 'KeyPress' or 'KeyRelease'. :type event_type: str :param key_string: A string of the form 'Mod1-Control-a'. Namely, a list of zero or more modifiers separated by '-', f...
entailment
def bind_key(conn, event_type, wid, key_string, cb): """ Binds a function ``cb`` to a particular key press ``key_string`` on a window ``wid``. Whether it's a key release or key press binding is determined by ``event_type``. ``bind_key`` will automatically hook into the ``event`` module's dispatcher,...
Binds a function ``cb`` to a particular key press ``key_string`` on a window ``wid``. Whether it's a key release or key press binding is determined by ``event_type``. ``bind_key`` will automatically hook into the ``event`` module's dispatcher, so that if you're using ``event.main()`` for your main loop,...
entailment
def parse_keystring(conn, key_string): """ A utility function to turn strings like 'Mod1+Mod4+a' into a pair corresponding to its modifiers and keycode. :param key_string: String starting with zero or more modifiers followed by exactly one key press. Avail...
A utility function to turn strings like 'Mod1+Mod4+a' into a pair corresponding to its modifiers and keycode. :param key_string: String starting with zero or more modifiers followed by exactly one key press. Available modifiers: Control, Mod1, Mod2, Mod3, Mod4, ...
entailment
def lookup_string(conn, kstr): """ Finds the keycode associated with a string representation of a keysym. :param kstr: English representation of a keysym. :return: Keycode, if one exists. :rtype: int """ if kstr in keysyms: return get_keycode(conn, keysyms[kstr]) elif len(kstr) ...
Finds the keycode associated with a string representation of a keysym. :param kstr: English representation of a keysym. :return: Keycode, if one exists. :rtype: int
entailment
def get_keyboard_mapping(conn): """ Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie """ mn, mx = get_min_max_keycode(conn) return conn.core.GetKeyboardMapping(mn, mx - mn + 1)
Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie
entailment
def get_keyboard_mapping_unchecked(conn): """ Return an unchecked keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie """ mn, mx = get_min_max_keycode() return conn.core.GetKeyboardMappingUnchecked...
Return an unchecked keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie
entailment
def get_keysym(conn, keycode, col=0, kbmap=None): """ Get the keysym associated with a particular keycode in the current X environment. Although we get a list of keysyms from X in 'get_keyboard_mapping', this list is really a table with 'keysys_per_keycode' columns and ``mx - mn`` rows (where ``mx``...
Get the keysym associated with a particular keycode in the current X environment. Although we get a list of keysyms from X in 'get_keyboard_mapping', this list is really a table with 'keysys_per_keycode' columns and ``mx - mn`` rows (where ``mx`` is the maximum keycode and ``mn`` is the minimum keycode)...
entailment
def get_keycode(conn, keysym): """ Given a keysym, find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in order to do this, including all columns. :param keysym: An X keysym. :return: A keycode or None if one could not be found. :rtype: int...
Given a keysym, find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in order to do this, including all columns. :param keysym: An X keysym. :return: A keycode or None if one could not be found. :rtype: int
entailment
def get_keys_to_mods(conn): """ Fetches and creates the keycode -> modifier mask mapping. Typically, you shouldn't have to use this---xpybutil will keep this up to date if it changes. This function may be useful in that it should closely replicate the output of the ``xmodmap`` command. For exam...
Fetches and creates the keycode -> modifier mask mapping. Typically, you shouldn't have to use this---xpybutil will keep this up to date if it changes. This function may be useful in that it should closely replicate the output of the ``xmodmap`` command. For example: :: keymods = get_key...
entailment
def get_modifiers(state): """ Takes a ``state`` (typically found in key press or button press events) and returns a string list representation of the modifiers that were pressed when generating the event. :param state: Typically from ``some_event.state``. :return: List of modifier string repres...
Takes a ``state`` (typically found in key press or button press events) and returns a string list representation of the modifiers that were pressed when generating the event. :param state: Typically from ``some_event.state``. :return: List of modifier string representations. :rtype: [str]
entailment
def grab_key(conn, wid, modifiers, key): """ Grabs a key for a particular window and a modifiers/key value. If the grab was successful, return True. Otherwise, return False. If your client is grabbing keys, it is useful to notify the user if a key wasn't grabbed. Keyboard shortcuts not responding is...
Grabs a key for a particular window and a modifiers/key value. If the grab was successful, return True. Otherwise, return False. If your client is grabbing keys, it is useful to notify the user if a key wasn't grabbed. Keyboard shortcuts not responding is disorienting! Also, this function will grab sev...
entailment
def ungrab_key(conn, wid, modifiers, key): """ Ungrabs a key that was grabbed by ``grab_key``. Similarly, it will return True on success and False on failure. When ungrabbing a key, the parameters to this function should be *precisely* the same as the parameters to ``grab_key``. :param wid: A ...
Ungrabs a key that was grabbed by ``grab_key``. Similarly, it will return True on success and False on failure. When ungrabbing a key, the parameters to this function should be *precisely* the same as the parameters to ``grab_key``. :param wid: A window identifier. :type wid: int :param modifi...
entailment
def update_keyboard_mapping(conn, e): """ Whenever the keyboard mapping is changed, this function needs to be called to update xpybutil's internal representing of the current keysym table. Indeed, xpybutil will do this for you automatically. Moreover, if something is changed that affects the curren...
Whenever the keyboard mapping is changed, this function needs to be called to update xpybutil's internal representing of the current keysym table. Indeed, xpybutil will do this for you automatically. Moreover, if something is changed that affects the current keygrabs, xpybutil will initiate a regrab wi...
entailment
def run_keybind_callbacks(e): """ A function that intercepts all key press/release events, and runs their corresponding callback functions. Nothing much to see here, except that we must mask out the trivial modifiers from the state in order to find the right callback. Callbacks are called in the...
A function that intercepts all key press/release events, and runs their corresponding callback functions. Nothing much to see here, except that we must mask out the trivial modifiers from the state in order to find the right callback. Callbacks are called in the order that they have been added. (FIFO.) ...
entailment
def __regrab(changes): """ Takes a dictionary of changes (mapping old keycode to new keycode) and regrabs any keys that have been changed with the updated keycode. :param changes: Mapping of changes from old keycode to new keycode. :type changes: dict :rtype: void """ for wid, mods, kc ...
Takes a dictionary of changes (mapping old keycode to new keycode) and regrabs any keys that have been changed with the updated keycode. :param changes: Mapping of changes from old keycode to new keycode. :type changes: dict :rtype: void
entailment
def get_storages(self, storage_type='normal'): """ Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite """ res = self.get_request('/storage/' + storage_type) return Storage._create_storage_objs(res['sto...
Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite
entailment
def get_storage(self, storage): """ Return a Storage object from the API. """ res = self.get_request('/storage/' + str(storage)) return Storage(cloud_manager=self, **res['storage'])
Return a Storage object from the API.
entailment
def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}): """ Create a Storage object. Returns an object based on the API's response. """ body = { 'storage': { 'size': size, 'tier': tier, ...
Create a Storage object. Returns an object based on the API's response.
entailment
def modify_storage(self, storage, size, title, backup_rule={}): """ Modify a Storage object. Returns an object based on the API's response. """ res = self._modify_storage(str(storage), size, title, backup_rule) return Storage(cloud_manager=self, **res['storage'])
Modify a Storage object. Returns an object based on the API's response.
entailment
def attach_storage(self, server, storage, storage_type, address): """ Attach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {}} if storage: body['storage_device']['storage'] = str(storage) if storage_type: ...
Attach a Storage object to a Server. Return a list of the server's storages.
entailment
def detach_storage(self, server, address): """ Detach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {'address': address}} url = '/server/{0}/storage/detach'.format(server) res = self.post_request(url, body) ret...
Detach a Storage object to a Server. Return a list of the server's storages.
entailment
def _reset(self, **kwargs): """ Reset after repopulating from API. """ # there are some inconsistenciens in the API regarding these # note: this could be written in fancier ways, but this way is simpler if 'uuid' in kwargs: self.uuid = kwargs['uuid'] ...
Reset after repopulating from API.
entailment
def save(self): """ Save (modify) the storage to the API. Note: only size and title are updateable fields. """ res = self.cloud_manager._modify_storage(self, self.size, self.title) self._reset(**res['storage'])
Save (modify) the storage to the API. Note: only size and title are updateable fields.
entailment
def to_dict(self): """ Return a dict that can be serialised to JSON and sent to UpCloud's API. Uses the convenience attribute `os` for determining `action` and `storage` fields. """ body = { 'tier': self.tier, 'title': self.title, 'siz...
Return a dict that can be serialised to JSON and sent to UpCloud's API. Uses the convenience attribute `os` for determining `action` and `storage` fields.
entailment
def fetch_album(self, album_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches an album by given ID. :param album_id: the album ID. :type album_id: str :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1....
Fetches an album by given ID. :param album_id: the album ID. :type album_id: str :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#albums-album_id`.
entailment
def lookup(self): """ Prints name, author, size and age """ print "%s by %s, size: %s, uploaded %s ago" % (self.name, self.author, self.size, self.age)
Prints name, author, size and age
entailment
def _get_max_page(self, url): """ Open url and return amount of pages """ html = requests.get(url).text pq = PyQuery(html) try: tds = int(pq("h2").text().split()[-1]) if tds % 25: return tds / 25 + 1 return tds / 25 ...
Open url and return amount of pages
entailment
def build(self, update=True): """ Build and return url. Also update max_page. """ ret = self.base + self.query page = "".join(("/", str(self.page), "/")) if self.category: category = " category:" + self.category else: category = "" ...
Build and return url. Also update max_page.
entailment
def build(self, update=True): """ Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path """ query_str = "?page={}".format(self.page) if s...
Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path
entailment
def _items(self): """ Parse url and yield namedtuple Torrent for every torrent on page """ torrents = map(self._get_torrent, self._get_rows()) for t in torrents: yield t
Parse url and yield namedtuple Torrent for every torrent on page
entailment
def _get_torrent(self, row): """ Parse row into namedtuple """ td = row("td") name = td("a.cellMainLink").text() name = name.replace(" . ", ".").replace(" .", ".") author = td("a.plain").text() verified_author = True if td(".lightgrey>.ka-verify") else Fal...
Parse row into namedtuple
entailment
def _get_rows(self): """ Return all rows on page """ html = requests.get(self.url.build()).text if re.search('did not match any documents', html): return [] pq = PyQuery(html) rows = pq("table.data").find("tr") return map(rows.eq, range(rows.si...
Return all rows on page
entailment
def pages(self, page_from, page_to): """ Yield torrents in range from page_from to page_to """ if not all([page_from < self.url.max_page, page_from > 0, page_to <= self.url.max_page, page_to > page_from]): raise IndexError("Invalid page numbers") ...
Yield torrents in range from page_from to page_to
entailment
def all(self): """ Yield torrents in range from current page to last page """ return self.pages(self.url.page, self.url.max_page)
Yield torrents in range from current page to last page
entailment
def order(self, field, order=None): """ Set field and order set by arguments """ if not order: order = ORDER.DESC self.url.order = (field, order) self.url.set_page(1) return self
Set field and order set by arguments
entailment
def category(self, category): """ Change category of current search and return self """ self.url.category = category self.url.set_page(1) return self
Change category of current search and return self
entailment
def destroy(self): """ Remove this FirewallRule from the API. This instance must be associated with a server for this method to work, which is done by instantiating via server.get_firewall_rules(). """ if not hasattr(self, 'server') or not self.server: raise ...
Remove this FirewallRule from the API. This instance must be associated with a server for this method to work, which is done by instantiating via server.get_firewall_rules().
entailment
def fetch_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches new release categories by given ID. :param category_id: the station ID. :type category_id: str :param terr: the current territory. :return: API response. :rtype: list ...
Fetches new release categories by given ID. :param category_id: the station ID. :type category_id: str :param terr: the current territory. :return: API response. :rtype: list See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories-category_id`
entailment
def fetch_top_tracks_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN): ''' Fetcher top tracks belong to an artist by given ID. :param artist_id: the artist ID. :type artist_id: str :param terr: the current territory. :return: API response. :rtype: dict ...
Fetcher top tracks belong to an artist by given ID. :param artist_id: the artist ID. :type artist_id: str :param terr: the current territory. :return: API response. :rtype: dict See 'https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-toptracks'
entailment