repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
mayfield/cellulario
cellulario/iocell.py
IOCell.cleanup_event_loop
python
def cleanup_event_loop(self): for task in asyncio.Task.all_tasks(loop=self.loop): if self.debug: warnings.warn('Cancelling task: %s' % task) task._log_destroy_pending = False task.cancel() self.loop.close() self.loop.set_exception_handler(self....
Cleanup an event loop and close it down forever.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L99-L110
null
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.add_tier
python
def add_tier(self, coro, **kwargs): self.assertNotFinalized() assert asyncio.iscoroutinefunction(coro) tier = self.Tier(self, coro, **kwargs) self.tiers.append(tier) self.tiers_coro_map[coro] = tier return tier
Add a coroutine to the cell as a task tier. The source can be a single value or a list of either `Tier` types or coroutine functions already added to a `Tier` via `add_tier`.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L123-L132
[ "def assertNotFinalized(self):\n \"\"\" Ensure the cell is not used more than once. \"\"\"\n if self.finalized:\n raise RuntimeError('Already finalized: %s' % self)\n" ]
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.append_tier
python
def append_tier(self, coro, **kwargs): source = self.tiers[-1] if self.tiers else None return self.add_tier(coro, source=source, **kwargs)
Implicitly source from the tail tier like a pipe.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L134-L137
[ "def add_tier(self, coro, **kwargs):\n \"\"\" Add a coroutine to the cell as a task tier. The source can be a\n single value or a list of either `Tier` types or coroutine functions\n already added to a `Tier` via `add_tier`. \"\"\"\n self.assertNotFinalized()\n assert asyncio.iscoroutinefunction(cor...
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.tier
python
def tier(self, *args, append=True, source=None, **kwargs): if len(args) == 1 and not kwargs and callable(args[0]): raise TypeError('Uncalled decorator syntax is invalid') def decorator(coro): if not asyncio.iscoroutinefunction(coro): coro = asyncio.coroutine(coro...
Function decorator for a tier coroutine. If the function being decorated is not already a coroutine function it will be wrapped.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L145-L159
null
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.cleaner
python
def cleaner(self, coro): if not asyncio.iscoroutinefunction(coro): coro = asyncio.coroutine(coro) self.add_cleaner(coro) return coro
Function decorator for a cleanup coroutine.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L161-L166
[ "def add_cleaner(self, coro):\n \"\"\" Add a coroutine to run after the cell is done. This is for the\n user to perform any cleanup such as closing sockets. \"\"\"\n self.assertNotFinalized()\n self.cleaners.append(coro)\n" ]
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.finalize
python
def finalize(self): self.assertNotFinalized() starters = [] finishers = [] for x in self.tiers: if not x.sources: starters.append(x) if not x.dests: finishers.append(x) self.add_tier(self.output_feed, source=finishers) ...
Look at our tiers and setup the final data flow. Once this is run a cell can not be modified again.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L168-L182
[ "def assertNotFinalized(self):\n \"\"\" Ensure the cell is not used more than once. \"\"\"\n if self.finalized:\n raise RuntimeError('Already finalized: %s' % self)\n", "def add_tier(self, coro, **kwargs):\n \"\"\" Add a coroutine to the cell as a task tier. The source can be a\n single value ...
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.output
python
def output(self): starters = self.finalize() try: yield from self._output(starters) finally: self.close()
Produce a classic generator for this cell's final results.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L200-L206
[ "def finalize(self):\n \"\"\" Look at our tiers and setup the final data flow. Once this is run\n a cell can not be modified again. \"\"\"\n self.assertNotFinalized()\n starters = []\n finishers = []\n for x in self.tiers:\n if not x.sources:\n starters.append(x)\n if not...
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.event_loop
python
def event_loop(self): if hasattr(self.loop, '._run_once'): self.loop._thread_id = threading.get_ident() try: self.loop._run_once() finally: self.loop._thread_id = None else: self.loop.call_soon(self.loop.stop) se...
Run the event loop once.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L208-L218
null
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
mayfield/cellulario
cellulario/iocell.py
IOCell.clean
python
def clean(self): if self.cleaners: yield from asyncio.wait([x() for x in self.cleaners], loop=self.loop)
Run all of the cleaners added by the user.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L248-L252
null
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...
jashort/SmartFileSorter
smartfilesorter/actionplugins/renameto.py
RenameTo.do_action
python
def do_action(self, target, dry_run=False): original_path = os.path.dirname(target) original_filename, original_extension = os.path.splitext(os.path.basename(target)) new_filename = re.sub(self.match, self.replace_with, original_filename) + original_extension destination = os.path.join(...
:param target: Full path and filename :param dry_run: True - don't actually perform action. False: perform action. No effect for this rule. :return: filename: Full path and filename after action completes
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/actionplugins/renameto.py#L28-L57
null
class RenameTo(object): """ Renames a given file. Performs a case sensitive search and replace on the filename, then renames it. Also supports regular expressions. """ config_name = 'rename-to' def __init__(self, parameters): self.logger = logging.getLogger(__name__) if 'match' ...
jashort/SmartFileSorter
smartfilesorter/ruleset.py
RuleSet.add_match_rule
python
def add_match_rule(self, rule_config_name): self.logger.debug('Adding match rule {0}'.format(rule_config_name)) # Handle rules that are just a string, like 'stop-processing' if type(rule_config_name) == str: self.add_rule(rule_config_name, None, self.available_match_plugins, self.mat...
Adds the given match rule to this ruleset's match rules :param rule_config_name: Plugin's config name :return: None
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L37-L50
[ "def add_rule(self, config_name, value, plugins, destination):\n \"\"\"\n Adds a rule. Use add_action_rule or add_match_rule instead\n :param rule_wrapper: Rule wrapper class (ActionRule or MatchRule)\n :param config_name: config_name of the plugin to add\n :param value: configuration information for...
class RuleSet(object): """ A ruleset is a collection of associated match rules and actions. For example: - file-extension-is: .log - filename-starts-with: ex - move-to: /archive/logs/ Match rules are a boolean AND operation -- all must match. Actions are all applied in order. """ def _...
jashort/SmartFileSorter
smartfilesorter/ruleset.py
RuleSet.add_action_rule
python
def add_action_rule(self, rule_config_name): self.logger.debug('Adding action rule {0}'.format(rule_config_name)) # Handle rules that are just a string, like 'stop-processing' if type(rule_config_name) == str: self.add_rule(rule_config_name, None, self.available_action_plugins, self....
Adds the given action rule to this ruleset's action rules :param rule_config_name: :return:
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L52-L65
[ "def add_rule(self, config_name, value, plugins, destination):\n \"\"\"\n Adds a rule. Use add_action_rule or add_match_rule instead\n :param rule_wrapper: Rule wrapper class (ActionRule or MatchRule)\n :param config_name: config_name of the plugin to add\n :param value: configuration information for...
class RuleSet(object): """ A ruleset is a collection of associated match rules and actions. For example: - file-extension-is: .log - filename-starts-with: ex - move-to: /archive/logs/ Match rules are a boolean AND operation -- all must match. Actions are all applied in order. """ def _...
jashort/SmartFileSorter
smartfilesorter/ruleset.py
RuleSet.add_rule
python
def add_rule(self, config_name, value, plugins, destination): if config_name in plugins: rule = plugins[config_name](value) destination.append(rule) else: self.logger.error("Plugin with config_name {0} not found".format(config_name)) raise IndexError("Plug...
Adds a rule. Use add_action_rule or add_match_rule instead :param rule_wrapper: Rule wrapper class (ActionRule or MatchRule) :param config_name: config_name of the plugin to add :param value: configuration information for the rule :param plugins: list of all available plugins :pa...
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L67-L82
null
class RuleSet(object): """ A ruleset is a collection of associated match rules and actions. For example: - file-extension-is: .log - filename-starts-with: ex - move-to: /archive/logs/ Match rules are a boolean AND operation -- all must match. Actions are all applied in order. """ def _...
jashort/SmartFileSorter
smartfilesorter/ruleset.py
RuleSet.matches_all_rules
python
def matches_all_rules(self, target_filename): for rule in self.match_rules: if rule.test(target_filename) is False: return False self.logger.debug('{0}: {1} - {2}'.format(self.name, os.path.basename(target_filename), ...
Returns true if the given file matches all the rules in this ruleset. :param target_filename: :return: boolean
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L84-L98
null
class RuleSet(object): """ A ruleset is a collection of associated match rules and actions. For example: - file-extension-is: .log - filename-starts-with: ex - move-to: /archive/logs/ Match rules are a boolean AND operation -- all must match. Actions are all applied in order. """ def _...
jashort/SmartFileSorter
smartfilesorter/ruleset.py
RuleSet.do_actions
python
def do_actions(self, target_filename, dry_run=False): for rule in self.action_rules: target_filename = rule.do_action(target_filename, dry_run) raise StopProcessingException
Runs all the given action rules in this ruleset on target_filename :param target_filename: :retrn: filename Filename and path after any actions have been completed \
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L100-L109
null
class RuleSet(object): """ A ruleset is a collection of associated match rules and actions. For example: - file-extension-is: .log - filename-starts-with: ex - move-to: /archive/logs/ Match rules are a boolean AND operation -- all must match. Actions are all applied in order. """ def _...
jashort/SmartFileSorter
smartfilesorter/ruleset.py
RuleSet.add_action_rules
python
def add_action_rules(self, action_rules): if type(action_rules) == list: for r in action_rules: self.add_action_rule(r) else: # Handle a single rule being passed in that's not in a list self.add_action_rule(action_rules)
Add the given action rules to the ruleset. Handles single rules or a list of rules. :param action_rules: Object representing YAML section from config file :return: Example action_rules object: ['print-file-info', {'move-to': '/tmp'}, 'stop-processing']
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L111-L125
[ "def add_action_rule(self, rule_config_name):\n \"\"\"\n Adds the given action rule to this ruleset's action rules\n :param rule_config_name:\n :return:\n \"\"\"\n self.logger.debug('Adding action rule {0}'.format(rule_config_name))\n # Handle rules that are just a string, like 'stop-processing...
class RuleSet(object): """ A ruleset is a collection of associated match rules and actions. For example: - file-extension-is: .log - filename-starts-with: ex - move-to: /archive/logs/ Match rules are a boolean AND operation -- all must match. Actions are all applied in order. """ def _...
jashort/SmartFileSorter
smartfilesorter/ruleset.py
RuleSet.add_match_rules
python
def add_match_rules(self, match_rules): if type(match_rules) == list: for r in match_rules: self.add_match_rule(r) else: # Handle a single rule being passed in that's not in a list self.add_match_rule(match_rules)
Add the given match rules to the ruleset. Handles single rules or a list of rules. :param match_rules: Object representing YAML section from config file :return: Example match_rules object: [{'filename-starts-with': 'abc'}, {'filename-ends-with': 'xyz']
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L127-L141
[ "def add_match_rule(self, rule_config_name):\n \"\"\"\n Adds the given match rule to this ruleset's match rules\n :param rule_config_name: Plugin's config name\n :return: None\n \"\"\"\n self.logger.debug('Adding match rule {0}'.format(rule_config_name))\n # Handle rules that are just a string,...
class RuleSet(object): """ A ruleset is a collection of associated match rules and actions. For example: - file-extension-is: .log - filename-starts-with: ex - move-to: /archive/logs/ Match rules are a boolean AND operation -- all must match. Actions are all applied in order. """ def _...
jashort/SmartFileSorter
smartfilesorter/smartfilesorter.py
SmartFileSorter.parse_arguments
python
def parse_arguments(arguments=sys.argv[1:]): args = docopt.docopt(doc=""" Smart File Sorter Usage: sfp RULEFILE DIRECTORY [--debug] [--dry-run] [--log LOGFILE] sfp [--debug] --list-plugins Options: RULEFILE Rule configuration file to execute DIRECTORY Directory of files to process ...
Process command line arguments :param: List of strings containing command line arguments, defaults to sys.argv[1:] :return: docopt args object
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L22-L43
null
class SmartFileSorter(object): def __init__(self): self.args = None self.logger = None self.match_plugins = [] self.action_plugins = [] @staticmethod def create_logger(self, args={}): """ Create and configure the program's logger object. Log levels...
jashort/SmartFileSorter
smartfilesorter/smartfilesorter.py
SmartFileSorter.create_logger
python
def create_logger(self, args={}): # Set up logging logger = logging.getLogger("SmartFileSorter") logger.level = logging.INFO if '--debug' in args and args['--debug'] is True: logger.setLevel(logging.DEBUG) file_log_formatter = logging.Formatter('%(asctime)s %(name)s...
Create and configure the program's logger object. Log levels: DEBUG - Log everything. Hidden unless --debug is used. INFO - information only ERROR - Critical error :param args: Object containing program's parsed command line arguments :return: None
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L45-L81
null
class SmartFileSorter(object): def __init__(self): self.args = None self.logger = None self.match_plugins = [] self.action_plugins = [] @staticmethod def parse_arguments(arguments=sys.argv[1:]): """ Process command line arguments :param: List of strin...
jashort/SmartFileSorter
smartfilesorter/smartfilesorter.py
SmartFileSorter.get_files
python
def get_files(self, path): if os.path.isfile(path): self.logger.debug('Called with single file as target: {0}'.format(path)) yield path return self.logger.debug('Getting list of files in {0}'.format(path)) try: for f in os.listdir(path): ...
Yields full path and filename for each file that exists in the given directory. Will ignore hidden files (that start with a ".") and directories :param path: Directory or filename :return:
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L83-L105
null
class SmartFileSorter(object): def __init__(self): self.args = None self.logger = None self.match_plugins = [] self.action_plugins = [] @staticmethod def parse_arguments(arguments=sys.argv[1:]): """ Process command line arguments :param: List of strin...
jashort/SmartFileSorter
smartfilesorter/smartfilesorter.py
SmartFileSorter.load_rules
python
def load_rules(self, filename): self.logger.debug('Reading rules from %s', filename) try: in_file = open(filename) except IOError: self.logger.error('Error opening {0}'.format(filename)) raise y = None try: y = yaml.load(in_file) ...
Load rules from YAML configuration in the given stream object :param filename: Filename of rule YAML file :return: rules object
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L107-L130
null
class SmartFileSorter(object): def __init__(self): self.args = None self.logger = None self.match_plugins = [] self.action_plugins = [] @staticmethod def parse_arguments(arguments=sys.argv[1:]): """ Process command line arguments :param: List of strin...
jashort/SmartFileSorter
smartfilesorter/smartfilesorter.py
SmartFileSorter.load_plugins
python
def load_plugins(self, plugin_path): self.logger.debug('Loading plugins from {0}'.format(plugin_path)) plugins = {} plugin_dir = os.path.realpath(plugin_path) sys.path.append(plugin_dir) for f in os.listdir(plugin_dir): if f.endswith(".py"): name = f[...
Loads plugins from modules in plugin_path. Looks for the config_name property in each object that's found. If so, adds that to the dictionary with the config_name as the key. config_name should be unique between different plugins. :param plugin_path: Path to load plugins from :return: d...
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L132-L178
null
class SmartFileSorter(object): def __init__(self): self.args = None self.logger = None self.match_plugins = [] self.action_plugins = [] @staticmethod def parse_arguments(arguments=sys.argv[1:]): """ Process command line arguments :param: List of strin...
jashort/SmartFileSorter
smartfilesorter/smartfilesorter.py
SmartFileSorter.build_rules
python
def build_rules(rule_yaml, match_plugins, action_plugins): rule_sets = [] for yaml_section in rule_yaml: rule_sets.append(RuleSet(yaml_section, match_plugins=match_plugins, action_plugins=action_plugins)) return rule_sets
Convert parsed rule YAML in to a list of ruleset objects :param rule_yaml: Dictionary parsed from YAML rule file :param match_plugins: Dictionary of match plugins (key=config_name, value=plugin object) :param action_plugins: Dictionary of action plugins (key=config_name, value=plugin object) ...
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L181-L193
null
class SmartFileSorter(object): def __init__(self): self.args = None self.logger = None self.match_plugins = [] self.action_plugins = [] @staticmethod def parse_arguments(arguments=sys.argv[1:]): """ Process command line arguments :param: List of strin...
jashort/SmartFileSorter
smartfilesorter/smartfilesorter.py
SmartFileSorter.run
python
def run(self, args): module_dir = os.path.dirname(__file__) self.match_plugins = self.load_plugins(os.path.join(module_dir, 'matchplugins/')) self.action_plugins = self.load_plugins(os.path.join(module_dir, 'actionplugins/')) if args['--list-plugins'] is True: print("\nAvail...
Load plugins and run with the configuration given in args :param args: Object containing program's parsed command line arguments :return: None
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L195-L239
[ "def get_files(self, path):\n \"\"\"\n Yields full path and filename for each file that exists in the given directory. Will\n ignore hidden files (that start with a \".\") and directories\n :param path: Directory or filename\n :return:\n \"\"\"\n\n if os.path.isfile(path):\n self.logger....
class SmartFileSorter(object): def __init__(self): self.args = None self.logger = None self.match_plugins = [] self.action_plugins = [] @staticmethod def parse_arguments(arguments=sys.argv[1:]): """ Process command line arguments :param: List of strin...
jashort/SmartFileSorter
smartfilesorter/actionplugins/printfileinfo.py
PrintFileInfo.do_action
python
def do_action(self, target, dry_run=False): if dry_run is False: try: filename = os.path.basename(target) size = os.path.getsize(target) print("{0}\t{1}".format(filename, size)) except OSError: self.logger.error("Error getti...
:param target: Full path and filename :param dry_run: True - don't actually perform action. False: perform action. No effect for this rule. :return: filename: Full path and filename after action completes
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/actionplugins/printfileinfo.py#L15-L29
null
class PrintFileInfo(object): """ Prints the filename and size to stdout. Mostly used for testing. """ config_name = 'print-file-info' def __init__(self, value=None): self.value = value self.logger = logging.getLogger(__name__)
jashort/SmartFileSorter
smartfilesorter/actionplugins/moveto.py
MoveTo.do_action
python
def do_action(self, target, dry_run=False): # Get full path to the file in the destination directory new_filename = os.path.join(self.destination, os.path.basename(target)) # If the file exists in the destination directory, append _NNN to the name where NNN is # a zero padded number. St...
:param target: Full path and filename :param dry_run: True - don't actually perform action. False: perform action. :return: filename: Full path and filename after action completes
train
https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/actionplugins/moveto.py#L17-L62
null
class MoveTo(object): """ Moves a given file to a new directory """ config_name = 'move-to' def __init__(self, destination): self.destination = os.path.expanduser(destination) self.continue_processing = False self.logger = logging.getLogger(__name__)
litters/shrew
shrew/utils/auth.py
unlock_keychain
python
def unlock_keychain(username): if 'SSH_TTY' not in os.environ: return # Don't unlock if we've already seen this user. if username in _unlocked: return _unlocked.add(username) if sys.platform == 'darwin': sys.stderr.write("You are running under SSH. Please unlock your loca...
If the user is running via SSH, their Keychain must be unlocked first.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L133-L147
null
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/utils/auth.py
save_password
python
def save_password(entry, password, username=None): if username is None: username = get_username() has_keychain = initialize_keychain() if has_keychain: try: keyring.set_password(entry, username, password) except Exception as e: log.warn("Unable to set passw...
Saves the given password in the user's keychain. :param entry: The entry in the keychain. This is a caller specific key. :param password: The password to save in the keychain. :param username: The username to get the password for. Default is the current user.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L150-L169
[ "def get_username(use_store=False):\n if use_store:\n with load_config(sections=AUTH_SECTIONS, defaults=AUTH_CONFIG_DEFAULTS) as config:\n if config.has_option(AUTH_SECTION, 'username'):\n username = config.get(AUTH_SECTION, 'username')\n else:\n usernam...
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/utils/auth.py
remove_password
python
def remove_password(entry, username=None): if username is None: username = get_username() has_keychain = initialize_keychain() if has_keychain: try: keyring.delete_password(entry, username) except Exception as e: print e log.warn("Unable to dele...
Removes the password for the specific user in the user's keychain. :param entry: The entry in the keychain. This is a caller specific key. :param username: The username whose password is to be removed. Default is the current user.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L172-L191
[ "def get_username(use_store=False):\n if use_store:\n with load_config(sections=AUTH_SECTIONS, defaults=AUTH_CONFIG_DEFAULTS) as config:\n if config.has_option(AUTH_SECTION, 'username'):\n username = config.get(AUTH_SECTION, 'username')\n else:\n usernam...
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/utils/auth.py
get_password
python
def get_password(entry=None, username=None, prompt=None, always_ask=False): password = None if username is None: username = get_username() has_keychain = initialize_keychain() # Unlock the user's keychain otherwise, if running under SSH, 'security(1)' will thrown an error. unlock_keychai...
Prompt the user for a password on stdin. :param username: The username to get the password for. Default is the current user. :param entry: The entry in the keychain. This is a caller specific key. :param prompt: The entry in the keychain. This is a caller specific key. :param always_ask: Force ...
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L194-L223
[ "def get_username(use_store=False):\n if use_store:\n with load_config(sections=AUTH_SECTIONS, defaults=AUTH_CONFIG_DEFAULTS) as config:\n if config.has_option(AUTH_SECTION, 'username'):\n username = config.get(AUTH_SECTION, 'username')\n else:\n usernam...
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/utils/auth.py
get_password_from_keyring
python
def get_password_from_keyring(entry=None, username=None): if username is None: username = get_username() has_keychain = initialize_keychain() # Unlock the user's keychain otherwise, if running under SSH, 'security(1)' will thrown an error. unlock_keychain(username) if has_keychain and en...
:param entry: The entry in the keychain. This is a caller specific key. :param username: The username to get the password for. Default is the current user.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L226-L247
[ "def get_username(use_store=False):\n if use_store:\n with load_config(sections=AUTH_SECTIONS, defaults=AUTH_CONFIG_DEFAULTS) as config:\n if config.has_option(AUTH_SECTION, 'username'):\n username = config.get(AUTH_SECTION, 'username')\n else:\n usernam...
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/utils/auth.py
validate_password
python
def validate_password(entry, username, check_function, password=None, retries=1, save_on_success=True, prompt=None, **check_args): if password is None: password = get_password(entry, username, prompt) for _ in xrange(retries + 1): if check_function(username, password, **check_args): ...
Validate a password with a check function & retry if the password is incorrect. Useful for after a user has changed their password in LDAP, but their local keychain entry is then out of sync. :param str entry: The keychain entry to fetch a password from. :param str username: The username to authenti...
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L250-L283
[ "def save_password(entry, password, username=None):\n \"\"\"\n Saves the given password in the user's keychain.\n\n :param entry: The entry in the keychain. This is a caller specific key.\n :param password: The password to save in the keychain.\n :param username: The username to get the passw...
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/utils/auth.py
get_stored_credentials
python
def get_stored_credentials(): with load_config(sections=AUTH_SECTIONS, defaults=AUTH_CONFIG_DEFAULTS) as config: username = config.get(AUTH_SECTION, 'username') if not username: # if we don't have a username then we cannot lookup the password return None, None has_keycha...
Gets the credentials, username and password, that have been stored in ~/.shrew/config.ini and the secure keychain respectively without bothering to prompt the user if either credential cannot be found. :returns: username and password :rtype: tuple of str
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L286-L313
null
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/utils/auth.py
FixedOSXKeychain.delete_password
python
def delete_password(service, username): try: # set up the call for security. call = subprocess.Popen(['security', 'delete-generic-password', '-a', username, ...
Delete the password for the username of the service.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/utils/auth.py#L60-L79
null
class FixedOSXKeychain(OSXKeychain): """ OSXKeychain does not implement delete_password() yet """ @staticmethod
litters/shrew
shrew/cli.py
entrypoint
python
def entrypoint(method, depth=1, cls=None): current_frame = inspect.currentframe(depth).f_locals if '__name__' in current_frame and current_frame['__name__'] == '__main__': if cls is None: cls = CLI method(cls()) return method
Run a method as your __main__ via decorator. Example:: @shrew.cli.entrypoint def main(cli): ... Shorthand for:: def main(): cli = shrew.cli.CLI() ... if __name__ == '__main__': method()
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L30-L61
null
# # Copyright 2014 the original author or authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
litters/shrew
shrew/cli.py
CLI.add_config_option
python
def add_config_option(self, default=None): self.argparser.add_argument('--config', default=default, help='Config file to read. Defaults to: %(default)s') self.should_parse_config = True
Add a --config option to the argument parser.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L216-L220
null
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
litters/shrew
shrew/cli.py
CLI.add_username_password
python
def add_username_password(self, use_store=False): self.argparser.add_argument('--username', default=None, help='Username') self.argparser.add_argument('--password', default=None, help='Password') self.argparser.add_argument('--clear-store', action='store_true', default=False, help='Clear passwor...
Add --username and --password options :param bool use_store: Name of the section (concept, command line options, API reference)
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L222-L230
null
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
litters/shrew
shrew/cli.py
CLI._add_documentation_link
python
def _add_documentation_link(self, links, section, variable_name, default=None): url = getattr(sys.modules['__main__'], variable_name, default) if url: links.append('%s: %s' % (section, url))
:param list links: List of links to append link of the form "Section: <link>", if link available :param str section: Name of the section (concept, command line options, API reference) :param str variable_name: Variable name in main module that should hold URL to documentation :param str de...
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L232-L243
null
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
litters/shrew
shrew/cli.py
CLI.__parse_args
python
def __parse_args(self, accept_unrecognized_args=False): # If the user provided a description, use it. Otherwise grab the doc string. if self.description: self.argparser.description = self.description elif getattr(sys.modules['__main__'], '__doc__', None): self.argparser....
Invoke the argument parser.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L245-L265
null
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
litters/shrew
shrew/cli.py
CLI.__parse_config
python
def __parse_config(self): if self.should_parse_config and (self.args.config or self.config_file): self.config = ConfigParser.SafeConfigParser() self.config.read(self.args.config or self.config_file)
Invoke the config file parser.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L267-L272
null
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
litters/shrew
shrew/cli.py
CLI.__process_username_password
python
def __process_username_password(self): if self.use_username_password_store is not None: if self.args.clear_store: with load_config(sections=AUTH_SECTIONS) as config: config.remove_option(AUTH_SECTION, 'username') if not self.args.username: ...
If indicated, process the username and password
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L274-L289
[ "def get_username(use_store=False):\n if use_store:\n with load_config(sections=AUTH_SECTIONS, defaults=AUTH_CONFIG_DEFAULTS) as config:\n if config.has_option(AUTH_SECTION, 'username'):\n username = config.get(AUTH_SECTION, 'username')\n else:\n usernam...
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
litters/shrew
shrew/cli.py
CLI.__finish_initializing
python
def __finish_initializing(self): if self.args.debug or self.args.trace: # Set the console (StreamHandler) to allow debug statements. if self.args.debug: self.console.setLevel(logging.DEBUG) self.console.setFormatter(logging.Formatter('[%(levelname)s] %(asct...
Handle any initialization after arguments & config has been parsed.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L291-L327
null
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
litters/shrew
shrew/cli.py
CLI.run
python
def run(self, accept_unrecognized_args=False): self.__parse_args(accept_unrecognized_args) self.__parse_config() self.__process_username_password() self.__finish_initializing() exit_status = 0 try: yield self except ExitedCleanly: pass ...
Called via the `with` statement to invoke the :func:`contextlib.contextmanager`. Control is then yielded back to the caller. All exceptions are caught & a stack trace emitted, except in the case of `shrew.cli.ExitedCleanly`.
train
https://github.com/litters/shrew/blob/ed4b1879321d858d6bc884d14fea7557372a4d41/shrew/cli.py#L339-L372
[ "def __parse_args(self, accept_unrecognized_args=False):\n \"\"\" Invoke the argument parser. \"\"\"\n\n # If the user provided a description, use it. Otherwise grab the doc string.\n if self.description:\n self.argparser.description = self.description\n elif getattr(sys.modules['__main__'], '__d...
class CLI(object): """ Initialize a command line helper instance. Example:: import shrew.cli # Adding a version variable will automatically let you use --version on the command line. # VERSION is also acceptable. version = "1.0" @shrew.cli.entryp...
veeti/decent
decent/error.py
Error.as_dict
python
def as_dict(self, join='.'): if self.path: path = [str(node) for node in self.path] else: path = '' return { join.join(path): self.message }
Returns the error as a path to message dictionary. Paths are joined with the ``join`` string.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/error.py#L28-L37
null
class Error(DecentError): """ A single validation error. The ``message`` contains an explanation for the error: for example, "this value must be at least 10 characters long". The ``path`` is a list of keys to the field this error is for. This is usually automatically set by the :class:`decent....
veeti/decent
decent/error.py
Invalid.as_dict
python
def as_dict(self, join='.'): result = {} for e in self.errors: result.update(e.as_dict(join)) return result
Returns all the errors in this collection as a path to message dictionary. Paths are joined with the ``join`` string.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/error.py#L64-L72
null
class Invalid(Error): """ A collection of one or more validation errors for a schema. """ def __init__(self, errors=None): self.errors = [] if errors: self.errors.extend(errors[:]) def append(self, error): self.errors.append(error) @property def messag...
veeti/decent
decent/validators.py
All
python
def All(*validators): @wraps(All) def built(value): for validator in validators: value = validator(value) return value return built
Combines all the given validator callables into one, running all the validators in sequence on the given value.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L11-L21
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def Any(*validators): """ Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given. """ @wraps(Any) ...
veeti/decent
decent/validators.py
Any
python
def Any(*validators): @wraps(Any) def built(value): error = None for validator in validators: try: return validator(value) except Error as e: error = e raise error return built
Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L23-L37
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Maybe
python
def Maybe(validator): @wraps(Maybe) def built(value): if value != None: return validator(value) return built
Wraps the given validator callable, only using it for the given value if it is not ``None``.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L39-L48
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Msg
python
def Msg(validator, message): @wraps(Msg) def built(value): try: return validator(value) except Error as e: e.message = message raise e return built
Wraps the given validator callable, replacing any error messages raised.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L50-L61
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Default
python
def Default(default): @wraps(Default) def built(value): if value == None: return default return value return built
Creates a validator callable that replaces ``None`` with the specified default value.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L63-L73
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Eq
python
def Eq(value, message="Not equal to {!s}"): @wraps(Eq) def built(_value): if _value != value: raise Error(message.format(value)) return _value return built
Creates a validator that compares the equality of the given value to ``value``. A custom message can be specified with ``message``. It will be formatted with ``value``.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L77-L90
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Type
python
def Type(expected, message="Not of type {}"): @wraps(Type) def built(value): if type(value) != expected: raise Error(message.format(expected.__name__)) return value return built
Creates a validator that compares the type of the given value to ``expected``. This is a direct type() equality check. Also see ``Instance``, which is an isinstance() check. A custom message can be specified with ``message``.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L92-L105
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Instance
python
def Instance(expected, message="Not an instance of {}"): @wraps(Instance) def built(value): if not isinstance(value, expected): raise Error(message.format(expected.__name__)) return value return built
Creates a validator that checks if the given value is an instance of ``expected``. A custom message can be specified with ``message``.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L107-L119
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Coerce
python
def Coerce(type, message="Not a valid {} value"): @wraps(Coerce) def built(value): try: return type(value) except (TypeError, ValueError) as e: raise Error(message.format(type.__name__)) return built
Creates a validator that attempts to coerce the given value to the specified ``type``. Will raise an error if the coercion fails. A custom message can be specified with ``message``.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L121-L134
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
List
python
def List(validator): @wraps(List) def built(value): if not hasattr(value, '__iter__'): raise Error("Must be a list") invalid = Invalid() for i, item in enumerate(value): try: value[i] = validator(item) except Invalid as e: ...
Creates a validator that runs the given validator on every item in a list or other collection. The validator can mutate the values. Any raised errors will be collected into a single ``Invalid`` error. Their paths will be replaced with the index of the item. Will raise an error if the input value is not...
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L138-L167
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Boolean
python
def Boolean(): @wraps(Boolean) def built(value): # Already a boolean? if isinstance(value, bool): return value # None if value == None: return False # Integers if isinstance(value, int): return not value == 0 # String...
Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted in lower- and uppercase: * ``y, yes, t, true`` * ``n, no, f, ...
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L171-L208
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Range
python
def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"): @wraps(Range) def built(value): if not isinstance(value, numbers.Number) or isinstance(value, bool): raise Error("Not a number") if min is not None and min > value: r...
Creates a validator that checks if the given numeric value is in the specified range, inclusive. Accepts values specified by ``numbers.Number`` only, excluding booleans. The error messages raised can be customized with ``min_message`` and ``max_message``. The ``min`` and ``max`` arguments are formatte...
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L212-L231
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Length
python
def Length(min=None, max=None, min_message="Must have a length of at least {min}", max_message="Must have a length of at most {max}"): validator = Range(min, max, min_message, max_message) @wraps(Length) def built(value): if not hasattr(value, '__len__'): raise Error("Does not have a len...
Creates a validator that checks if the given value's length is in the specified range, inclusive. (Returns the original value.) See :func:`.Range`.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L233-L247
[ "def Range(min=None, max=None, min_message=\"Must be at least {min}\", max_message=\"Must be at most {max}\"):\n \"\"\"\n Creates a validator that checks if the given numeric value is in the\n specified range, inclusive.\n\n Accepts values specified by ``numbers.Number`` only, excluding booleans.\n\n ...
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
NotEmpty
python
def NotEmpty(): @wraps(NotEmpty) def built(value): if not isinstance(value, six.string_types) or not value: raise Error("Must not be empty") return value return built
Creates a validator that validates the given string is not empty. Will raise an error for non-string types.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L286-L296
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
veeti/decent
decent/validators.py
Uuid
python
def Uuid(to_uuid=True): @wraps(Uuid) def built(value): invalid = Error("Not a valid UUID") if isinstance(value, uuid.UUID): return value elif not isinstance(value, six.string_types): raise invalid try: as_uuid = uuid.UUID(value) excep...
Creates a UUID validator. Will raise an error for non-string types and non-UUID values. The given value will be converted to an instance of ``uuid.UUID`` unless ``to_uuid`` is ``False``.
train
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L300-L325
null
from functools import wraps import numbers import uuid import six from decent.error import Error, Invalid ## Helpers def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): ...
cmutel/constructive_geometries
constructive_geometries/cg.py
has_gis
python
def has_gis(wrapped, instance, args, kwargs): if gis: return wrapped(*args, **kwargs) else: warn(MISSING_GIS)
Skip function execution if there are no presamples
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L22-L27
null
from multiprocessing import Pool, cpu_count from warnings import warn import hashlib import itertools import json import os import wrapt try: from shapely.geometry import shape, mapping from shapely.ops import cascaded_union import fiona gis = True except ImportError: gis = False MISSING_GIS = ""...
cmutel/constructive_geometries
constructive_geometries/cg.py
sha256
python
def sha256(filepath, blocksize=65536): hasher = hashlib.sha256() fo = open(filepath, 'rb') buf = fo.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = fo.read(blocksize) return hasher.hexdigest()
Generate SHA 256 hash for file at `filepath`
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L33-L41
null
from multiprocessing import Pool, cpu_count from warnings import warn import hashlib import itertools import json import os import wrapt try: from shapely.geometry import shape, mapping from shapely.ops import cascaded_union import fiona gis = True except ImportError: gis = False MISSING_GIS = ""...
cmutel/constructive_geometries
constructive_geometries/cg.py
ConstructiveGeometries.check_data
python
def check_data(self): assert os.path.exists(self.data_fp) if gis: with fiona.drivers(): with fiona.open(self.faces_fp) as src: assert src.meta gpkg_hash = json.load(open(self.data_fp))['metadata']['sha256'] assert gpkg_hash == sha256(self....
Check that definitions file is present, and that faces file is readable.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L73-L82
[ "def sha256(filepath, blocksize=65536):\n \"\"\"Generate SHA 256 hash for file at `filepath`\"\"\"\n hasher = hashlib.sha256()\n fo = open(filepath, 'rb')\n buf = fo.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = fo.read(blocksize)\n return hasher.hexdigest()\n" ]
class ConstructiveGeometries(object): def __init__(self): self.data_fp = os.path.join(DATA_FILEPATH, "faces.json") self.faces_fp = os.path.join(DATA_FILEPATH, "faces.gpkg") self.check_data() self.load_definitions() def load_definitions(self): """Load mapping of country ...
cmutel/constructive_geometries
constructive_geometries/cg.py
ConstructiveGeometries.load_definitions
python
def load_definitions(self): self.data = dict(json.load(open(self.data_fp))['data']) self.all_faces = set(self.data.pop("__all__")) self.locations = set(self.data.keys())
Load mapping of country names to face ids
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L84-L88
null
class ConstructiveGeometries(object): def __init__(self): self.data_fp = os.path.join(DATA_FILEPATH, "faces.json") self.faces_fp = os.path.join(DATA_FILEPATH, "faces.gpkg") self.check_data() self.load_definitions() def check_data(self): """Check that definitions file is ...
cmutel/constructive_geometries
constructive_geometries/cg.py
ConstructiveGeometries.construct_rest_of_world
python
def construct_rest_of_world(self, excluded, name=None, fp=None, geom=True): for location in excluded: assert location in self.locations, "Can't find location {}".format(location) included = self.all_faces.difference( set().union(*[set(self.data[loc]) for loc in excluded]) ...
Construct rest-of-world geometry and optionally write to filepath ``fp``. Excludes faces in location list ``excluded``. ``excluded`` must be an iterable of location strings (not face ids).
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L90-L111
null
class ConstructiveGeometries(object): def __init__(self): self.data_fp = os.path.join(DATA_FILEPATH, "faces.json") self.faces_fp = os.path.join(DATA_FILEPATH, "faces.gpkg") self.check_data() self.load_definitions() def check_data(self): """Check that definitions file is ...
cmutel/constructive_geometries
constructive_geometries/cg.py
ConstructiveGeometries.construct_rest_of_worlds
python
def construct_rest_of_worlds(self, excluded, fp=None, use_mp=True, simplify=True): geoms = {} raw_data = [] for key in sorted(excluded): locations = excluded[key] for location in locations: assert location in self.locations, "Can't find location {}".format...
Construct many rest-of-world geometries and optionally write to filepath ``fp``. ``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L114-L141
null
class ConstructiveGeometries(object): def __init__(self): self.data_fp = os.path.join(DATA_FILEPATH, "faces.json") self.faces_fp = os.path.join(DATA_FILEPATH, "faces.gpkg") self.check_data() self.load_definitions() def check_data(self): """Check that definitions file is ...
cmutel/constructive_geometries
constructive_geometries/cg.py
ConstructiveGeometries.construct_rest_of_worlds_mapping
python
def construct_rest_of_worlds_mapping(self, excluded, fp=None): metadata = { 'filename': 'faces.gpkg', 'field': 'id', 'sha256': sha256(self.faces_fp) } data = [] for key, locations in excluded.items(): for location in locations: ...
Construct topo mapping file for ``excluded``. ``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``. Topo mapping has the data format: .. code-block:: python { 'data': [ ['location label', ...
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L143-L182
[ "def sha256(filepath, blocksize=65536):\n \"\"\"Generate SHA 256 hash for file at `filepath`\"\"\"\n hasher = hashlib.sha256()\n fo = open(filepath, 'rb')\n buf = fo.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = fo.read(blocksize)\n return hasher.hexdigest()\n" ]
class ConstructiveGeometries(object): def __init__(self): self.data_fp = os.path.join(DATA_FILEPATH, "faces.json") self.faces_fp = os.path.join(DATA_FILEPATH, "faces.gpkg") self.check_data() self.load_definitions() def check_data(self): """Check that definitions file is ...
cmutel/constructive_geometries
constructive_geometries/cg.py
ConstructiveGeometries.construct_difference
python
def construct_difference(self, parent, excluded, name=None, fp=None): assert parent in self.locations, "Can't find location {}".format(parent) for location in excluded: assert location in self.locations, "Can't find location {}".format(location) included = set(self.data[parent]).diff...
Construct geometry from ``parent`` without the regions in ``excluded`` and optionally write to filepath ``fp``. ``excluded`` must be an iterable of location strings (not face ids).
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L185-L200
null
class ConstructiveGeometries(object): def __init__(self): self.data_fp = os.path.join(DATA_FILEPATH, "faces.json") self.faces_fp = os.path.join(DATA_FILEPATH, "faces.gpkg") self.check_data() self.load_definitions() def check_data(self): """Check that definitions file is ...
cmutel/constructive_geometries
constructive_geometries/cg.py
ConstructiveGeometries.write_geoms_to_file
python
def write_geoms_to_file(self, fp, geoms, names=None): if fp[-5:] != '.gpkg': fp = fp + '.gpkg' if names is not None: assert len(geoms) == len(names), "Inconsistent length of geometries and names" else: names = ("Merged geometry {}".format(count) for count in i...
Write unioned geometries ``geoms`` to filepath ``fp``. Optionally use ``names`` in name field.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L203-L223
null
class ConstructiveGeometries(object): def __init__(self): self.data_fp = os.path.join(DATA_FILEPATH, "faces.json") self.faces_fp = os.path.join(DATA_FILEPATH, "faces.gpkg") self.check_data() self.load_definitions() def check_data(self): """Check that definitions file is ...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
resolved_row
python
def resolved_row(objs, geomatcher): def get_locations(lst): for elem in lst: try: yield elem['location'] except TypeError: yield elem geomatcher['RoW'] = geomatcher.faces.difference( reduce( set.union, [geomatcher[o...
Temporarily insert ``RoW`` into ``geomatcher.topology``, defined by the topo faces not used in ``objs``. Will overwrite any existing ``RoW``. On exiting the context manager, ``RoW`` is deleted.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L260-L280
[ "def get_locations(lst):\n for elem in lst:\n try:\n yield elem['location']\n except TypeError:\n yield elem\n" ]
from . import ConstructiveGeometries from collections.abc import MutableMapping from contextlib import contextmanager from functools import reduce import country_converter as coco class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as it...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
Geomatcher._actual_key
python
def _actual_key(self, key): if key in self or key in ("RoW", "GLO"): return key elif (self.default_namespace, key) in self: return (self.default_namespace, key) if isinstance(key, str) and self.coco: new = coco.convert(names=[key], to='ISO2', not_found=None) ...
Translate provided key into the key used in the topology. Tries the unmodified key, the key with the default namespace, and the country converter. Raises a ``KeyError`` if none of these finds a suitable definition in ``self.topology``.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L87-L102
null
class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as its base data a definition of the world split into topological faces. This definition is provided by the `constructive_geometries <>`__ library. A toplogical face is a polygon which do...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
Geomatcher._finish_filter
python
def _finish_filter(self, lst, key, include_self, exclusive, biggest_first): key = self._actual_key(key) locations = [x[0] for x in lst] if not include_self and key in locations: lst.pop(locations.index(key)) lst.sort(key=lambda x: x[1], reverse=biggest_first) lst = ...
Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L104-L132
[ "def _actual_key(self, key):\n \"\"\"Translate provided key into the key used in the topology. Tries the unmodified key, the key with the default namespace, and the country converter. Raises a ``KeyError`` if none of these finds a suitable definition in ``self.topology``.\"\"\"\n if key in self or key in (\"R...
class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as its base data a definition of the world split into topological faces. This definition is provided by the `constructive_geometries <>`__ library. A toplogical face is a polygon which do...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
Geomatcher.intersects
python
def intersects(self, key, include_self=False, exclusive=False, biggest_first=True, only=None): possibles = self.topology if only is None else {k: self[k] for k in only} if key == 'RoW' and 'RoW' not in self: return ['RoW'] if 'RoW' in possibles else [] faces = self[key] lst...
Get all locations that intersect this location. Note that sorting is done by first by number of faces intersecting ``key``; the total number of faces in the intersected region is only used to break sorting ties. If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial defini...
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L134-L153
[ "def _finish_filter(self, lst, key, include_self, exclusive, biggest_first):\n \"\"\"Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly.\"\"\"\n key = self._actual_key(key)\n locations = [x[0...
class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as its base data a definition of the world split into topological faces. This definition is provided by the `constructive_geometries <>`__ library. A toplogical face is a polygon which do...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
Geomatcher.contained
python
def contained(self, key, include_self=True, exclusive=False, biggest_first=True, only=None): if 'RoW' not in self: if key == 'RoW': return ['RoW'] if 'RoW' in (only or []) else [] elif only and 'RoW' in only: only.pop(only.index('RoW')) possibles ...
Get all locations that are completely within this location. If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``.contained("RoW")`` returns a list with either ``RoW`` or nothing.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L155-L175
[ "def _finish_filter(self, lst, key, include_self, exclusive, biggest_first):\n \"\"\"Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly.\"\"\"\n key = self._actual_key(key)\n locations = [x[0...
class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as its base data a definition of the world split into topological faces. This definition is provided by the `constructive_geometries <>`__ library. A toplogical face is a polygon which do...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
Geomatcher.within
python
def within(self, key, include_self=True, exclusive=False, biggest_first=True, only=None): possibles = self.topology if only is None else {k: self[k] for k in only} _ = lambda key: [key] if key in possibles else [] if 'RoW' not in self and key == 'RoW': answer = [] + _('RoW') + _('GLO...
Get all locations that completely contain this location. If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``RoW`` can only be contained by ``GLO`` and ``RoW``.
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L177-L195
[ "def _finish_filter(self, lst, key, include_self, exclusive, biggest_first):\n \"\"\"Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly.\"\"\"\n key = self._actual_key(key)\n locations = [x[0...
class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as its base data a definition of the world split into topological faces. This definition is provided by the `constructive_geometries <>`__ library. A toplogical face is a polygon which do...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
Geomatcher.split_face
python
def split_face(self, face, number=None, ids=None): assert face in self.faces if ids: ids = set(ids) else: max_int = max(x for x in self.faces if isinstance(x, int)) ids = set(range(max_int + 1, max_int + 1 + (number or 2))) for obj in self.topology.v...
Split a topological face into a number of small faces. * ``face``: The face to split. Must be in the topology. * ``number``: Number of new faces to create. Optional, can be inferred from ``ids``. Default is 2 new faces. * ``ids``: Iterable of new face ids. Optional, default is the maximum integ...
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L197-L223
null
class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as its base data a definition of the world split into topological faces. This definition is provided by the `constructive_geometries <>`__ library. A toplogical face is a polygon which do...
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
Geomatcher.add_definitions
python
def add_definitions(self, data, namespace, relative=True): if not relative: self.topology.update({(namespace, k): v for k, v in data.items()}) self.faces.update(set.union(*data.values())) else: self.topology.update({ (namespace, k): set.union(*[self[o]...
Add new topological definitions to ``self.topology``. If ``relative`` is true, then ``data`` is defined relative to the existing locations already in ``self.topology``, e.g. IMAGE: .. code-block:: python {"Russia Region": [ "AM", "AZ", "GE",...
train
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L225-L256
null
class Geomatcher(MutableMapping): """Object managing spatial relationships using the a world topology. ``Geomatcher`` takes as its base data a definition of the world split into topological faces. This definition is provided by the `constructive_geometries <>`__ library. A toplogical face is a polygon which do...
maxfischer2781/include
include/inhibit.py
DisabledIncludeTypes.disable
python
def disable(self, identifier, children_only=False): import_path = self._identifier2import_path(identifier=identifier) if not children_only and import_path not in self._disabled: self._disable_path(import_path) self._disabled.add(import_path) if import_path not in self._ch...
Disable an include type :param identifier: module or name of the include type :param children_only: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type: **module** (``include.files``...
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/inhibit.py#L66-L94
[ "def _write_child_disabled(self):\n os.environ[self.environment_key] = ','.join(self._children_disabled)\n", "def _disable_path(import_path):\n from . import _IMPORT_HOOKS\n if import_path in _IMPORT_HOOKS:\n sys.meta_path.remove(_IMPORT_HOOKS[import_path])\n _IMPORT_HOOKS[import_path] = _disab...
class DisabledIncludeTypes(object): """ Interface for disabling include types Meta-container to control disabled include types. The methods :py:meth:`disable` and :py:meth:`enable` allow to control which include types can be used. Disabled types cannot be used to import code, be it explicitly or i...
maxfischer2781/include
include/inhibit.py
DisabledIncludeTypes.enable
python
def enable(self, identifier, exclude_children=False): import_path = self._identifier2import_path(identifier=identifier) if import_path in self._disabled: self._enable_path(import_path) self._disabled.remove(import_path) if not exclude_children and import_path in self._chi...
Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type. See :py:m...
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/inhibit.py#L96-L112
[ "def _write_child_disabled(self):\n os.environ[self.environment_key] = ','.join(self._children_disabled)\n", "def _enable_path(import_path):\n from . import _IMPORT_HOOKS\n _disabled_loader = _IMPORT_HOOKS.pop(import_path)\n sys.meta_path.remove(_disabled_loader)\n", "def _identifier2import_path(sel...
class DisabledIncludeTypes(object): """ Interface for disabling include types Meta-container to control disabled include types. The methods :py:meth:`disable` and :py:meth:`enable` allow to control which include types can be used. Disabled types cannot be used to import code, be it explicitly or i...
maxfischer2781/include
include/inhibit.py
DisabledTypeLoader.load_module
python
def load_module(self, name): # allow reload noop if name in sys.modules: return sys.modules[name] raise DisabledIncludeError('Include type %r disabled, cannot import module %r' % (self._module_prefix, name))
Load and return a module If the module is already loaded, the existing module is returned. Otherwise, raises :py:exc:`DisabledIncludeError`.
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/inhibit.py#L184-L194
null
class DisabledTypeLoader(import_hook.BaseIncludeLoader): def uri2module(self, uri): """ Convert an unencoded source uri to an encoded module name Always raises :py:exc:`DisabledIncludeError`. """ raise DisabledIncludeError('Include type %r disabled' % self._module_prefix)
maxfischer2781/include
include/__init__.py
disable
python
def disable(identifier, children_only=False): DISABLED_TYPES.disable(identifier=identifier, children_only=children_only)
Disable an include type :param identifier: module or name of the include type :param children_only: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type. See :py:meth:`~.DisabledIncludeTypes.disable` ...
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/__init__.py#L68-L78
null
from __future__ import absolute_import import sys import weakref # weak reference to installed hooks _IMPORT_HOOKS = weakref.WeakValueDictionary() # must have _IMPORT_HOOKS to bootstrap hook disabling from .inhibit import DISABLED_TYPES def path(file_path): """ Include module code from a file identified by i...
maxfischer2781/include
include/__init__.py
enable
python
def enable(identifier, exclude_children=False): DISABLED_TYPES.enable(identifier=identifier, exclude_children=exclude_children)
Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type. See :py:meth:`~.DisabledI...
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/__init__.py#L81-L91
null
from __future__ import absolute_import import sys import weakref # weak reference to installed hooks _IMPORT_HOOKS = weakref.WeakValueDictionary() # must have _IMPORT_HOOKS to bootstrap hook disabling from .inhibit import DISABLED_TYPES def path(file_path): """ Include module code from a file identified by i...
maxfischer2781/include
include/encoded/import_hook.py
EncodedModuleLoader.module2uri
python
def module2uri(self, module_name): encoded_str = super(EncodedModuleLoader, self).module2uri(module_name) encoded = encoded_str.encode('ASCII') compressed = base64.b64decode(encoded, b'+&') return zlib.decompress(compressed)
Convert an encoded module name to an unencoded source uri
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/encoded/import_hook.py#L17-L22
[ "def module2uri(self, module_name):\n \"\"\"Convert an encoded module name to an unencoded source uri\"\"\"\n assert module_name.startswith(self.module_prefix), 'incompatible module name'\n path = module_name[len(self.module_prefix):]\n path = path.replace('&#DOT', '.')\n return path.replace('&#SEP',...
class EncodedModuleLoader(import_hook.BaseIncludeLoader): """ Load python modules from their encoded content This import hook allows storing and using module content as a compressed data blob. """ def uri2module(self, uri): """Convert an unencoded source uri to an encoded module name"...
maxfischer2781/include
include/encoded/import_hook.py
EncodedModuleLoader.uri2module
python
def uri2module(self, uri): # uri is the source code of the module compressed = zlib.compress(uri) encoded = base64.b64encode(compressed, b'+&') encoded_str = encoded.decode('ASCII') return super(EncodedModuleLoader, self).uri2module(encoded_str)
Convert an unencoded source uri to an encoded module name
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/encoded/import_hook.py#L24-L30
[ "def uri2module(self, uri):\n \"\"\"Convert an unencoded source uri to an encoded module name\"\"\"\n module_name = uri.replace('.', '&#DOT')\n module_name = module_name.replace(os.sep, '&#SEP')\n return self.module_prefix + module_name\n" ]
class EncodedModuleLoader(import_hook.BaseIncludeLoader): """ Load python modules from their encoded content This import hook allows storing and using module content as a compressed data blob. """ def module2uri(self, module_name): """Convert an encoded module name to an unencoded sourc...
maxfischer2781/include
include/encoded/import_hook.py
EncodedModuleLoader.load_module
python
def load_module(self, name): if name in sys.modules: return sys.modules[name] module_source = self.module2uri(name) module_container = tempfile.NamedTemporaryFile(suffix='.py', delete=False) with module_container: module_container.write(module_source) ...
Load and return a module Always returns the corresponding module. If the module is already loaded, the existing module is returned.
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/encoded/import_hook.py#L32-L50
[ "def module2uri(self, module_name):\n \"\"\"Convert an encoded module name to an unencoded source uri\"\"\"\n encoded_str = super(EncodedModuleLoader, self).module2uri(module_name)\n encoded = encoded_str.encode('ASCII')\n compressed = base64.b64decode(encoded, b'+&')\n return zlib.decompress(compres...
class EncodedModuleLoader(import_hook.BaseIncludeLoader): """ Load python modules from their encoded content This import hook allows storing and using module content as a compressed data blob. """ def module2uri(self, module_name): """Convert an encoded module name to an unencoded sourc...
maxfischer2781/include
include/mount/__init__.py
MountLoader.load_module
python
def load_module(self, name): if name in sys.modules: return sys.modules[name] # load the actual import hook module module_name = self.mount2name(name) __import__(module_name) # alias the import hook module to the mount, so both can be used interchangeably modu...
Load and return a module
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L9-L19
[ "def mount2name(self, mount):\n \"\"\"Convert a mount name to a module name\"\"\"\n if not self.is_mount(mount):\n raise ValueError('%r is not a supported mount name' % (mount,))\n return mount.replace(self.mount_prefix, self.module_prefix)\n" ]
class MountLoader(object): def __init__(self, mount_prefix, module_prefix): self.mount_prefix = mount_prefix self.module_prefix = module_prefix def find_module(self, name, path=None): if name.startswith(self.mount_prefix) and name.count('.') - self.mount_prefix.count('.') == 1: ...
maxfischer2781/include
include/mount/__init__.py
MountLoader.is_module
python
def is_module(self, name): if self.module_prefix.startswith(self.mount_prefix): return name.startswith(self.module_prefix) return name.startswith(self.module_prefix) and not name.startswith(self.mount_prefix)
Test that `name` is a module name
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L26-L30
null
class MountLoader(object): def __init__(self, mount_prefix, module_prefix): self.mount_prefix = mount_prefix self.module_prefix = module_prefix def load_module(self, name): """Load and return a module""" if name in sys.modules: return sys.modules[name] # load...
maxfischer2781/include
include/mount/__init__.py
MountLoader.is_mount
python
def is_mount(self, name): if self.mount_prefix.startswith(self.module_prefix): return name.startswith(self.mount_prefix) return name.startswith(self.mount_prefix) and not name.startswith(self.module_prefix)
Test that `name` is a mount name
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L32-L36
null
class MountLoader(object): def __init__(self, mount_prefix, module_prefix): self.mount_prefix = mount_prefix self.module_prefix = module_prefix def load_module(self, name): """Load and return a module""" if name in sys.modules: return sys.modules[name] # load...
maxfischer2781/include
include/mount/__init__.py
MountLoader.name2mount
python
def name2mount(self, name): if not self.is_module(name): raise ValueError('%r is not a supported module name' % (name, )) return name.replace(self.module_prefix, self.mount_prefix)
Convert a module name to a mount name
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L38-L42
[ "def is_module(self, name):\n \"\"\"Test that `name` is a module name\"\"\"\n if self.module_prefix.startswith(self.mount_prefix):\n return name.startswith(self.module_prefix)\n return name.startswith(self.module_prefix) and not name.startswith(self.mount_prefix)\n" ]
class MountLoader(object): def __init__(self, mount_prefix, module_prefix): self.mount_prefix = mount_prefix self.module_prefix = module_prefix def load_module(self, name): """Load and return a module""" if name in sys.modules: return sys.modules[name] # load...
maxfischer2781/include
include/mount/__init__.py
MountLoader.mount2name
python
def mount2name(self, mount): if not self.is_mount(mount): raise ValueError('%r is not a supported mount name' % (mount,)) return mount.replace(self.mount_prefix, self.module_prefix)
Convert a mount name to a module name
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L44-L48
[ "def is_mount(self, name):\n \"\"\"Test that `name` is a mount name\"\"\"\n if self.mount_prefix.startswith(self.module_prefix):\n return name.startswith(self.mount_prefix)\n return name.startswith(self.mount_prefix) and not name.startswith(self.module_prefix)\n" ]
class MountLoader(object): def __init__(self, mount_prefix, module_prefix): self.mount_prefix = mount_prefix self.module_prefix = module_prefix def load_module(self, name): """Load and return a module""" if name in sys.modules: return sys.modules[name] # load...
maxfischer2781/include
include/base/import_hook.py
BaseIncludeLoader.module2uri
python
def module2uri(self, module_name): assert module_name.startswith(self.module_prefix), 'incompatible module name' path = module_name[len(self.module_prefix):] path = path.replace('&#DOT', '.') return path.replace('&#SEP', os.sep)
Convert an encoded module name to an unencoded source uri
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/base/import_hook.py#L47-L52
null
class BaseIncludeLoader(object): """ Import hook to load Python modules from an arbitrary location :param module_prefix: prefix for modules to import :type module_prefix: str Base class for import hooks to non-standard code sources. Implements the general structure for encoded sources: a modul...
maxfischer2781/include
include/base/import_hook.py
BaseIncludeLoader.uri2module
python
def uri2module(self, uri): module_name = uri.replace('.', '&#DOT') module_name = module_name.replace(os.sep, '&#SEP') return self.module_prefix + module_name
Convert an unencoded source uri to an encoded module name
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/base/import_hook.py#L54-L58
null
class BaseIncludeLoader(object): """ Import hook to load Python modules from an arbitrary location :param module_prefix: prefix for modules to import :type module_prefix: str Base class for import hooks to non-standard code sources. Implements the general structure for encoded sources: a modul...
maxfischer2781/include
include/base/import_hook.py
BaseIncludeLoader.find_module
python
def find_module(self, fullname, path=None): # path points to the top-level package path if any # and we can only import sub-modules/-packages if path is None: return if fullname.startswith(self.module_prefix): return self else: return None
Find the appropriate loader for module ``name`` :param fullname: ``__name__`` of the module to import :type fullname: str :param path: ``__path__`` of the *parent* package already imported :type path: str or None
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/base/import_hook.py#L69-L85
null
class BaseIncludeLoader(object): """ Import hook to load Python modules from an arbitrary location :param module_prefix: prefix for modules to import :type module_prefix: str Base class for import hooks to non-standard code sources. Implements the general structure for encoded sources: a modul...
maxfischer2781/include
include/files/import_hook.py
FilePathLoader.load_module
python
def load_module(self, name): if name in sys.modules: return sys.modules[name] path = self.module2uri(name) if os.path.isfile(path): return self._load_module(name, path) elif os.path.isdir(path): return self._load_package(name, path) else: ...
Load and return a module Always returns the corresponding module. If the module is already loaded, the existing module is returned.
train
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/files/import_hook.py#L15-L30
[ "def module2uri(self, module_name):\n \"\"\"Convert an encoded module name to an unencoded source uri\"\"\"\n assert module_name.startswith(self.module_prefix), 'incompatible module name'\n path = module_name[len(self.module_prefix):]\n path = path.replace('&#DOT', '.')\n return path.replace('&#SEP',...
class FilePathLoader(import_hook.BaseIncludeLoader): """ Load python file from their path This import hook allows using encoded paths as module names to load modules directly from their file. """ def _load_module(self, name, path): module = imp.load_source(name, path) module._...
jspricke/python-abook
abook.py
abook2vcf
python
def abook2vcf(): from argparse import ArgumentParser, FileType from os.path import expanduser from sys import stdout parser = ArgumentParser(description='Converter from Abook to vCard syntax.') parser.add_argument('infile', nargs='?', default=expanduser('~/.abook/addressbook'), ...
Command line tool to convert from Abook to vCard
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L328-L341
[ "def to_vcf(self):\n \"\"\" Converts to vCard string\"\"\"\n return '\\r\\n'.join([v.serialize() for v in self.to_vcards()])\n" ]
# Python library to convert between Abook and vCard # # Copyright (C) 2013-2018 Jochen Sprickerhof # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
jspricke/python-abook
abook.py
vcf2abook
python
def vcf2abook(): from argparse import ArgumentParser, FileType from sys import stdin parser = ArgumentParser(description='Converter from vCard to Abook syntax.') parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin, help='Input vCard file (default: stdin)')...
Command line tool to convert from vCard to Abook
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L344-L356
[ "def abook_file(vcard, bookfile):\n \"\"\"Write a new Abook file with the given vcards\"\"\"\n book = ConfigParser(default_section='format')\n\n book['format'] = {}\n book['format']['program'] = 'abook'\n book['format']['version'] = '0.6.1'\n\n for (i, card) in enumerate(readComponents(vcard.read(...
# Python library to convert between Abook and vCard # # Copyright (C) 2013-2018 Jochen Sprickerhof # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
jspricke/python-abook
abook.py
Abook._update
python
def _update(self): with self._lock: if getmtime(self._filename) > self._last_modified: self._last_modified = getmtime(self._filename) self._book = ConfigParser(default_section='format') self._book.read(self._filename)
Update internal state.
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L42-L48
null
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.append_vobject
python
def append_vobject(self, vcard, filename=None): book = ConfigParser(default_section='format') with self._lock: book.read(self._filename) section = str(max([-1] + [int(k) for k in book.sections()]) + 1) Abook.to_abook(vcard, section, book, self._filename) w...
Appends an address to the Abook addressbook vcard -- vCard to append filename -- unused return the new UID of the appended vcard
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L58-L72
[ "def _gen_uid(entry):\n \"\"\"Generates a UID based on the index in the Abook file\n Not that the index is just a number and abook tends to regenerate it upon sorting.\n \"\"\"\n return '%s@%s' % (entry.name, getfqdn())\n", "def to_abook(card, section, book, bookfile=None):\n \"\"\"Converts a vCard...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.remove
python
def remove(self, uid, filename=None): book = ConfigParser(default_section='format') with self._lock: book.read(self._filename) del book[uid.split('@')[0]] with open(self._filename, 'w') as fp: book.write(fp, False)
Removes an address to the Abook addressbook uid -- UID of the entry to remove
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L74-L83
null
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.replace_vobject
python
def replace_vobject(self, uid, vcard, filename=None): entry = uid.split('@')[0] book = ConfigParser(default_section='format') with self._lock: book.read(self._filename) Abook.to_abook(vcard, entry, book, self._filename) with open(self._filename, 'w') as fp: ...
Updates an address to the Abook addressbook uid -- uid of the entry to replace vcard -- vCard of the new content filename -- unused
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L89-L104
[ "def _gen_uid(entry):\n \"\"\"Generates a UID based on the index in the Abook file\n Not that the index is just a number and abook tends to regenerate it upon sorting.\n \"\"\"\n return '%s@%s' % (entry.name, getfqdn())\n", "def to_abook(card, section, book, bookfile=None):\n \"\"\"Converts a vCard...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....