Search is not available for this dataset
text
stringlengths
75
104k
def do_down(self, arg): """d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame). """ if self.curindex + 1 == len(self.stack): self.error('Newest frame') return try: count = int(arg ...
def do_until(self, arg): """unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also sto...
def do_run(self, arg): """run [args...] Restart the debugged python program. If a string is supplied it is splitted with "shlex", and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run". ...
def do_jump(self, arg): """j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don't want to run. It should be noted that not all jumps are...
def do_debug(self, arg): """debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment). """ self.settrace(False) globals = self.curframe.f_globals loc...
def do_quit(self, arg): """q(uit)\nexit Quit from the debugger. The program being executed is aborted. """ if isinstance(self.stdin, RemoteSocket) and not self.is_debug_instance: return self.do_detach(arg) self._user_requested_quit = True self.set_quit() ...
def do_args(self, arg): """a(rgs) Print the argument list of the current function. """ co = self.curframe.f_code dict = self.get_locals(self.curframe) n = co.co_argcount if co.co_flags & 4: n = n+1 if co.co_flags & 8: n = n+1 for i in range(n): ...
def do_retval(self, arg): """retval Print the return value for the last return of a function. """ locals = self.get_locals(self.curframe) if '__return__' in locals: self.message(bdb.safe_repr(locals['__return__'])) else: self.error('Not yet returne...
def do_p(self, arg): """p expression Print the value of the expression. """ try: self.message(bdb.safe_repr(self._getval(arg))) except Exception: pass
def do_pp(self, arg): """pp expression Pretty-print the value of the expression. """ obj = self._getval(arg) try: repr(obj) except Exception: self.message(bdb.safe_repr(obj)) else: self.message(pprint.pformat(obj))
def do_list(self, arg): """l(ist) [first [,last] | .] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines ...
def do_longlist(self, arg): """longlist | ll List the whole source code for the current function or frame. """ filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: lines, lineno = getsourcelines(self.curframe, ...
def do_source(self, arg): """source expression Try to get source code for the given object and display it. """ try: obj = self._getval(arg) except Exception: return try: lines, lineno = getsourcelines(obj, self.get_locals(self.curframe)...
def _print_lines(self, lines, start, breaks=(), frame=None): """Print a range of lines.""" if frame: current_lineno = frame.f_lineno exc_lineno = self.tb_lineno.get(frame, -1) else: current_lineno = exc_lineno = -1 for lineno, line in enumerate(lines, ...
def do_whatis(self, arg): """whatis arg Print the type of the argument. """ try: value = self._getval(arg) except Exception: # _getval() already printed the error return code = None # Is it a function? try: c...
def do_display(self, arg): """display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame. """ if not arg: self.message('Curren...
def do_undisplay(self, arg): """undisplay [expression] Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame. """ if arg: try: del self.displaying.get(self.curframe, {})[a...
def do_interact(self, arg): """interact Start an interative interpreter whose global namespace contains all the (global and local) names found in the current scope. """ def readfunc(prompt): self.stdout.write(prompt) self.stdout.flush() line =...
def do_alias(self, arg): """alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the param...
def do_unalias(self, arg): """unalias name Delete the specified alias. """ args = arg.split() if len(args) == 0: return if args[0] in self.aliases: del self.aliases[args[0]]
def do_thread(self, arg): """th(read) [threadnumber] Without argument, display a summary of all active threads. The summary prints for each thread: 1. the thread number assigned by pdb 2. the thread name 3. the python thread identifier 4. the current s...
def do_help(self, arg): """h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. "help pdb" shows the full pdb documentation. "help exec" gives help on the ! command. """ if not arg: ...
def read(self, limit=-1): """Read content. See file.read""" remaining = self.len - self.parent_fd.tell() + self.offset if limit > remaining or limit == -1: limit = remaining return self.parent_fd.read(limit)
def seek(self, offset, whence=os.SEEK_SET): """Seek to position in stream, see file.seek""" pos = None if whence == os.SEEK_SET: pos = self.offset + offset elif whence == os.SEEK_CUR: pos = self.tell() + offset elif whence == os.SEEK_END: pos ...
def close(self): """Close file, see file.close""" try: self.parent_fd.fileno() except io.UnsupportedOperation: logger.debug("Not closing parent_fd - reusing existing") else: self.parent_fd.close()
def _build_query(self, uri, params=None, action_token_type=None): """Prepare query string""" if params is None: params = QueryParams() params['response_format'] = 'json' session_token = None if action_token_type in self._action_tokens: # Favor action t...
def request(self, action, params=None, action_token_type=None, upload_info=None, headers=None): """Perform request to MediaFire API action -- "category/name" of method to call params -- dict of parameters or query string action_token_type -- action token to use: None, "u...
def _process_response(self, response): """Parse response""" forward_raw = False content_type = response.headers['Content-Type'] if content_type != 'application/json': logger.debug("headers: %s", response.headers) # API BUG: text/xml content-type with json payload...
def _regenerate_secret_key(self): """Regenerate secret key http://www.mediafire.com/developers/core_api/1.3/getting_started/#call_signature """ # Don't regenerate the key if we have none if self._session and 'secret_key' in self._session: self._session['secret_key'] ...
def session(self, value): """Set session token value -- dict returned by user/get_session_token""" # unset session token if value is None: self._session = None return if not isinstance(value, dict): raise ValueError("session info is required...
def set_action_token(self, type_=None, action_token=None): """Set action tokens type_ -- either "upload" or "image" action_token -- string obtained from user/get_action_token, set None to remove the token """ if action_token is None: del self....
def user_get_session_token(self, app_id=None, email=None, password=None, ekey=None, fb_access_token=None, tw_oauth_token=None, tw_oauth_token_secret=None, api_key=None): """user/get_session_token http://www.med...
def user_set_avatar(self, action=None, quick_key=None, url=None): """user/set_avatar http://www.mediafire.com/developers/core_api/1.3/user/#set_avatar """ return self.request("user/set_avatar", QueryParams({ "action": action, "quick_key": quick_key, "...
def user_update(self, display_name=None, first_name=None, last_name=None, email=None, password=None, current_password=None, birth_date=None, gender=None, website=None, subdomain=None, location=None, newsletter=None, primary_usage=None, time...
def folder_get_info(self, folder_key=None, device_id=None, details=None): """folder/get_info http://www.mediafire.com/developers/core_api/1.3/folder/#get_info """ return self.request('folder/get_info', QueryParams({ 'folder_key': folder_key, 'device_id': device_i...
def folder_get_content(self, folder_key=None, content_type=None, filter_=None, device_id=None, order_by=None, order_direction=None, chunk=None, details=None, chunk_size=None): """folder/get_content http://www.mediafire.com...
def folder_update(self, folder_key, foldername=None, description=None, privacy=None, privacy_recursive=None, mtime=None): """folder/update http://www.mediafire.com/developers/core_api/1.3/folder/#update """ return self.request('folder/update', QueryParams({ ...
def folder_create(self, foldername=None, parent_key=None, action_on_duplicate=None, mtime=None): """folder/create http://www.mediafire.com/developers/core_api/1.3/folder/#create """ return self.request('folder/create', QueryParams({ 'foldername': folder...
def upload_check(self, filename=None, folder_key=None, filedrop_key=None, size=None, hash_=None, path=None, resumable=None): """upload/check http://www.mediafire.com/developers/core_api/1.3/upload/#check """ return self.request('upload/check', QueryParams({ ...
def upload_simple(self, fd, filename, folder_key=None, path=None, filedrop_key=None, action_on_duplicate=None, mtime=None, file_size=None, file_hash=None): """upload/simple http://www.mediafire.com/developers/core_api/1.3/upload/#simple """ ac...
def upload_resumable(self, fd, filesize, filehash, unit_hash, unit_id, unit_size, quick_key=None, action_on_duplicate=None, mtime=None, version_control=None, folder_key=None, filedrop_key=None, path=None, previous_hash=None): """upload/r...
def upload_instant(self, filename, size, hash_, quick_key=None, folder_key=None, filedrop_key=None, path=None, action_on_duplicate=None, mtime=None, version_control=None, previous_hash=None): """upload/instant http://www.mediafire.com...
def file_update(self, quick_key, filename=None, description=None, mtime=None, privacy=None): """file/update http://www.mediafire.com/developers/core_api/1.3/file/#update """ return self.request('file/update', QueryParams({ 'quick_key': quick_key, ...
def file_update_file(self, quick_key, file_extension=None, filename=None, description=None, mtime=None, privacy=None, timezone=None): """file/update_file http://www.mediafire.com/developers/core_api/1.3/file/#update_file """ return self....
def file_zip(self, keys, confirm_download=None, meta_only=None): """file/zip http://www.mediafire.com/developers/core_api/1.3/file/#zip """ return self.request('file/zip', QueryParams({ 'keys': keys, 'confirm_download': confirm_download, 'meta_only': ...
def _reset(self): '''Reset all of our stateful variables''' self._socket = None # The pending messages we have to send, and the current buffer we're # sending self._pending = deque() self._out_buffer = '' # Our read buffer self._buffer = '' # The i...
def connect(self, force=False): '''Establish a connection''' # Don't re-establish existing connections if not force and self.alive(): return True self._reset() # Otherwise, try to connect with self._socket_lock: try: logger.info('...
def close(self): '''Close our connection''' # Flush any unsent message try: while self.pending(): self.flush() except socket.error: pass with self._socket_lock: try: if self._socket: self._soc...
def socket(self, blocking=True): '''Blockingly yield the socket''' # If the socket is available, then yield it. Otherwise, yield nothing if self._socket_lock.acquire(blocking): try: yield self._socket finally: self._socket_lock.release()
def identified(self, res): '''Handle a response to our 'identify' command. Returns response''' # If they support it, they should give us a JSON blob which we should # inspect. try: res.data = json.loads(res.data) self._identify_response = res.data logg...
def setblocking(self, blocking): '''Set whether or not this message is blocking''' for sock in self.socket(): sock.setblocking(blocking) self._blocking = blocking
def flush(self): '''Flush some of the waiting messages, returns count written''' # When profiling, we found that while there was some efficiency to be # gained elsewhere, the big performance hit is sending lots of small # messages at a time. In particular, consumers send many 'FIN' messa...
def send(self, command, message=None): '''Send a command over the socket with length endcoded''' if message: joined = command + constants.NL + util.pack(message) else: joined = command + constants.NL if self._blocking: for sock in self.socket(): ...
def identify(self, data): '''Send an identification message''' return self.send(constants.IDENTIFY, json.dumps(data))
def sub(self, topic, channel): '''Subscribe to a topic/channel''' return self.send(' '.join((constants.SUB, topic, channel)))
def pub(self, topic, message): '''Publish to a topic''' return self.send(' '.join((constants.PUB, topic)), message)
def mpub(self, topic, *messages): '''Publish multiple messages to a topic''' return self.send(constants.MPUB + ' ' + topic, messages)
def rdy(self, count): '''Indicate that you're ready to receive''' self.ready = count self.last_ready_sent = count return self.send(constants.RDY + ' ' + str(count))
def req(self, message_id, timeout): '''Re-queue a message''' return self.send(constants.REQ + ' ' + message_id + ' ' + str(timeout))
def _read(self, limit=1000): '''Return all the responses read''' # It's important to know that it may return no responses or multiple # responses. It depends on how the buffering works out. First, read from # the socket for sock in self.socket(): if sock is None: ...
def read(self): '''Responses from an established socket''' responses = self._read() # Determine the number of messages in here and decrement our ready # count appropriately self.ready -= sum( map(int, (r.frame_type == Message.FRAME_TYPE for r in responses))) r...
def discover(self, topic): '''Run the discovery mechanism''' logger.info('Discovering on topic %s', topic) producers = [] for lookupd in self._lookupd: logger.info('Discovering on %s', lookupd) try: # Find all the current producers on this instance...
def check_connections(self): '''Connect to all the appropriate instances''' logger.info('Checking connections') if self._lookupd: self.discover(self._topic) # Make sure we're connected to all the prescribed hosts for hostspec in self._nsqd_tcp_addresses: ...
def connection_checker(self): '''Run periodic reconnection checks''' thread = ConnectionChecker(self) logger.info('Starting connection-checker thread') thread.start() try: yield thread finally: logger.info('Stopping connection-checker') ...
def connect(self, host, port): '''Connect to the provided host, port''' conn = connection.Connection(host, port, reconnection_backoff=self._reconnection_backoff, auth_secret=self._auth_secret, timeout=self._connect_timeout, **self._identify_options) ...
def add(self, connection): '''Add a connection''' key = (connection.host, connection.port) with self._lock: if key not in self._connections: self._connections[key] = connection self.added(connection) return connection else: ...
def remove(self, connection): '''Remove a connection''' key = (connection.host, connection.port) with self._lock: found = self._connections.pop(key, None) try: self.close_connection(found) except Exception as exc: logger.warn('Failed to close %...
def read(self): '''Read from any of the connections that need it''' # We'll check all living connections connections = [c for c in self.connections() if c.alive()] if not connections: # If there are no connections, obviously we return no messages, but # we should...
def random_connection(self): '''Pick a random living connection''' # While at the moment there's no need for this to be a context manager # per se, I would like to use that interface since I anticipate # adding some wrapping around it at some point. yield random.choice( ...
def wait_response(self): '''Wait for a response''' responses = self.read() while not responses: responses = self.read() return responses
def pub(self, topic, message): '''Publish the provided message to the provided topic''' with self.random_connection() as client: client.pub(topic, message) return self.wait_response()
def mpub(self, topic, *messages): '''Publish messages to a topic''' with self.random_connection() as client: client.mpub(topic, *messages) return self.wait_response()
def create_socket(self): """Create a socket for the daemon, depending on the directory location. Args: config_dir (str): The absolute path to the config directory used by the daemon. Returns: socket.socket: The daemon socket. Clients connect to this socket. """...
def initialize_directories(self, root_dir): """Create all directories needed for logs and configs.""" if not root_dir: root_dir = os.path.expanduser('~') # Create config directory, if it doesn't exist self.config_dir = os.path.join(root_dir, '.config/pueue') if not o...
def respond_client(self, answer, socket): """Send an answer to the client.""" response = pickle.dumps(answer, -1) socket.sendall(response) self.read_list.remove(socket) socket.close()
def read_config(self): """Read a previous configuration file or create a new with default values.""" config_file = os.path.join(self.config_dir, 'pueue.ini') self.config = configparser.ConfigParser() # Try to get configuration file and return it # If this doesn't work, a new defa...
def write_config(self): """Write the current configuration to the config file.""" config_file = os.path.join(self.config_dir, 'pueue.ini') with open(config_file, 'w') as file_descriptor: self.config.write(file_descriptor)
def main(self): """The main function containing the loop for communication and process management. This function is the heart of the daemon. It is responsible for: - Client communication - Executing commands from clients - Update the status of processes by polling the Pr...
def stop_daemon(self, payload=None): """Kill current processes and initiate daemon shutdown. The daemon will shut down after a last check on all killed processes. """ kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.running = False ...
def set_config(self, payload): """Update the current config depending on the payload and save it.""" self.config['default'][payload['option']] = str(payload['value']) if payload['option'] == 'maxProcesses': self.process_handler.set_max(payload['value']) if payload['option'] ...
def pipe_to_process(self, payload): """Send something to stdin of a specific process.""" message = payload['input'] key = payload['key'] if not self.process_handler.is_running(key): return {'message': 'No running process for this key', 'status': 'error'} ...
def send_status(self, payload): """Send the daemon status and the current queue for displaying.""" answer = {} data = [] # Get daemon status if self.paused: answer['status'] = 'paused' else: answer['status'] = 'running' # Add current queue...
def reset_everything(self, payload): """Kill all processes, delete the queue and clean everything up.""" kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.process_handler.wait_for_finish() self.reset = True answer = {'message': 'Resetting c...
def clear(self, payload): """Clear queue from any `done` or `failed` entries. The log will be rotated once. Otherwise we would loose all logs from thoes finished processes. """ self.logger.rotate(self.queue) self.queue.clear() self.logger.write(self.queue) ...
def start(self, payload): """Start the daemon and all processes or only specific processes.""" # Start specific processes, if `keys` is given in the payload if payload.get('keys'): succeeded = [] failed = [] for key in payload.get('keys'): succ...
def pause(self, payload): """Start the daemon and all processes or only specific processes.""" # Pause specific processes, if `keys` is given in the payload if payload.get('keys'): succeeded = [] failed = [] for key in payload.get('keys'): succ...
def edit_command(self, payload): """Edit the command of a specific entry.""" key = payload['key'] command = payload['command'] if self.queue[key]: if self.queue[key]['status'] in ['queued', 'stashed']: self.queue[key]['command'] = command answe...
def stash(self, payload): """Stash the specified processes.""" succeeded = [] failed = [] for key in payload['keys']: if self.queue.get(key) is not None: if self.queue[key]['status'] == 'queued': self.queue[key]['status'] = 'stashed' ...
def kill_process(self, payload): """Pause the daemon and kill all processes or kill a specific process.""" # Kill specific processes, if `keys` is given in the payload kill_signal = signals[payload['signal'].lower()] kill_shell = payload.get('all', False) if payload.get('keys'): ...
def remove(self, payload): """Remove specified entries from the queue.""" succeeded = [] failed = [] for key in payload['keys']: running = self.process_handler.is_running(key) if not running: removed = self.queue.remove(key) if remo...
def switch(self, payload): """Switch the two specified entry positions in the queue.""" first = payload['first'] second = payload['second'] running = self.process_handler.is_running(first) or self.process_handler.is_running(second) if running: answer = { ...
def restart(self, payload): """Restart the specified entries.""" succeeded = [] failed = [] for key in payload['keys']: restarted = self.queue.restart(key) if restarted: succeeded.append(str(key)) else: failed.append(str...
def sendall(self, data, flags=0): '''Same as socket.sendall''' count = len(data) while count: sent = self.send(data, flags) # This could probably be a buffer object data = data[sent:] count -= sent
def do_ls(client, args): """List directory""" for item in client.get_folder_contents_iter(args.uri): # privacy flag if item['privacy'] == 'public': item['pf'] = '@' else: item['pf'] = '-' if isinstance(item, Folder): # type flag i...
def do_file_upload(client, args): """Upload files""" # Sanity check if len(args.paths) > 1: # destination must be a directory try: resource = client.get_resource_by_uri(args.dest_uri) except ResourceNotFoundError: resource = None if resource and not ...
def do_file_download(client, args): """Download file""" # Sanity check if not os.path.isdir(args.dest_path) and not args.dest_path.endswith('/'): print("file-download: " "target '{}' is not a directory".format(args.dest_path)) if not os.path.exists(args.dest_path): ...
def do_file_show(client, args): """Output file contents to stdout""" for src_uri in args.uris: client.download_file(src_uri, sys.stdout.buffer) return True
def do_folder_create(client, args): """Create directory""" for folder_uri in args.uris: client.create_folder(folder_uri, recursive=True) return True
def do_resource_delete(client, args): """Remove resource""" for resource_uri in args.uris: client.delete_resource(resource_uri, purge=args.purge) print("Deleted {}".format(resource_uri)) return True
def do_file_update_metadata(client, args): """Update file metadata""" client.update_file_metadata(args.uri, filename=args.filename, description=args.description, mtime=args.mtime, privacy=args.privacy) return True