INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the output of the wrapped PyTorch model for the given input along with a callback to handle the backward pass.
def begin_update(self, x_data, h_0=None, drop=0.0): """Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass. """ x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True) # Make prediction out, ...
Wrap a function into a layer
def layerize(begin_update=None, predict=None, *args, **kwargs): """Wrap a function into a layer""" if begin_update is not None: return FunctionLayer(begin_update, predict=predict, *args, **kwargs) def wrapper(begin_update): return FunctionLayer(begin_update, *args, **kwargs) return wra...
Wrap a function over a sequence of layers and an input into a layer.
def metalayerize(user_func): """Wrap a function over a sequence of layers and an input into a layer.""" def returned(layers, *args, **kwargs): def begin_update(X, *args, **kwargs): return user_func(layers, X, *args, **kwargs) return FunctionLayer(begin_update, *args, **kwargs) ...
Transform a sequences of layers into a null operation.
def noop(*layers): """Transform a sequences of layers into a null operation.""" def begin_update(X, drop=0.0): return X, lambda D, *a, **k: D return begin_update
Compose two models f and g such that they become layers of a single feed - forward model that computes g ( f ( x )).
def chain(*layers): """Compose two models `f` and `g` such that they become layers of a single feed-forward model that computes `g(f(x))`. Raises exception if their dimensions don't match. """ if len(layers) == 0: return FeedForward([]) elif len(layers) == 1: return layers[0] ...
Construct n copies of a layer with distinct weights.
def clone(orig, n): """Construct `n` copies of a layer, with distinct weights. i.e. `clone(f, 3)(x)` computes `f(f'(f''(x)))`. """ if n == 0: return layerize(noop()) layers = [orig] for i in range(n - 1): layers.append(copy.deepcopy(orig)) layers[-1].set_id() return ...
Compose two or more models f g etc such that their outputs are concatenated i. e. concatenate ( f g ) ( x ) computes hstack ( f ( x ) g ( x ))
def concatenate(*layers): # pragma: no cover """Compose two or more models `f`, `g`, etc, such that their outputs are concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))` """ if not layers: return noop() ops = layers[0].ops def begin_update(X, *a, **k): forwa...
Separate a sequence of layers begin_update methods into two lists of functions: one that computes the forward values and the other that completes the backward pass. The backward sequence is only populated after the forward functions have been applied.
def split_backward(layers): # pragma: no cover """Separate a sequence of layers' `begin_update` methods into two lists of functions: one that computes the forward values, and the other that completes the backward pass. The backward sequence is only populated after the forward functions have been applie...
Transform a function func that returns tuples into a function that returns single values. Call a function sink on the unused values.
def sink_return(func, sink, splitter=None): # pragma: no cover """Transform a function `func` that returns tuples into a function that returns single values. Call a function `sink` on the unused values. """ def wrap(*args, **kwargs): output = func(*args, **kwargs) if splitter is None: ...
Group inputs to a layer so that the layer only has to compute for the unique values. The data is transformed back before output and the same transformation is applied for the gradient. Effectively this is a cache local to each minibatch.
def uniqued(layer, column=0): """Group inputs to a layer, so that the layer only has to compute for the unique values. The data is transformed back before output, and the same transformation is applied for the gradient. Effectively, this is a cache local to each minibatch. The uniqued wrapper is us...
Map a layer across list items
def foreach(layer, drop_factor=1.0): """Map a layer across list items""" def foreach_fwd(docs, drop=0.0): sents = [] lengths = [] for doc in docs: doc_sents = [sent for sent in doc if len(sent)] subset = [ s for s in doc_sents if numpy.random.rand...
Map a layer across sentences ( assumes spaCy - esque. sents interface )
def foreach_sentence(layer, drop_factor=1.0): """Map a layer across sentences (assumes spaCy-esque .sents interface)""" def sentence_fwd(docs, drop=0.0): sents = [] lengths = [] for doc in docs: doc_sents = [sent for sent in doc.sents if len(sent)] subset = [ ...
Serialize user defined function.
def func_dump(func): '''Serialize user defined function.''' code = marshal.dumps(func.__code__).decode('raw_unicode_escape') defaults = func.__defaults__ if func.__closure__: closure = tuple(c.cell_contents for c in func.__closure__) else: closure = None return code, defaults, cl...
Deserialize user defined function.
def func_load(code, defaults=None, closure=None, globs=None): '''Deserialize user defined function.''' if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code code = marshal.loads(code.encode('raw_unicode_escape')) if globs is None: globs = globals() ...
Parse the texts with spaCy. Make one - hot vectors for the labels.
def preprocess(ops, nlp, rows, get_ids): """Parse the texts with spaCy. Make one-hot vectors for the labels.""" Xs = [] ys = [] for (text1, text2), label in rows: Xs.append((get_ids([nlp(text1)])[0], get_ids([nlp(text2)])[0])) ys.append(label) return Xs, to_categorical(ys, nb_classes...
Create a bidirectional LSTM layer. Args: number out number in
def BiLSTM(nO, nI): """Create a bidirectional LSTM layer. Args: number out, number in""" return Bidirectional(LSTM(nO // 2, nI), LSTM(nO // 2, nI))
Create an LSTM layer. Args: number out number in
def LSTM(nO, nI): """Create an LSTM layer. Args: number out, number in""" weights = LSTM_weights(nO, nI) gates = LSTM_gates(weights.ops) return Recurrent(RNN_step(weights, gates))
Stitch two RNN models into a bidirectional layer.
def Bidirectional(l2r, r2l): """Stitch two RNN models into a bidirectional layer.""" nO = l2r.nO def birnn_fwd(Xs, drop=0.0): l2r_Zs, bp_l2r_Zs = l2r.begin_update(Xs, drop=drop) r2l_Zs, bp_r2l_Zs = r2l.begin_update( [l2r.ops.xp.ascontiguousarray(X[::-1]) for X in Xs] ) ...
Apply a stepwise model over a sequence maintaining state. For RNNs
def Recurrent(step_model): """Apply a stepwise model over a sequence, maintaining state. For RNNs""" ops = step_model.ops def recurrent_fwd(seqs, drop=0.0): lengths = [len(X) for X in seqs] X, size_at_t, unpad = ops.square_sequences(seqs) Y = ops.allocate((X.shape[0], X.shape[1], st...
Create a step model for an RNN given weights and gates functions.
def RNN_step(weights, gates): """Create a step model for an RNN, given weights and gates functions.""" def rnn_step_fwd(prevstate_inputs, drop=0.0): prevstate, inputs = prevstate_inputs cell_tm1, hidden_tm1 = prevstate acts, bp_acts = weights.begin_update((inputs, hidden_tm1), drop=dro...
Downloads a file from a URL if it not already in the cache.
def get_file(fname, origin, untar=False, unzip=False, md5_hash=None, cache_subdir='datasets'): '''Downloads a file from a URL if it not already in the cache. Passing the MD5 hash will verify the file after download as well as if it is already present in the cache. # Arguments fname: n...
Validates a file against a MD5 hash
def validate_file(fpath, md5_hash): '''Validates a file against a MD5 hash # Arguments fpath: path to the file being validated md5_hash: the MD5 hash being validated against # Returns Whether the file is valid ''' hasher = hashlib.md5() with open(fpath, 'rb') as f: ...
Get word forms.
def Orth(docs, drop=0.0): """Get word forms.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.orth i += 1 return ids, None
Get word shapes.
def Shape(docs, drop=0.0): """Get word shapes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.shape i += 1 return ids, None
Get prefixes.
def Prefix(docs, drop=0.0): """Get prefixes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.prefix i += 1 return ids, None
Get suffixes.
def Suffix(docs, drop=0.0): """Get suffixes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.suffix i += 1 return ids, None
Print training progress. Called after each epoch.
def track_progress(**context): """Print training progress. Called after each epoch.""" model = context["model"] train_X = context["train_X"] dev_X = context["dev_X"] dev_y = context["dev_y"] n_train = len(train_X) trainer = context["trainer"] def each_epoch(): global epoch_train...
Parse the texts with spaCy. Make one - hot vectors for the labels.
def preprocess(ops, nlp, rows, get_ids): """Parse the texts with spaCy. Make one-hot vectors for the labels.""" Xs = [] ys = [] for (text1, text2), label in rows: Xs.append((get_ids([nlp(text1)])[0], get_ids([nlp(text2)])[0])) ys.append(label) return Xs, ops.asarray(ys, dtype="float3...
Check whether an array is a cupy array
def is_cupy_array(arr): """Check whether an array is a cupy array""" if cupy is None: return False elif isinstance(arr, cupy.ndarray): return True else: return False
Use GPU if it s available. Returns True if so False otherwise.
def prefer_gpu(): """Use GPU if it's available. Returns True if so, False otherwise.""" from ._classes.model import Model from .ops import CupyOps if CupyOps.xp is not None: Model.Ops = CupyOps Model.ops = CupyOps() return True else: return False
Pad sentence sequences with EOL markers.
def mark_sentence_boundaries(sequences, drop=0.0): # pragma: no cover """Pad sentence sequences with EOL markers.""" for sequence in sequences: sequence.insert(0, "-EOL-") sequence.insert(0, "-EOL-") sequence.append("-EOL-") sequence.append("-EOL-") return sequences, None
Important: Fragmented ( = continuation ) messages are not supported since their usage cases are limited - when we don t know the payload length.
def send_text(self, message, opcode=OPCODE_TEXT): """ Important: Fragmented(=continuation) messages are not supported since their usage cases are limited - when we don't know the payload length. """ # Validate message if isinstance(message, bytes): message = ...
Main function.
def main(): """Main function.""" # Get the command line arg args = docopt(__doc__, version="Mackup {}".format(VERSION)) mckp = Mackup() app_db = ApplicationsDatabase() def printAppHeader(app_name): if verbose: print(("\n{0} {1} {0}").format(header("---"), bold(app_name))) ...
Get home and mackup filepaths for given file
def getFilepaths(self, filename): """ Get home and mackup filepaths for given file Args: filename (str) Returns: home_filepath, mackup_filepath (str, str) """ return (os.path.join(os.environ['HOME'], filename), os.path.join(self.m...
Backup the application config files.
def backup(self): """ Backup the application config files. Algorithm: if exists home/file if home/file is a real file if exists mackup/file are you sure ? if sure rm mackup/file ...
Restore the application config files.
def restore(self): """ Restore the application config files. Algorithm: if exists mackup/file if exists home/file are you sure ? if sure rm home/file link mackup/file home/file else ...
Uninstall Mackup.
def uninstall(self): """ Uninstall Mackup. Restore any file where it was before the 1st Mackup backup. Algorithm: for each file in config if mackup/file exists if home/file exists delete home/file ...
Check if the current env is usable and has everything s required.
def check_for_usable_environment(self): """Check if the current env is usable and has everything's required.""" # Do not let the user run Mackup as root if os.geteuid() == 0: utils.error("Running Mackup as a superuser is useless and" " dangerous. Don't do it!"...
Check if the current env can be used to restore files.
def check_for_usable_restore_env(self): """Check if the current env can be used to restore files.""" self.check_for_usable_environment() if not os.path.isdir(self.mackup_folder): utils.error("Unable to find the Mackup folder: {}\n" "You might want to back up ...
If the Mackup home folder does not exist create it.
def create_mackup_home(self): """If the Mackup home folder does not exist, create it.""" if not os.path.isdir(self.mackup_folder): if utils.confirm("Mackup needs a directory to store your" " configuration files\n" "Do you want to crea...
Get the list of applications that should be backed up by Mackup.
def get_apps_to_backup(self): """ Get the list of applications that should be backed up by Mackup. It's the list of allowed apps minus the list of ignored apps. Returns: (set) List of application names to back up """ # Instantiate the app db app_db =...
Return the application configuration files.
def get_config_files(): """ Return the application configuration files. Return a list of configuration files describing the apps supported by Mackup. The files return are absolute full path to those files. e.g. /usr/lib/mackup/applications/bash.cfg Only one config file ...
Return application names.
def get_app_names(self): """ Return application names. Return the list of application names that are available in the database. Returns: set of str. """ app_names = set() for name in self.apps: app_names.add(name) return ...
Return the list of pretty app names that are available in the database.
def get_pretty_app_names(self): """ Return the list of pretty app names that are available in the database. Returns: set of str. """ pretty_app_names = set() for app_name in self.get_app_names(): pretty_app_names.add(self.get_name(app_name)) ...
Ask the user if he really want something to happen.
def confirm(question): """ Ask the user if he really want something to happen. Args: question(str): What can happen Returns: (boolean): Confirmed or not """ if FORCE_YES: return True while True: answer = input(question + ' <Yes|No>').lower() if ans...
Delete the given file directory or link.
def delete(filepath): """ Delete the given file, directory or link. It Should support undelete later on. Args: filepath (str): Absolute full path to a file. e.g. /path/to/file """ # Some files have ACLs, let's remove them recursively remove_acl(filepath) # Some files have immu...
Copy a file or a folder ( recursively ) from src to dst.
def copy(src, dst): """ Copy a file or a folder (recursively) from src to dst. For simplicity sake, both src and dst must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. copy('/path/to/src_file', '/path/to/dst_file') or cop...
Create a link to a target file or a folder.
def link(target, link_to): """ Create a link to a target file or a folder. For simplicity sake, both target and link_to must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. link('/path/to/file', '/path/to/link') But not: l...
Recursively set the chmod for files to 0600 and 0700 for folders.
def chmod(target): """ Recursively set the chmod for files to 0600 and 0700 for folders. It's ok unless we need something more specific. Args: target (str): Root file or folder """ assert isinstance(target, str) assert os.path.exists(target) file_mode = stat.S_IRUSR | stat.S_I...
Throw an error with the given message and immediately quit.
def error(message): """ Throw an error with the given message and immediately quit. Args: message(str): The message to display. """ fail = '\033[91m' end = '\033[0m' sys.exit(fail + "Error: {}".format(message) + end)
Try to locate the Dropbox folder.
def get_dropbox_folder_location(): """ Try to locate the Dropbox folder. Returns: (str) Full path to the current Dropbox folder """ host_db_path = os.path.join(os.environ['HOME'], '.dropbox/host.db') try: with open(host_db_path, 'r') as f_hostdb: data = f_hostdb.read...
Try to locate the Google Drive folder.
def get_google_drive_folder_location(): """ Try to locate the Google Drive folder. Returns: (str) Full path to the current Google Drive folder """ gdrive_db_path = 'Library/Application Support/Google/Drive/sync_config.db' yosemite_gdrive_db_path = ('Library/Application Support/Google/Dr...
Try to locate the Box folder.
def get_box_folder_location(): """ Try to locate the Box folder. Returns: (str) Full path to the current Box folder """ box_prefs_path = ('Library/Application Support/Box/Box Sync/' 'sync_root_folder.txt') box_home = None box_prefs = os.path.join(os.environ['H...
Try to locate the Copy folder.
def get_copy_folder_location(): """ Try to locate the Copy folder. Returns: (str) Full path to the current Copy folder """ copy_settings_path = 'Library/Application Support/Copy Agent/config.db' copy_home = None copy_settings = os.path.join(os.environ['HOME'], copy_settings_path) ...
Try to locate the iCloud Drive folder.
def get_icloud_folder_location(): """ Try to locate the iCloud Drive folder. Returns: (str) Full path to the iCloud Drive folder. """ yosemite_icloud_path = '~/Library/Mobile Documents/com~apple~CloudDocs/' icloud_home = os.path.expanduser(yosemite_icloud_path) if not os.path.isdi...
Check if a process with the given name is running.
def is_process_running(process_name): """ Check if a process with the given name is running. Args: (str): Process name, e.g. "Sublime Text" Returns: (bool): True if the process is running """ is_running = False # On systems with pgrep, check if the given process is running...
Remove the ACL of the file or folder located on the given path.
def remove_acl(path): """ Remove the ACL of the file or folder located on the given path. Also remove the ACL of any file and folder below the given one, recursively. Args: path (str): Path to the file or folder to remove the ACL for, recursively. """ # Some fil...
Check if the given path can be synced locally.
def can_file_be_synced_on_current_platform(path): """ Check if the given path can be synced locally. Check if it makes sense to sync the file at the given path on the current platform. For now we don't sync any file in the ~/Library folder on GNU/Linux. There might be other exceptions in the fu...
Full path to the Mackup configuration files.
def fullpath(self): """ Full path to the Mackup configuration files. The full path to the directory when Mackup is storing the configuration files. Returns: str """ return str(os.path.join(self.path, self.directory))
Configure the ConfigParser instance the way we want it.
def _setup_parser(self, filename=None): """ Configure the ConfigParser instance the way we want it. Args: filename (str) or None Returns: SafeConfigParser """ assert isinstance(filename, str) or filename is None # If we are not overridin...
Warn the user if an old config format is detected.
def _warn_on_old_config(self): """Warn the user if an old config format is detected.""" # Is an old setion is in the config file ? old_sections = ['Allowed Applications', 'Ignored Applications'] for old_section in old_sections: if self._parser.has_section(old_section): ...
Parse the storage engine in the config.
def _parse_engine(self): """ Parse the storage engine in the config. Returns: str """ if self._parser.has_option('storage', 'engine'): engine = str(self._parser.get('storage', 'engine')) else: engine = ENGINE_DROPBOX assert is...
Parse the storage path in the config.
def _parse_path(self): """ Parse the storage path in the config. Returns: str """ if self.engine == ENGINE_DROPBOX: path = get_dropbox_folder_location() elif self.engine == ENGINE_GDRIVE: path = get_google_drive_folder_location() ...
Parse the storage directory in the config.
def _parse_directory(self): """ Parse the storage directory in the config. Returns: str """ if self._parser.has_option('storage', 'directory'): directory = self._parser.get('storage', 'directory') # Don't allow CUSTOM_APPS_DIR as a storage dir...
Parse the applications to ignore in the config.
def _parse_apps_to_ignore(self): """ Parse the applications to ignore in the config. Returns: set """ # We ignore nothing by default apps_to_ignore = set() # Is the "[applications_to_ignore]" in the cfg file ? section_title = 'applications_to...
Parse the applications to backup in the config.
def _parse_apps_to_sync(self): """ Parse the applications to backup in the config. Returns: set """ # We allow nothing by default apps_to_sync = set() # Is the "[applications_to_sync]" section in the cfg file ? section_title = 'applications_t...
Build tabula - py option from template file
def load_template(path_or_buffer): '''Build tabula-py option from template file Args: file_like_obj: File like object of Tabula app template Returns: `obj`:dict: tabula-py options ''' from itertools import groupby from operator import itemgetter path_or_buffer = _stringif...
Convert Tabula app template to tabula - py option
def _convert_template_option(template): '''Convert Tabula app template to tabula-py option Args: template (dict): Tabula app template Returns: `obj`:dict: tabula-py option ''' option = {} extraction_method = template.get('extraction_method') if extraction_method == 'guess'...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.
def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def newFunc(*args, **kwargs): warnings.warn("Call to deprecated function {}.".format(func.__name__), cate...
Call tabula - java with the given lists of Java options and tabula - py options as well as an optional path to pass to tabula - java as a regular argument and an optional encoding to use for any required output sent to stderr.
def _run(java_options, options, path=None, encoding='utf-8'): """Call tabula-java with the given lists of Java options and tabula-py options, as well as an optional path to pass to tabula-java as a regular argument and an optional encoding to use for any required output sent to stderr. tabula-py op...
Read tables in PDF.
def read_pdf(input_path, output_format='dataframe', encoding='utf-8', java_options=None, pandas_options=None, multiple_tables=False, **kwargs): '''Read tables in PDF. Args: input_path (file like obj): File like object of tareg...
Read tables in PDF.
def read_pdf_with_template( input_path, template_path, pandas_options=None, encoding='utf-8', java_options=None, **kwargs): '''Read tables in PDF. Args: input_path (file like obj): File like object of tareget PDF file. template_path (f...
Convert tables from PDF into a file.
def convert_into(input_path, output_path, output_format='csv', java_options=None, **kwargs): '''Convert tables from PDF into a file. Args: input_path (file like obj): File like object of tareget PDF file. output_path (str): File path of output file. output_format...
Convert tables from PDFs in a directory.
def convert_into_by_batch(input_dir, output_format='csv', java_options=None, **kwargs): '''Convert tables from PDFs in a directory. Args: input_dir (str): Directory path. output_format (str, optional): Output format of this function (csv, json or tsv) java_option...
Extract tables from json.
def _extract_from(raw_json, pandas_options=None): '''Extract tables from json. Args: raw_json (list): Decoded list from tabula-java JSON. pandas_options (dict optional): pandas options for `pd.DataFrame()` ''' data_frames = [] if pandas_options is None: ...
Translate pd. read_csv () options into pd. DataFrame () especially for header.
def _convert_pandas_csv_options(pandas_options, columns): ''' Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header. Args: pandas_option (dict): pandas options like {'header': None}. columns (list): list of column name. ''' _columns = pan...
Build options for tabula - java
def build_options(kwargs=None): '''Build options for tabula-java Args: options (str, optional): Raw option string for tabula-java. pages (str, int, :obj:`list` of :obj:`int`, optional): An optional values specifying pages to extract from. It allows `str`,`int...
Ensure localize target file.
def localize_file(path_or_buffer): '''Ensure localize target file. If the target file is remote, this function fetches into local storage. Args: path (str): File path or file like object or URL of target file. Returns: filename (str): file name in local storage tem...
Convert path like object to string
def _stringify_path(path_or_buffer): '''Convert path like object to string Args: path_or_buffer: object to be converted Returns: string_path_or_buffer: maybe string version of path_or_buffer ''' try: import pathlib _PATHLIB_INSTALLED = True except ImportError: ...
I implement wormhole receive. I return a Deferred that fires with None ( for success ) or signals one of the following errors: * WrongPasswordError: the two sides didn t use matching passwords * Timeout: something didn t happen fast enough for our tastes * TransferError: the sender rejected the transfer: verifier misma...
def receive(args, reactor=reactor, _debug_stash_wormhole=None): """I implement 'wormhole receive'. I return a Deferred that fires with None (for success), or signals one of the following errors: * WrongPasswordError: the two sides didn't use matching passwords * Timeout: something didn't happen fast eno...
the zipfile module does not restore file permissions so we ll do it manually
def _extract_file(self, zf, info, extract_dir): """ the zipfile module does not restore file permissions so we'll do it manually """ out_path = os.path.join(extract_dir, info.filename) out_path = os.path.abspath(out_path) if not out_path.startswith(extract_dir): ...
If launch_tor = True I will try to launch a new Tor process ask it for its SOCKS and control ports and use those for outbound connections ( and inbound onion - service listeners if necessary ).
def get_tor(reactor, launch_tor=False, tor_control_port=None, timing=None, stderr=sys.stderr): """ If launch_tor=True, I will try to launch a new Tor process, ask it for its SOCKS and control ports, and use those for outbound connections (and inbound onion...
This looks for an appropriate SSH key to send possibly querying the user in the meantime. DO NOT CALL after reactor. run as this ( possibly ) does blocking stuff like asking the user questions ( via click. prompt () )
def find_public_key(hint=None): """ This looks for an appropriate SSH key to send, possibly querying the user in the meantime. DO NOT CALL after reactor.run as this (possibly) does blocking stuff like asking the user questions (via click.prompt()) Returns a 3-tuple: kind, keyid, pubkey_data ...
Create a Magic Wormhole and communicate through it.
def wormhole(context, dump_timing, transit_helper, relay_url, appid): """ Create a Magic Wormhole and communicate through it. Wormholes are created by speaking the same magic CODE in two different places at the same time. Wormholes are secure against anyone who doesn't use the same code. """ ...
Internal helper. This calls the given command ( a no - argument callable ) with the Config instance in cfg and interprets any errors for the user.
def _dispatch_command(reactor, cfg, command): """ Internal helper. This calls the given command (a no-argument callable) with the Config instance in cfg and interprets any errors for the user. """ cfg.timing.add("command dispatch") cfg.timing.add( "import", when=start, which="top").f...
Send a text message file or directory
def send(cfg, **kwargs): """Send a text message, file, or directory""" for name, value in kwargs.items(): setattr(cfg, name, value) with cfg.timing.add("import", which="cmd_send"): from . import cmd_send return go(cmd_send.send, cfg)
Receive a text message file or directory ( from wormhole send )
def receive(cfg, code, **kwargs): """ Receive a text message, file, or directory (from 'wormhole send') """ for name, value in kwargs.items(): setattr(cfg, name, value) with cfg.timing.add("import", which="cmd_receive"): from . import cmd_receive if len(code) == 1: cfg.co...
Add a public - key to a ~/. ssh/ authorized_keys file
def ssh_invite(ctx, code_length, user, **kwargs): """ Add a public-key to a ~/.ssh/authorized_keys file """ for name, value in kwargs.items(): setattr(ctx.obj, name, value) from . import cmd_ssh ctx.obj.code_length = code_length ctx.obj.ssh_user = user return go(cmd_ssh.invite, c...
Send your SSH public - key
def ssh_accept(cfg, code, key_file, yes, **kwargs): """ Send your SSH public-key In response to a 'wormhole ssh invite' this will send public-key you specify (if there's only one in ~/.ssh/* that will be sent). """ for name, value in kwargs.items(): setattr(cfg, name, value) from ....
Return an ( integer ) available TCP port on localhost. This briefly listens on the port in question then closes it right away.
def allocate_tcp_port(): """Return an (integer) available TCP port on localhost. This briefly listens on the port in question, then closes it right away.""" # We want to bind() the socket but not listen(). Twisted (in # tcp.Port.createInternetSocket) would do several other things: # non-blocking, cl...
If the timer fires first cancel the deferred. If the deferred fires first cancel the timer.
def _not_forever(self, timeout, d): """If the timer fires first, cancel the deferred. If the deferred fires first, cancel the timer.""" t = self._reactor.callLater(timeout, d.cancel) def _done(res): if t.active(): t.cancel() return res d....
This is a convenience API which returns a Deferred that callbacks with a single chunk of data from another wormhole ( and then closes the wormhole ). Under the hood it s just using an instance returned from: func: wormhole. wormhole. This is similar to the wormhole receive command.
def receive(reactor, appid, relay_url, code, use_tor=False, launch_tor=False, tor_control_port=None, on_code=None): """ This is a convenience API which returns a Deferred that callbacks with a single chunk of data from anoth...
Get access to a specific table.
def table(self, name=DEFAULT_TABLE, **options): """ Get access to a specific table. Creates a new table, if it hasn't been created before, otherwise it returns the cached :class:`~tinydb.Table` object. :param name: The name of the table. :type name: str :param c...
Purge a specific table from the database. ** CANNOT BE REVERSED! **
def purge_table(self, name): """ Purge a specific table from the database. **CANNOT BE REVERSED!** :param name: The name of the table. :type name: str """ if name in self._table_cache: del self._table_cache[name] proxy = StorageProxy(self._storage, n...
Helper function for processing all documents specified by condition or IDs.
def process_elements(self, func, cond=None, doc_ids=None, eids=None): """ Helper function for processing all documents specified by condition or IDs. A repeating pattern in TinyDB is to run some code on all documents that match a condition or are specified by their ID. This is ...
Insert a new document into the table.
def insert(self, document): """ Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID """ doc_id = self._get_doc_id(document) data = self._read() data[doc_id] = dict(document) self._wri...
Insert multiple documents into the table.
def insert_multiple(self, documents): """ Insert multiple documents into the table. :param documents: a list of documents to insert :returns: a list containing the inserted documents' IDs """ doc_ids = [] data = self._read() for doc in documents: ...
Remove all matching documents.
def remove(self, cond=None, doc_ids=None, eids=None): """ Remove all matching documents. :param cond: the condition to check against :type cond: query :param doc_ids: a list of document IDs :type doc_ids: list :returns: a list containing the removed document's ID...
Update all matching documents to have a given set of fields.
def update(self, fields, cond=None, doc_ids=None, eids=None): """ Update all matching documents to have a given set of fields. :param fields: the fields that the matching documents will have or a method that will update the documents :type fields: dict | dict -> N...
Write back documents by doc_id
def write_back(self, documents, doc_ids=None, eids=None): """ Write back documents by doc_id :param documents: a list of document to write back :param doc_ids: a list of document IDs which need to be written back :returns: a list of document IDs that have been written ""...