text
stringlengths
81
112k
Run the callback def callback(self): '''Run the callback''' self._callback(*self._args, **self._kwargs) self._last_checked = time.time()
Run the callback periodically 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('Cal...
Login to MediaFire account. Keyword arguments: email -- account email password -- account password app_id -- application ID api_key -- API Key (optional) def login(self, email=None, password=None, app_id=None, api_key=None): """Login to MediaFire account. Keywo...
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...
Return resource by quick_key/folder_key. key -- quick_key or folder_key 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_k...
Return resource by remote path. path -- remote path Keyword arguments: folder_key -- what to use as the root folder (None for root) def get_resource_by_path(self, path, folder_key=None): """Return resource by remote path. path -- remote path Keyword arguments: ...
Iterator for api.folder_get_content 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...
Return iterator for directory contents. uri -- mediafire URI Example: for item in get_folder_contents_iter('mf:///Documents'): print(item) def get_folder_contents_iter(self, uri): """Return iterator for directory contents. uri -- mediafire URI Ex...
Create folder. uri -- MediaFire URI Keyword arguments: recursive -- set to True to create intermediate folders. def create_folder(self, uri, recursive=False): """Create folder. uri -- MediaFire URI Keyword arguments: recursive -- set to True to create interme...
Delete folder. uri -- MediaFire folder URI Keyword arguments: purge -- delete the folder without sending it to Trash def delete_folder(self, uri, purge=False): """Delete folder. uri -- MediaFire folder URI Keyword arguments: purge -- delete the folder without...
Delete file. uri -- MediaFire file URI Keyword arguments: purge -- delete the file without sending it to Trash. def delete_file(self, uri, purge=False): """Delete file. uri -- MediaFire file URI Keyword arguments: purge -- delete the file without sending it t...
Delete file or folder uri -- mediafire URI Keyword arguments: purge -- delete the resource without sending it to Trash. def delete_resource(self, uri, purge=False): """Delete file or folder uri -- mediafire URI Keyword arguments: purge -- delete the resource ...
Prepare Upload object, resolve paths 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, ...
Upload file to MediaFire. source -- path to the file or a file-like object (e.g. io.BytesIO) dest_uri -- MediaFire Resource URI 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 -- ...
Download file from MediaFire. src_uri -- MediaFire file URI to download target -- download path or file-like object in write mode def download_file(self, src_uri, target): """Download file from MediaFire. src_uri -- MediaFire file URI to download target -- download path or fil...
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...
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 ...
Parse and validate MediaFire URI. 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 ...
The clean stats from all the hosts reporting to this host. 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 = pr...
All the raw, unaggregated stats (with duplicates). def raw(self): '''All the raw, unaggregated stats (with duplicates).''' topic_keys = ( 'message_count', 'depth', 'backend_depth', 'paused' ) channel_keys = ( 'in_flight_count'...
Stats that have been aggregated appropriately. 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) dat...
Return the current python source line. 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.pat...
Subscribe connection and manipulate its RDY state def reconnected(self, conn): '''Subscribe connection and manipulate its RDY state''' conn.sub(self._topic, self._channel) conn.rdy(1)
Distribute the ready state across all of the connections 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( ...
Determine whether or not we need to redistribute the ready state 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.connec...
Read some number of messages 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 retu...
Profile the block 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()
Generator for count messages of the provided size 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 ...
Collect data into fixed-length chunks or blocks 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
Basic benchmark 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)...
Read a stream of floats and give summary statistics 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) ...
Whether or not enough time has passed since the last failure 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
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 ...
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. def execute_log(args, root_dir): """Print the current log file. Args: args['keys'] (int): If given, ...
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. def execute_show(args, root_dir):...
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`. def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches a...
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') def show(self, user, feed, id): """ Show a s...
Submit action on the Indicator object :return: Indicator Object def create(self): """ Submit action on the Indicator object :return: Indicator Object """ uri = '/users/{0}/feeds/{1}/indicators'\ .format(self.user, self.feed) data = { "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 ...
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...
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,...
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, ...
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 def lookup_string(conn, kstr): """ Finds the keycode associated with a string representation of a keysym. :param kstr: English r...
Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie 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...
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 def get_keyboard_mapping_unchecked(conn): """ Return an unchecked keyboard mapping cookie that can be used to fetch the table of keys...
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)...
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 def get_keycode(conn, keysym): """ ...
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...
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] def get_...
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...
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...
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...
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.) ...
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 def __regrab(changes): """ Takes a dictionary of changes...
Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite def get_storages(self, storage_type='normal'): """ Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, f...
Return a Storage object from the API. 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'])
Create a Storage object. Returns an object based on the API's response. 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'...
Modify a Storage object. Returns an object based on the API's response. 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) ...
Attach a Storage object to a Server. Return a list of the server's storages. 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: ...
Detach a Storage object to a Server. Return a list of the server's storages. 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...
Reset after repopulating from API. 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: ...
Save (modify) the storage to the API. Note: only size and title are updateable fields. 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) ...
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. def to_dict(self): """ Return a dict that can be serialised to JSON and sent to UpCloud's API. Uses the convenience attrib...
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`. def fetch_album(self, album_id, terr=KKBOXTerritor...
Prints name, author, size and age 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)
Open url and return amount of pages 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...
Build and return url. Also update max_page. 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 ...
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 def build(self, update=True): """ Build and return url. Also update max_page. URL structure for us...
Parse url and yield namedtuple Torrent for every torrent on page 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 row into namedtuple 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(".ligh...
Return all rows on page 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 m...
Yield torrents in range from page_from to page_to 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]): ...
Yield torrents in range from current page to last page def all(self): """ Yield torrents in range from current page to last page """ return self.pages(self.url.page, self.url.max_page)
Set field and order set by arguments 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
Change category of current search and return self def category(self, category): """ Change category of current search and return self """ self.url.category = category self.url.set_page(1) return 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(). def destroy(self): """ Remove this FirewallRule from the API. This instance must be associated with a ...
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` def fetch_ne...
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' def fetch_top_...
List all tags as Tag objects. def get_tags(self): """List all tags as Tag objects.""" res = self.get_request('/tag') return [Tag(cloud_manager=self, **tag) for tag in res['tags']['tag']]
Return the tag as Tag object. def get_tag(self, name): """Return the tag as Tag object.""" res = self.get_request('/tag/' + name) return Tag(cloud_manager=self, **res['tag'])
Create a new Tag. Only name is mandatory. Returns the created Tag object. def create_tag(self, name, description=None, servers=[]): """ Create a new Tag. Only name is mandatory. Returns the created Tag object. """ servers = [str(server) for server in servers] b...
PUT /tag/name. Returns a dict that can be used to create a Tag object. Private method used by the Tag class and TagManager.modify_tag. def _modify_tag(self, name, description, servers, new_name): """ PUT /tag/name. Returns a dict that can be used to create a Tag object. Private method...
PUT /tag/name. Returns a new Tag object based on the API response. def modify_tag(self, name, description=None, servers=None, new_name=None): """ PUT /tag/name. Returns a new Tag object based on the API response. """ res = self._modify_tag(name, description, servers, new_name) r...
Remove tags from a server. - server: Server object or UUID string - tags: list of Tag objects or strings def remove_tags(self, server, tags): """ Remove tags from a server. - server: Server object or UUID string - tags: list of Tag objects or strings """ ...
Helper for assigning object attributes from API responses. def assignIfExists(opts, default=None, **kwargs): """ Helper for assigning object attributes from API responses. """ for opt in opts: if(opt in kwargs): return kwargs[opt] return default
Try a given operation (API call) n times. Raises if the API call fails with an error_code that is not expected. Raises if the API call has not succeeded within n attempts. Waits 3 seconds betwee each attempt. def try_it_n_times(operation, expected_error_codes, custom_error='operation failed', n=10): "...
Extract a pseudorandom key suitable for use with hkdf_expand from the input_key_material and a salt using HMAC with the provided hash (default SHA-512). salt should be a random, application-specific byte string. If salt is None or the empty string, an all-zeros string of the same length as the hash's block size w...
Expand `pseudo_random_key` and `info` into a key of length `bytes` using HKDF's expand function based on HMAC with the provided hash (default SHA-512). See the HKDF draft RFC and paper for usage notes. def hkdf_expand(pseudo_random_key, info=b"", length=32, hash=hashlib.sha512): ''' Expand `pseudo_random_key` and ...
Generate output key material based on an `info` value Arguments: - info - context to generate the OKM - length - length in bytes of the key to generate See the HKDF draft RFC for guidance. def expand(self, info=b"", length=32): ''' Generate output key material based on an `info` value Arguments: - i...
Helper function for creating Server.login_user blocks. (see: https://www.upcloud.com/api/8-servers/#create-server) def login_user_block(username, ssh_keys, create_password=True): """ Helper function for creating Server.login_user blocks. (see: https://www.upcloud.com/api/8-servers/#create-server) ...
Reset the server object with new values given as params. - server: a dict representing the server. e.g the API response. - kwargs: any meta fields such as cloud_manager and populated. Note: storage_devices and ip_addresses may be given in server as dicts or in kwargs as lists containin...
Sync changes from the API to the local object. Note: syncs ip_addresses and storage_devices too (/server/uuid endpoint) def populate(self): """ Sync changes from the API to the local object. Note: syncs ip_addresses and storage_devices too (/server/uuid endpoint) """ s...
Sync local changes in server's attributes to the API. Note: DOES NOT sync IPAddresses and storage_devices, use add_ip, add_storage, remove_ip, remove_storage instead. def save(self): """ Sync local changes in server's attributes to the API. Note: DOES NOT sync IPAddresses and ...
Shutdown/stop the server. By default, issue a soft shutdown with a timeout of 30s. After the a timeout a hard shutdown is performed if the server has not stopped. Note: API responds immediately (unlike in start), with state: started. This client will, however, set state as 'maintenance' to sig...
Start the server. Note: slow and blocking request. The API waits for confirmation from UpCloud's IaaS backend before responding. def start(self, timeout=120): """ Start the server. Note: slow and blocking request. The API waits for confirmation from UpCloud's IaaS backend before respo...
Restart the server. By default, issue a soft restart with a timeout of 30s and a hard restart after the timeout. After the a timeout a hard restart is performed if the server has not stopped. Note: API responds immediately (unlike in start), with state: started. This client will, howev...
Allocate a new (random) IP-address to the Server. def add_ip(self, family='IPv4'): """ Allocate a new (random) IP-address to the Server. """ IP = self.cloud_manager.attach_ip(self.uuid, family) self.ip_addresses.append(IP) return IP
Release the specified IP-address from the server. def remove_ip(self, IPAddress): """ Release the specified IP-address from the server. """ self.cloud_manager.release_ip(IPAddress.address) self.ip_addresses.remove(IPAddress)
Attach the given storage to the Server. Default address is next available. def add_storage(self, storage=None, type='disk', address=None): """ Attach the given storage to the Server. Default address is next available. """ self.cloud_manager.attach_storage(server=self.u...
Remove Storage from a Server. The Storage must be a reference to an object in Server.storage_devices or the method will throw and Exception. A Storage from get_storage(uuid) will not work as it is missing the 'address' property. def remove_storage(self, storage): """ Remove St...