INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
calls map to shift the recover execution to flat_map_nvim_io
def nvim_io_recover(self, io: NvimIORecover[A]) -> NvimIO[B]: '''calls `map` to shift the recover execution to flat_map_nvim_io ''' return eval_step(self.vim)(io.map(lambda a: a))
Read codeml file.
def read_codeml_output( filename, df, altall_cutoff=0.2, ): """Read codeml file. """ # Read paml output. with open(filename, 'r') as f: data = f.read() # Rip all trees out of the codeml output. regex = re.compile('\([()\w\:. ,]+;') trees = regex.findall(data) anc_tree = trees[2] # First tree in codeml file is the original input tree tip_tree = dendropy.Tree.get(data=trees[0], schema='newick') # Third tree in codeml fule is ancestor tree. anc_tree = dendropy.Tree.get(data=trees[2], schema='newick') # Main tree to return tree = tip_tree # Map ancestors onto main tree object ancestors = anc_tree.internal_nodes() for i, node in enumerate(tree.internal_nodes()): node.label = ancestors[i].label # Map nodes onto dataframe. df['reconstruct_label'] = None for node in tree.postorder_node_iter(): # Ignore parent node if node.parent_node is None: pass elif node.is_leaf(): node_label = node.taxon.label parent_label = node.parent_node.label # Set node label. df.loc[df.uid == node_label, 'reconstruct_label'] = node_label # Set parent label. parent_id = df.loc[df.uid == node_label, 'parent'].values[0] df.loc[df.id == parent_id, 'reconstruct_label'] = node.parent_node.label elif node.is_internal(): label = node.label parent_id = df.loc[df.reconstruct_label == label, 'parent'].values[0] df.loc[df.id == parent_id, 'reconstruct_label'] = node.parent_node.label # Compile a regular expression to find blocks of data for internal nodes node_regex = re.compile("""Prob distribution at node [0-9]+, by site[-\w():.\s]+\n""") # Strip the node number from this block of data. node_num_regex = re.compile("[0-9]+") # Get dataframes for all ancestors. df['ml_sequence'] = None df['ml_posterior'] = None df['alt_sequence'] = None df['alt_posterior'] = None for node in node_regex.findall(data): # Get node label node_label = node_num_regex.search(node).group(0) # Compile regex for matching site data site_regex = re.compile("(?:\w\(\w.\w{3}\) )+") # Iterate through each match for site data. ml_sequence, ml_posterior, alt_sequence, alt_posterior = [], [], [], [] for site in site_regex.findall(node): # Iterate through residues scores = [float(site[i+2:i+7]) for i in range(0,len(site), 9)] residues = [site[i] for i in range(0, len(site), 9)] # Get the indices of sorted scores sorted_score_index = [i[0] for i in sorted( enumerate(scores), key=lambda x:x[1], reverse=True)] ml_idx = sorted_score_index[0] alt_idx = sorted_score_index[1] # Should we keep alterative site. ml_sequence.append(residues[ml_idx]) ml_posterior.append(scores[ml_idx]) if scores[alt_idx] < altall_cutoff: alt_idx = ml_idx alt_sequence.append(residues[alt_idx]) alt_posterior.append(scores[alt_idx]) keys = [ "ml_sequence", "ml_posterior", "alt_sequence", "alt_posterior" ] vals = [ "".join(ml_sequence), sum(ml_posterior) / len(ml_posterior), "".join(alt_sequence), sum(alt_posterior) / len(alt_posterior), ] df.loc[df.reconstruct_label == node_label, keys] = vals return df
Always return a stripped string localized if possible
def ugettext(message, context=None): """Always return a stripped string, localized if possible""" stripped = strip_whitespace(message) message = add_context(context, stripped) if context else stripped ret = django_ugettext(message) # If the context isn't found, we need to return the string without it return stripped if ret == message else ret
Always return a stripped string localized if possible
def ungettext(singular, plural, number, context=None): """Always return a stripped string, localized if possible""" singular_stripped = strip_whitespace(singular) plural_stripped = strip_whitespace(plural) if context: singular = add_context(context, singular_stripped) plural = add_context(context, plural_stripped) else: singular = singular_stripped plural = plural_stripped ret = django_nugettext(singular, plural, number) # If the context isn't found, the string is returned as it came if ret == singular: return singular_stripped elif ret == plural: return plural_stripped return ret
Install our gettext and ngettext functions into Jinja2 s environment.
def install_jinja_translations(): """ Install our gettext and ngettext functions into Jinja2's environment. """ class Translation(object): """ We pass this object to jinja so it can find our gettext implementation. If we pass the GNUTranslation object directly, it won't have our context and whitespace stripping action. """ ugettext = staticmethod(ugettext) ungettext = staticmethod(ungettext) import jingo jingo.env.install_gettext_translations(Translation)
Override django s utils. translation. activate (). Django forces files to be named django. mo ( http:// code. djangoproject. com/ ticket/ 6376 ). Since that s dumb and we want to be able to load different files depending on what part of the site the user is in we ll make our own function here.
def activate(locale): """ Override django's utils.translation.activate(). Django forces files to be named django.mo (http://code.djangoproject.com/ticket/6376). Since that's dumb and we want to be able to load different files depending on what part of the site the user is in, we'll make our own function here. """ if INSTALL_JINJA_TRANSLATIONS: install_jinja_translations() if django.VERSION >= (1, 3): django_trans._active.value = _activate(locale) else: from django.utils.thread_support import currentThread django_trans._active[currentThread()] = _activate(locale)
We piggyback on jinja2 s babel_extract () ( really Babel s extract_ * functions ) but they don t support some things we need so this function will tweak the message. Specifically:
def tweak_message(message): """We piggyback on jinja2's babel_extract() (really, Babel's extract_* functions) but they don't support some things we need so this function will tweak the message. Specifically: 1) We strip whitespace from the msgid. Jinja2 will only strip whitespace from the ends of a string so linebreaks show up in your .po files still. 2) Babel doesn't support context (msgctxt). We hack that in ourselves here. """ if isinstance(message, basestring): message = strip_whitespace(message) elif isinstance(message, tuple): # A tuple of 2 has context, 3 is plural, 4 is plural with context if len(message) == 2: message = add_context(message[1], message[0]) elif len(message) == 3: if all(isinstance(x, basestring) for x in message[:2]): singular, plural, num = message message = (strip_whitespace(singular), strip_whitespace(plural), num) elif len(message) == 4: singular, plural, num, ctxt = message message = (add_context(ctxt, strip_whitespace(singular)), add_context(ctxt, strip_whitespace(plural)), num) return message
this is the central unsafe function using a lock and updating the state in guard in - place.
def exclusive_ns(guard: StateGuard[A], desc: str, thunk: Callable[..., NS[A, B]], *a: Any) -> Do: '''this is the central unsafe function, using a lock and updating the state in `guard` in-place. ''' yield guard.acquire() log.debug2(lambda: f'exclusive: {desc}') state, response = yield N.ensure_failure(thunk(*a).run(guard.state), guard.release) yield N.delay(lambda v: unsafe_update_state(guard, state)) yield guard.release() log.debug2(lambda: f'release: {desc}') yield N.pure(response)
Calculate a percentage.
def _percent(data, part, total): """ Calculate a percentage. """ try: return round(100 * float(data[part]) / float(data[total]), 1) except ZeroDivisionError: return 0
Get stats info.
def _get_cache_stats(server_name=None): """ Get stats info. """ server_info = {} for svr in mc_client.get_stats(): svr_info = svr[0].split(' ') svr_name = svr_info[0] svr_stats = svr[1] svr_stats['bytes_percent'] = _percent(svr_stats, 'bytes', 'limit_maxbytes') svr_stats['get_hit_rate'] = _percent(svr_stats, 'get_hits', 'cmd_get') svr_stats['get_miss_rate'] = _percent(svr_stats, 'get_misses', 'cmd_get') if server_name and server_name == svr_name: return svr_stats server_info[svr_name] = svr_stats return server_info
Get slabs info.
def _get_cache_slabs(server_name=None): """ Get slabs info. """ server_info = {} for svr in mc_client.get_slabs(): svr_info = svr[0].split(' ') svr_name = svr_info[0] if server_name and server_name == svr_name: return svr[1] server_info[svr_name] = svr[1] return server_info
Add admin global context for compatibility with Django 1. 7
def _context_data(data, request=None): """ Add admin global context, for compatibility with Django 1.7 """ try: return dict(site.each_context(request).items() + data.items()) except AttributeError: return data
Return the status of all servers.
def server_status(request): """ Return the status of all servers. """ data = { 'cache_stats': _get_cache_stats(), 'can_get_slabs': hasattr(mc_client, 'get_slabs'), } return render_to_response('memcache_admin/server_status.html', data, RequestContext(request))
Show the dashboard.
def dashboard(request): """ Show the dashboard. """ # mc_client will be a dict if memcached is not configured if not isinstance(mc_client, dict): cache_stats = _get_cache_stats() else: cache_stats = None if cache_stats: data = _context_data({ 'title': _('Memcache Dashboard'), 'cache_stats': cache_stats, 'can_get_slabs': hasattr(mc_client, 'get_slabs'), 'REFRESH_RATE': SETTINGS['REFRESH_RATE'], }, request) template = 'memcache_admin/dashboard.html' else: data = _context_data({ 'title': _('Memcache Dashboard - Error'), 'error_message': _('Unable to connect to a memcache server.'), }, request) template = 'memcache_admin/dashboard_error.html' return render_to_response(template, data, RequestContext(request))
Show server statistics.
def stats(request, server_name): """ Show server statistics. """ server_name = server_name.strip('/') data = _context_data({ 'title': _('Memcache Statistics for %s') % server_name, 'cache_stats': _get_cache_stats(server_name), }, request) return render_to_response('memcache_admin/stats.html', data, RequestContext(request))
Show server slabs.
def slabs(request, server_name): """ Show server slabs. """ data = _context_data({ 'title': _('Memcache Slabs for %s') % server_name, 'cache_slabs': _get_cache_slabs(server_name), }, request) return render_to_response('memcache_admin/slabs.html', data, RequestContext(request))
Convert a byte value into a human - readable format.
def human_bytes(value): """ Convert a byte value into a human-readable format. """ value = float(value) if value >= 1073741824: gigabytes = value / 1073741824 size = '%.2f GB' % gigabytes elif value >= 1048576: megabytes = value / 1048576 size = '%.2f MB' % megabytes elif value >= 1024: kilobytes = value / 1024 size = '%.2f KB' % kilobytes else: size = '%.2f B' % value return size
Find a config in our children so we can fill in variables in our other children with its data.
def find_config(self, children): """ Find a config in our children so we can fill in variables in our other children with its data. """ named_config = None found_config = None # first see if we got a kwarg named 'config', as this guy is special if 'config' in children: if type(children['config']) == str: children['config'] = ConfigFile(children['config']) elif isinstance(children['config'], Config): children['config'] = children['config'] elif type(children['config']) == dict: children['config'] = Config(data=children['config']) else: raise TypeError("Don't know how to turn {} into a Config".format(type(children['config']))) named_config = children['config'] # next check the other kwargs for k in children: if isinstance(children[k], Config): found_config = children[k] # if we still don't have a config, see if there's a directory with one for k in children: if isinstance(children[k], Directory): for j in children[k]._children: if j == 'config' and not named_config: named_config = children[k]._children[j] if isinstance(children[k]._children[j], Config): found_config = children[k]._children[j] if named_config: return named_config else: return found_config
Add objects to the environment.
def add(self, **kwargs): """ Add objects to the environment. """ for key in kwargs: if type(kwargs[key]) == str: self._children[key] = Directory(kwargs[key]) else: self._children[key] = kwargs[key] self._children[key]._env = self self._children[key].apply_config(ConfigApplicator(self.config)) self._children[key].prepare()
Replace any config tokens in the file s path with values from the config.
def apply_config(self, applicator): """ Replace any config tokens in the file's path with values from the config. """ if type(self._fpath) == str: self._fpath = applicator.apply(self._fpath)
Get the path to the file relative to its parent.
def path(self): """ Get the path to the file relative to its parent. """ if self._parent: return os.path.join(self._parent.path, self._fpath) else: return self._fpath
Read and return the contents of the file.
def read(self): """ Read and return the contents of the file. """ with open(self.path) as f: d = f.read() return d
Write data to the file.
def write(self, data, mode='w'): """ Write data to the file. `data` is the data to write `mode` is the mode argument to pass to `open()` """ with open(self.path, mode) as f: f.write(data)
Configure the Python logging module for this file.
def configure(self): """ Configure the Python logging module for this file. """ # build a file handler for this file handler = logging.FileHandler(self.path, delay=True) # if we got a format string, create a formatter with it if self._format: handler.setFormatter(logging.Formatter(self._format)) # if we got a string for the formatter, assume it's the name of a # formatter in the environment's config if type(self._formatter) == str: if self._env and self._env.config.logging.dict_config.formatters[self._formatter]: d = self._env.config.logging.dict_config.formatters[self._formatter].to_dict() handler.setFormatter(logging.Formatter(**d)) elif type(self._formatter) == dict: # if it's a dict it must be the actual formatter params handler.setFormatter(logging.Formatter(**self._formatter)) # add the file handler to whatever loggers were specified if len(self._loggers): for name in self._loggers: logging.getLogger(name).addHandler(handler) else: # none specified, just add it to the root logger logging.getLogger().addHandler(handler)
Create the file.
def create(self): """ Create the file. If the file already exists an exception will be raised """ if not os.path.exists(self.path): open(self.path, 'a').close() else: raise Exception("File exists: {}".format(self.path))
Replace any config tokens with values from the config.
def apply_config(self, applicator): """ Replace any config tokens with values from the config. """ if type(self._path) == str: self._path = applicator.apply(self._path) for key in self._children: self._children[key].apply_config(applicator)
Return the path to this directory.
def path(self): """ Return the path to this directory. """ p = '' if self._parent and self._parent.path: p = os.path.join(p, self._parent.path) if self._base: p = os.path.join(p, self._base) if self._path: p = os.path.join(p, self._path) return p
Remove the directory.
def remove(self, recursive=True, ignore_error=True): """ Remove the directory. """ try: if recursive or self._cleanup == 'recursive': shutil.rmtree(self.path) else: os.rmdir(self.path) except Exception as e: if not ignore_error: raise e
Prepare the Directory for use in an Environment.
def prepare(self): """ Prepare the Directory for use in an Environment. This will create the directory if the create flag is set. """ if self._create: self.create() for k in self._children: self._children[k]._env = self._env self._children[k].prepare()
Clean up children and remove the directory.
def cleanup(self): """ Clean up children and remove the directory. Directory will only be removed if the cleanup flag is set. """ for k in self._children: self._children[k].cleanup() if self._cleanup: self.remove(True)
Find the path to something inside this directory.
def path_to(self, path): """ Find the path to something inside this directory. """ return os.path.join(self.path, str(path))
List the contents of the directory.
def list(self): """ List the contents of the directory. """ return [File(f, parent=self) for f in os.listdir(self.path)]
Write to a file in the directory.
def write(self, filename, data, mode='w'): """ Write to a file in the directory. """ with open(self.path_to(str(filename)), mode) as f: f.write(data)
Read a file from the directory.
def read(self, filename): """ Read a file from the directory. """ with open(self.path_to(str(filename))) as f: d = f.read() return d
Add objects to the directory.
def add(self, *args, **kwargs): """ Add objects to the directory. """ for key in kwargs: if isinstance(kwargs[key], str): self._children[key] = File(kwargs[key]) else: self._children[key] = kwargs[key] self._children[key]._parent = self self._children[key]._env = self._env added = [] for arg in args: if isinstance(arg, File): self._children[arg.name] = arg self._children[arg.name]._parent = self self._children[arg.name]._env = self._env elif isinstance(arg, str): f = File(arg) added.append(f) self._children[arg] = f self._children[arg]._parent = self self._children[arg]._env = self._env else: raise TypeError(type(arg)) # if we were passed a single file/filename, return the File object for convenience if len(added) == 1: return added[0] if len(args) == 1: return args[0]
Save the state to a file.
def save(self): """ Save the state to a file. """ with open(self.path, 'w') as f: f.write(yaml.dump(dict(self.d)))
Load a saved state file.
def load(self): """ Load a saved state file. """ if os.path.exists(self.path): with open(self.path, 'r') as f: self.d = yaml.safe_load(f.read().replace('\t', ' '*4))
Clean up the saved state.
def cleanup(self): """ Clean up the saved state. """ if os.path.exists(self.path): os.remove(self.path)
Loads plugins from the specified directory.
def load_plugins(self, directory): """ Loads plugins from the specified directory. `directory` is the full path to a directory containing python modules which each contain a subclass of the Plugin class. There is no criteria for a valid plugin at this level - any python module found in the directory will be loaded. Only modules that implement a subclass of the Plugin class above will be collected. The directory will be traversed recursively. """ # walk directory for filename in os.listdir(directory): # path to file filepath = os.path.join(directory, filename) # if it's a file, load it modname, ext = os.path.splitext(filename) if os.path.isfile(filepath) and ext == '.py': file, path, descr = imp.find_module(modname, [directory]) if file: mod = imp.load_module(modname, file, path, descr) # if it's a directory, recurse into it if os.path.isdir(filepath): self.load_plugins(filepath)
Recursively merge values from a nested dictionary into another nested dictionary.
def update_dict(target, source): """ Recursively merge values from a nested dictionary into another nested dictionary. For example: >>> target = { ... 'thing': 123, ... 'thang': { ... 'a': 1, ... 'b': 2 ... } ... } >>> source = { ... 'thang': { ... 'a': 666, ... 'c': 777 ... } ... } >>> update_dict(target, source) >>> target { 'thing': 123, 'thang': { 'a': 666, 'b': 2, 'c': 777 } } """ for k,v in source.items(): if isinstance(v, dict) and k in target and isinstance(source[k], dict): update_dict(target[k], v) else: target[k] = v
Return a ConfigNode object representing a child node with the specified relative path.
def _child(self, path): """ Return a ConfigNode object representing a child node with the specified relative path. """ if self._path: path = '{}.{}'.format(self._path, path) return ConfigNode(root=self._root, path=path)
Returns a tuple of a reference to the last container in the path and the last component in the key path.
def _resolve_path(self, create=False): """ Returns a tuple of a reference to the last container in the path, and the last component in the key path. For example, with a self._value like this: { 'thing': { 'another': { 'some_leaf': 5, 'one_more': { 'other_leaf': 'x' } } } } And a self._path of: 'thing.another.some_leaf' This will return a tuple of a reference to the 'another' dict, and 'some_leaf', allowing the setter and casting methods to directly access the item referred to by the key path. """ # Split up the key path if type(self._path) == str: key_path = self._path.split('.') else: key_path = [self._path] # Start at the root node node = self._root._data nodes = [self._root._data] # Traverse along key path while len(key_path): # Get the next key in the key path key = key_path.pop(0) # See if the test could be an int for array access, if so assume it is try: key = int(key) except: pass # If the next level doesn't exist, create it if create: if type(node) == dict and key not in node: node[key] = {} elif type(node) == list and type(key) == int and len(node) < key: node.append([None for i in range(key-len(node))]) # Store the last node and traverse down the hierarchy nodes.append(node) try: node = node[key] except TypeError: if type(key) == int: raise IndexError(key) else: raise KeyError(key) return (nodes[-1], key)
Get the value represented by this node.
def _get_value(self): """ Get the value represented by this node. """ if self._path: try: container, last = self._resolve_path() return container[last] except KeyError: return None except IndexError: return None else: return self._data
Update the configuration with new data.
def update(self, data={}, options={}): """ Update the configuration with new data. This can be passed either or both `data` and `options`. `options` is a dict of keypath/value pairs like this (similar to CherryPy's config mechanism: >>> c.update(options={ ... 'server.port': 8080, ... 'server.host': 'localhost', ... 'admin.email': 'admin@lol' ... }) `data` is a dict of actual config data, like this: >>> c.update(data={ ... 'server': { ... 'port': 8080, ... 'host': 'localhost' ... }, ... 'admin': { ... 'email': 'admin@lol' ... } ... }) """ # Handle an update with a set of options like CherryPy does for key in options: self[key] = options[key] # Merge in any data in `data` if isinstance(data, ConfigNode): data = data._get_value() update_dict(self._get_value(), data)
Load the config and defaults from files.
def load(self, reload=False): """ Load the config and defaults from files. """ if reload or not self._loaded: # load defaults if self._defaults_file and type(self._defaults_file) == str: self._defaults_file = File(self._defaults_file, parent=self._parent) defaults = {} if self._defaults_file: defaults = yaml.safe_load(self._defaults_file.read().replace('\t', ' ')) # load data data = {} if self.exists: data = yaml.safe_load(self.read().replace('\t', ' ')) # initialise with the loaded data self._defaults = defaults self._data = copy.deepcopy(self._defaults) self.update(data=data) # if specified, apply environment variables if self._apply_env: self.update(ConfigEnv(self._env_prefix)) self._loaded = True return self
Apply the config to a string.
def apply_to_str(self, obj): """ Apply the config to a string. """ toks = re.split('({config:|})', obj) newtoks = [] try: while len(toks): tok = toks.pop(0) if tok == '{config:': # pop the config variable, look it up var = toks.pop(0) val = self.config[var] # if we got an empty node, then it didn't exist if type(val) == ConfigNode and val == None: raise KeyError("No such config variable '{}'".format(var)) # add the value to the list newtoks.append(str(val)) # pop the '}' toks.pop(0) else: # not the start of a config block, just append it to the list newtoks.append(tok) return ''.join(newtoks) except IndexError: pass return obj
View decorator to validate requests from Twilio per http:// www. twilio. com/ docs/ security.
def validate_twilio_signature(func=None, backend_name='twilio-backend'): """View decorator to validate requests from Twilio per http://www.twilio.com/docs/security.""" def _dec(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): backend = kwargs.get('backend_name', backend_name) config = settings.INSTALLED_BACKENDS[backend]['config'] validator = RequestValidator(config['auth_token']) signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '') url = request.build_absolute_uri() body = {} if request.method == 'POST': body = request.POST require_validation = config.get('validate', True) if validator.validate(url, body, signature) or not require_validation: return view_func(request, *args, **kwargs) else: return HttpResponseBadRequest() return _wrapped_view if func is None: return _dec else: return _dec(func)
Build Twilio callback url for confirming message delivery status
def build_callback_url(request, urlname, message): """ Build Twilio callback url for confirming message delivery status :type message: OutgoingSMS """ location = reverse(urlname, kwargs={"pk": message.pk}) callback_domain = getattr(settings, "TWILIO_CALLBACK_DOMAIN", None) if callback_domain: url = "{}://{}{}".format( "https" if getattr(settings, "TWILIO_CALLBACK_USE_HTTPS", False) else "http", callback_domain, location ) elif request is not None: url = request.build_absolute_uri(location) else: raise ValueError( "Unable to build callback url. Configure TWILIO_CALLBACK_DOMAIN " "or pass request object to function call" ) return url
Create: class: OutgoingSMS object and send SMS using Twilio.
def send_sms(request, to_number, body, callback_urlname="sms_status_callback"): """ Create :class:`OutgoingSMS` object and send SMS using Twilio. """ client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) from_number = settings.TWILIO_PHONE_NUMBER message = OutgoingSMS.objects.create( from_number=from_number, to_number=to_number, body=body, ) status_callback = None if callback_urlname: status_callback = build_callback_url(request, callback_urlname, message) logger.debug("Sending SMS message to %s with callback url %s: %s.", to_number, status_callback, body) if not getattr(settings, "TWILIO_DRY_MODE", False): sent = client.sms.messages.create( to=to_number, from_=from_number, body=body, status_callback=status_callback ) logger.debug("SMS message sent: %s", sent.__dict__) message.sms_sid = sent.sid message.account_sid = sent.account_sid message.status = sent.status message.to_parsed = sent.to if sent.price: message.price = Decimal(force_text(sent.price)) message.price_unit = sent.price_unit message.sent_at = sent.date_created message.save(update_fields=[ "sms_sid", "account_sid", "status", "to_parsed", "price", "price_unit", "sent_at" ]) else: logger.info("SMS: from %s to %s: %s", from_number, to_number, body) return message
\ b Examples: $ moo README. md # live preview README. md $ moo - e *. md # export all markdown files $ moo -- no - css - e README. md # export README. md without CSS $ cat README. md | moo - e - | less # export STDIN to STDOUT
def main(port, export, css, files): """ \b Examples: $ moo README.md # live preview README.md $ moo -e *.md # export all markdown files $ moo --no-css -e README.md # export README.md without CSS $ cat README.md | moo -e - | less # export STDIN to STDOUT """ options = { 'css': css, 'port': port } try: if not export: if len(files) != 1: error("please specify just one file to preview") preview(files[0], options) else: export_files(files, options) except KeyboardInterrupt: sys.exit(0) except Exception as exc: die()
Called when socket is read - ready
def process_input(self): """Called when socket is read-ready""" try: pyngus.read_socket_input(self.connection, self.socket) except Exception as e: LOG.error("Exception on socket read: %s", str(e)) self.connection.close_input() self.connection.close() self.connection.process(time.time())
Called when socket is write - ready
def send_output(self): """Called when socket is write-ready""" try: pyngus.write_socket_output(self.connection, self.socket) except Exception as e: LOG.error("Exception on socket write: %s", str(e)) self.connection.close_output() self.connection.close() self.connection.process(time.time())
Do connection - based processing ( I/ O and timers )
def process(self): """ Do connection-based processing (I/O and timers) """ readfd = [] writefd = [] if self.connection.needs_input > 0: readfd = [self.socket] if self.connection.has_output > 0: writefd = [self.socket] timeout = None deadline = self.connection.next_tick if deadline: now = time.time() timeout = 0 if deadline <= now else deadline - now LOG.debug("select() start (t=%s)", str(timeout)) readable, writable, ignore = select.select(readfd, writefd, [], timeout) LOG.debug("select() returned") if readable: try: pyngus.read_socket_input(self.connection, self.socket) except Exception as e: LOG.error("Exception on socket read: %s", str(e)) self.connection.close_input() self.connection.close() self.connection.process(time.time()) if writable: try: pyngus.write_socket_output(self.connection, self.socket) except Exception as e: LOG.error("Exception on socket write: %s", str(e)) self.connection.close_output() self.connection.close()
Caller factory
def create_caller(self, method_map, source_addr, target_addr, receiver_properties, sender_properties): """ Caller factory """ if self.caller: self.caller.destroy() self.caller = MyCaller(method_map, self, source_addr, target_addr, receiver_properties, sender_properties) return self.caller
Send a message containing the RPC method call
def _send_request(self): """Send a message containing the RPC method call """ msg = Message() msg.subject = "An RPC call!" msg.address = self._to msg.reply_to = self._reply_to msg.body = self._method msg.correlation_id = 5 # whatever... print("sending RPC call request: %s" % str(self._method)) # @todo send timeout self._sender.send(msg, self, None, time.time() + # 10) self._sender.send(msg, self)
Read from the network layer and processes all data read. Can support both blocking and non - blocking sockets. Returns the number of input bytes processed or EOS if input processing is done. Any exceptions raised by the socket are re - raised.
def read_socket_input(connection, socket_obj): """Read from the network layer and processes all data read. Can support both blocking and non-blocking sockets. Returns the number of input bytes processed, or EOS if input processing is done. Any exceptions raised by the socket are re-raised. """ count = connection.needs_input if count <= 0: return count # 0 or EOS while True: try: sock_data = socket_obj.recv(count) break except socket.timeout as e: LOG.debug("Socket timeout exception %s", str(e)) raise # caller must handle except socket.error as e: err = e.errno if err in [errno.EAGAIN, errno.EWOULDBLOCK, errno.EINTR]: # try again later return 0 # otherwise, unrecoverable, caller must handle LOG.debug("Socket error exception %s", str(e)) raise except Exception as e: # beats me... assume fatal LOG.debug("unknown socket exception %s", str(e)) raise # caller must handle if len(sock_data) > 0: count = connection.process_input(sock_data) else: LOG.debug("Socket closed") count = Connection.EOS connection.close_input() connection.close_output() return count
Write data to the network layer. Can support both blocking and non - blocking sockets. Returns the number of output bytes sent or EOS if output processing is done. Any exceptions raised by the socket are re - raised.
def write_socket_output(connection, socket_obj): """Write data to the network layer. Can support both blocking and non-blocking sockets. Returns the number of output bytes sent, or EOS if output processing is done. Any exceptions raised by the socket are re-raised. """ count = connection.has_output if count <= 0: return count # 0 or EOS data = connection.output_data() if not data: # error - has_output > 0, but no data? return Connection.EOS while True: try: count = socket_obj.send(data) break except socket.timeout as e: LOG.debug("Socket timeout exception %s", str(e)) raise # caller must handle except socket.error as e: err = e.errno if err in [errno.EAGAIN, errno.EWOULDBLOCK, errno.EINTR]: # try again later return 0 # else assume fatal let caller handle it: LOG.debug("Socket error exception %s", str(e)) raise except Exception as e: # beats me... assume fatal LOG.debug("unknown socket exception %s", str(e)) raise if count > 0: connection.output_written(count) elif data: LOG.debug("Socket closed") count = Connection.EOS connection.close_output() connection.close_input() return count
Decorator that prevents callbacks from calling into link methods that are not reentrant
def _not_reentrant(func): """Decorator that prevents callbacks from calling into link methods that are not reentrant """ def wrap(*args, **kws): link = args[0] if link._callback_lock.in_callback: m = "Link %s cannot be invoked from a callback!" % func raise RuntimeError(m) return func(*args, **kws) return wrap
Return a map containing the settle modes as provided by the remote. Skip any default value.
def _get_remote_settle_modes(pn_link): """Return a map containing the settle modes as provided by the remote. Skip any default value. """ modes = {} snd = pn_link.remote_snd_settle_mode if snd == proton.Link.SND_UNSETTLED: modes['snd-settle-mode'] = 'unsettled' elif snd == proton.Link.SND_SETTLED: modes['snd-settle-mode'] = 'settled' if pn_link.remote_rcv_settle_mode == proton.Link.RCV_SECOND: modes['rcv-settle-mode'] = 'second' return modes
Assign addresses properties etc.
def configure(self, target_address, source_address, handler, properties): """Assign addresses, properties, etc.""" self._handler = handler self._properties = properties dynamic_props = None if properties: dynamic_props = properties.get("dynamic-node-properties") mode = _dist_modes.get(properties.get("distribution-mode")) if mode is not None: self._pn_link.source.distribution_mode = mode mode = _snd_settle_modes.get(properties.get("snd-settle-mode")) if mode is not None: self._pn_link.snd_settle_mode = mode mode = _rcv_settle_modes.get(properties.get("rcv-settle-mode")) if mode is not None: self._pn_link.rcv_settle_mode = mode if target_address is None: if not self._pn_link.is_sender: raise Exception("Dynamic target not allowed") self._pn_link.target.dynamic = True if dynamic_props: self._pn_link.target.properties.clear() self._pn_link.target.properties.put_dict(dynamic_props) elif target_address: self._pn_link.target.address = target_address if source_address is None: if not self._pn_link.is_receiver: raise Exception("Dynamic source not allowed") self._pn_link.source.dynamic = True if dynamic_props: self._pn_link.source.properties.clear() self._pn_link.source.properties.put_dict(dynamic_props) elif source_address: self._pn_link.source.address = source_address
Return the authorative source of the link.
def source_address(self): """Return the authorative source of the link.""" # If link is a sender, source is determined by the local # value, else use the remote. if self._pn_link.is_sender: return self._pn_link.source.address else: return self._pn_link.remote_source.address
Return the authorative target of the link.
def target_address(self): """Return the authorative target of the link.""" # If link is a receiver, target is determined by the local # value, else use the remote. if self._pn_link.is_receiver: return self._pn_link.target.address else: return self._pn_link.remote_target.address
Remote has closed the session used by this link.
def _session_closed(self): """Remote has closed the session used by this link.""" # if link not already closed: if self._endpoint_state & proton.Endpoint.REMOTE_ACTIVE: # simulate close received self._process_remote_state() elif self._endpoint_state & proton.Endpoint.REMOTE_UNINIT: # locally created link, will never come up self._failed = True self._link_failed("Parent session closed.")
See Link Reject AMQP1. 0 spec.
def reject(self, pn_condition=None): """See Link Reject, AMQP1.0 spec.""" self._pn_link.source.type = proton.Terminus.UNSPECIFIED super(SenderLink, self).reject(pn_condition)
Check if the delivery can be processed.
def _process_delivery(self, pn_delivery): """Check if the delivery can be processed.""" if pn_delivery.tag in self._send_requests: if pn_delivery.settled or pn_delivery.remote_state: # remote has reached a 'terminal state' outcome = pn_delivery.remote_state state = SenderLink._DISPOSITION_STATE_MAP.get(outcome, self.UNKNOWN) pn_disposition = pn_delivery.remote info = {} if state == SenderLink.REJECTED: if pn_disposition.condition: info["condition"] = pn_disposition.condition elif state == SenderLink.MODIFIED: info["delivery-failed"] = pn_disposition.failed info["undeliverable-here"] = pn_disposition.undeliverable annotations = pn_disposition.annotations if annotations: info["message-annotations"] = annotations send_req = self._send_requests.pop(pn_delivery.tag) send_req.destroy(state, info) pn_delivery.settle() elif pn_delivery.writable: # we can now send on this delivery if self._pending_sends: tag = self._pending_sends.popleft() send_req = self._send_requests[tag] self._write_msg(pn_delivery, send_req) else: # tag no longer valid, expired or canceled send? LOG.debug("Delivery ignored, tag=%s", str(pn_delivery.tag)) pn_delivery.settle()
See Link Reject AMQP1. 0 spec.
def reject(self, pn_condition=None): """See Link Reject, AMQP1.0 spec.""" self._pn_link.target.type = proton.Terminus.UNSPECIFIED super(ReceiverLink, self).reject(pn_condition)
Check if the delivery can be processed.
def _process_delivery(self, pn_delivery): """Check if the delivery can be processed.""" if pn_delivery.readable and not pn_delivery.partial: data = self._pn_link.recv(pn_delivery.pending) msg = proton.Message() msg.decode(data) self._pn_link.advance() if self._handler: handle = "rmsg-%s:%x" % (self._name, self._next_handle) self._next_handle += 1 self._unsettled_deliveries[handle] = pn_delivery with self._callback_lock: self._handler.message_received(self, msg, handle) else: # TODO(kgiusti): is it ok to assume Delivery.REJECTED? pn_delivery.settle()
Create a new sender link.
def new_sender(self, name): """Create a new sender link.""" pn_link = self._pn_session.sender(name) return self.request_sender(pn_link)
Create link from request for a sender.
def request_sender(self, pn_link): """Create link from request for a sender.""" sl = SenderLink(self._connection, pn_link) self._links.add(sl) return sl
Create a new receiver link.
def new_receiver(self, name): """Create a new receiver link.""" pn_link = self._pn_session.receiver(name) return self.request_receiver(pn_link)
Create link from request for a receiver.
def request_receiver(self, pn_link): """Create link from request for a receiver.""" rl = ReceiverLink(self._connection, pn_link) self._links.add(rl) return rl
Link has been destroyed.
def link_destroyed(self, link): """Link has been destroyed.""" self._links.discard(link) if not self._links: # no more links LOG.debug("destroying unneeded session") self._pn_session.close() self._pn_session.free() self._pn_session = None self._connection = None
Peer has closed its end of the session.
def _ep_need_close(self): """Peer has closed its end of the session.""" LOG.debug("Session %s close requested - closing...", self._name) links = self._links.copy() # may modify _links for link in links: link._session_closed()
Called when the Proton Engine generates an endpoint state change event.
def _process_endpoint_event(self, event): """Called when the Proton Engine generates an endpoint state change event. """ state_fsm = Endpoint._FSM[self._state] entry = state_fsm.get(event) if not entry: # protocol error: invalid event for current state old_state = self._state self._state = Endpoint.STATE_ERROR self._ep_error("invalid event=%s in state=%s" % (Endpoint.EVENT_NAMES[event], Endpoint.STATE_NAMES[old_state])) return self._state = entry[0] if entry[1]: entry[1](self)
Modifies inline patterns.
def extendMarkdown(self, md, md_globals): """Modifies inline patterns.""" mark_tag = SimpleTagPattern(MARK_RE, 'mark') md.inlinePatterns.add('mark', mark_tag, '_begin')
Peer has closed its end of the link.
def receiver_remote_closed(self, receiver_link, pn_condition): """Peer has closed its end of the link.""" LOG.debug("receiver_remote_closed condition=%s", pn_condition) receiver_link.close() self.done = True
Protocol error occurred.
def receiver_failed(self, receiver_link, error): """Protocol error occurred.""" LOG.warn("receiver_failed error=%s", error) receiver_link.close() self.done = True
Parse the hostname and port out of the server_address.
def get_host_port(server_address): """Parse the hostname and port out of the server_address.""" regex = re.compile(r"^amqp://([a-zA-Z0-9.]+)(:([\d]+))?$") x = regex.match(server_address) if not x: raise Exception("Bad address syntax: %s" % server_address) matches = x.groups() host = matches[0] port = int(matches[2]) if matches[2] else None return host, port
Create a TCP connection to the server.
def connect_socket(host, port, blocking=True): """Create a TCP connection to the server.""" addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM) if not addr: raise Exception("Could not translate address '%s:%s'" % (host, str(port))) my_socket = socket.socket(addr[0][0], addr[0][1], addr[0][2]) if not blocking: my_socket.setblocking(0) try: my_socket.connect(addr[0][4]) except socket.error as e: if e.errno != errno.EINPROGRESS: raise return my_socket
Create a TCP listening socket for a server.
def server_socket(host, port, backlog=10): """Create a TCP listening socket for a server.""" addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM) if not addr: raise Exception("Could not translate address '%s:%s'" % (host, str(port))) my_socket = socket.socket(addr[0][0], addr[0][1], addr[0][2]) my_socket.setblocking(0) # 0=non-blocking try: my_socket.bind(addr[0][4]) my_socket.listen(backlog) except socket.error as e: if e.errno != errno.EINPROGRESS: raise return my_socket
Handle I/ O and Timers on a single Connection.
def process_connection(connection, my_socket): """Handle I/O and Timers on a single Connection.""" if connection.closed: return False work = False readfd = [] writefd = [] if connection.needs_input > 0: readfd = [my_socket] work = True if connection.has_output > 0: writefd = [my_socket] work = True timeout = None deadline = connection.next_tick if deadline: work = True now = time.time() timeout = 0 if deadline <= now else deadline - now if not work: return False readable, writable, ignore = select.select(readfd, writefd, [], timeout) if readable: try: pyngus.read_socket_input(connection, my_socket) except Exception as e: # treat any socket error as LOG.error("Socket error on read: %s", str(e)) connection.close_input() # make an attempt to cleanly close connection.close() connection.process(time.time()) if writable: try: pyngus.write_socket_output(connection, my_socket) except Exception as e: LOG.error("Socket error on write %s", str(e)) connection.close_output() # this may not help, but it won't hurt: connection.close() return True
A utility to help determine which connections need processing. Returns a triple of lists containing those connections that 0 ) need to read from the network 1 ) need to write to the network 2 ) waiting for pending timers to expire. The timer list is sorted with the connection next expiring at index 0.
def need_processing(self): """A utility to help determine which connections need processing. Returns a triple of lists containing those connections that 0) need to read from the network, 1) need to write to the network, 2) waiting for pending timers to expire. The timer list is sorted with the connection next expiring at index 0. """ readers = [] writers = [] timer_heap = [] for c in iter(self._connections.values()): if c.needs_input > 0: readers.append(c) if c.has_output > 0: writers.append(c) if c.deadline: heapq.heappush(timer_heap, (c.next_tick, c)) timers = [] while timer_heap: x = heapq.heappop(timer_heap) timers.append(x[1]) return (readers, writers, timers)
Decorator that prevents callbacks from calling into methods that are not reentrant
def _not_reentrant(func): """Decorator that prevents callbacks from calling into methods that are not reentrant """ def wrap(self, *args, **kws): if self._callback_lock and self._callback_lock.in_callback: m = "Connection %s cannot be invoked from a callback!" % func raise RuntimeError(m) return func(self, *args, **kws) return wrap
Perform connection state processing.
def process(self, now): """Perform connection state processing.""" if self._pn_connection is None: LOG.error("Connection.process() called on destroyed connection!") return 0 # do nothing until the connection has been opened if self._pn_connection.state & proton.Endpoint.LOCAL_UNINIT: return 0 if self._pn_sasl and not self._sasl_done: # wait until SASL has authenticated if (_PROTON_VERSION < (0, 10)): if self._pn_sasl.state not in (proton.SASL.STATE_PASS, proton.SASL.STATE_FAIL): LOG.debug("SASL in progress. State=%s", str(self._pn_sasl.state)) if self._handler: with self._callback_lock: self._handler.sasl_step(self, self._pn_sasl) return self._next_deadline self._sasl_done = True if self._handler: with self._callback_lock: self._handler.sasl_done(self, self._pn_sasl, self._pn_sasl.outcome) else: if self._pn_sasl.outcome is not None: self._sasl_done = True if self._handler: with self._callback_lock: self._handler.sasl_done(self, self._pn_sasl, self._pn_sasl.outcome) # process timer events: timer_deadline = self._expire_timers(now) transport_deadline = self._pn_transport.tick(now) if timer_deadline and transport_deadline: self._next_deadline = min(timer_deadline, transport_deadline) else: self._next_deadline = timer_deadline or transport_deadline # process events from proton: pn_event = self._pn_collector.peek() while pn_event: # LOG.debug("pn_event: %s received", pn_event.type) if _Link._handle_proton_event(pn_event, self): pass elif self._handle_proton_event(pn_event): pass elif _SessionProxy._handle_proton_event(pn_event, self): pass self._pn_collector.pop() pn_event = self._pn_collector.peek() # check for connection failure after processing all pending # engine events: if self._error: if self._handler: # nag application until connection is destroyed self._next_deadline = now with self._callback_lock: self._handler.connection_failed(self, self._error) elif (self._endpoint_state == self._CLOSED and self._read_done and self._write_done): # invoke closed callback after endpoint has fully closed and # all pending I/O has completed: if self._handler: with self._callback_lock: self._handler.connection_closed(self) return self._next_deadline
Get a buffer of data that needs to be written to the network.
def output_data(self): """Get a buffer of data that needs to be written to the network. """ c = self.has_output if c <= 0: return None try: buf = self._pn_transport.peek(c) except Exception as e: self._connection_failed(str(e)) return None return buf
Factory method for Sender links.
def create_sender(self, source_address, target_address=None, event_handler=None, name=None, properties=None): """Factory method for Sender links.""" ident = name or str(source_address) if ident in self._sender_links: raise KeyError("Sender %s already exists!" % ident) session = _SessionProxy("session-%s" % ident, self) session.open() sl = session.new_sender(ident) sl.configure(target_address, source_address, event_handler, properties) self._sender_links[ident] = sl return sl
Rejects the SenderLink and destroys the handle.
def reject_sender(self, link_handle, pn_condition=None): """Rejects the SenderLink, and destroys the handle.""" link = self._sender_links.get(link_handle) if not link: raise Exception("Invalid link_handle: %s" % link_handle) link.reject(pn_condition) # note: normally, link.destroy() cannot be called from a callback, # but this link was never made available to the application so this # link is only referenced by the connection link.destroy()
Factory method for creating Receive links.
def create_receiver(self, target_address, source_address=None, event_handler=None, name=None, properties=None): """Factory method for creating Receive links.""" ident = name or str(target_address) if ident in self._receiver_links: raise KeyError("Receiver %s already exists!" % ident) session = _SessionProxy("session-%s" % ident, self) session.open() rl = session.new_receiver(ident) rl.configure(target_address, source_address, event_handler, properties) self._receiver_links[ident] = rl return rl
Clean up after connection failure detected.
def _connection_failed(self, error="Error not specified!"): """Clean up after connection failure detected.""" if not self._error: LOG.error("Connection failed: %s", str(error)) self._error = error
Both ends of the Endpoint have become active.
def _ep_active(self): """Both ends of the Endpoint have become active.""" LOG.debug("Connection is up") if self._handler: with self._callback_lock: self._handler.connection_active(self)
The remote has closed its end of the endpoint.
def _ep_need_close(self): """The remote has closed its end of the endpoint.""" LOG.debug("Connection remotely closed") if self._handler: cond = self._pn_connection.remote_condition with self._callback_lock: self._handler.connection_remote_closed(self, cond)
The endpoint state machine failed due to protocol error.
def _ep_error(self, error): """The endpoint state machine failed due to protocol error.""" super(Connection, self)._ep_error(error) self._connection_failed("Protocol error occurred.")
This decorator provides several helpful shortcuts for writing Twilio views.
def twilio_view(f): """This decorator provides several helpful shortcuts for writing Twilio views. - It ensures that only requests from Twilio are passed through. This helps protect you from forged requests. - It ensures your view is exempt from CSRF checks via Django's @csrf_exempt decorator. This is necessary for any view that accepts POST requests from outside the local domain (eg: Twilio's servers). - It allows your view to (optionally) return TwiML to pass back to Twilio's servers instead of building a ``HttpResponse`` object manually. - It allows your view to (optionally) return any ``twilio.Verb`` object instead of building a ``HttpResponse`` object manually. Usage:: from twilio.twiml import Response @twilio_view def my_view(request): r = Response() r.sms("Thanks for the SMS message!") return r """ @csrf_exempt @wraps(f) def decorator(request, *args, **kwargs): # Attempt to gather all required information to allow us to check the # incoming HTTP request for forgery. If any of this information is not # available, then we'll throw a HTTP 403 error (forbidden). # Ensure the request method is POST if request.method != "POST": logger.error("Twilio: Expected POST request", extra={"request": request}) return HttpResponseNotAllowed(request.method) if not getattr(settings, "TWILIO_SKIP_SIGNATURE_VALIDATION"): # Validate the request try: validator = RequestValidator(settings.TWILIO_AUTH_TOKEN) url = request.build_absolute_uri() # Ensure the original requested url is tested for validation # Prevents breakage when processed behind a proxy server if "HTTP_X_FORWARDED_SERVER" in request.META: protocol = "https" if request.META["HTTP_X_TWILIO_SSL"] == "Enabled" else "http" url = "{0}://{1}{2}".format( protocol, request.META["HTTP_X_FORWARDED_SERVER"], request.META["REQUEST_URI"] ) signature = request.META["HTTP_X_TWILIO_SIGNATURE"] except (AttributeError, KeyError) as e: logger.exception("Twilio: Missing META param", extra={"request": request}) return HttpResponseForbidden("Missing META param: %s" % e) # Now that we have all the required information to perform forgery # checks, we'll actually do the forgery check. if not validator.validate(url, request.POST, signature): logger.error( "Twilio: Invalid url signature %s - %s - %s", url, request.POST, signature, extra={"request": request} ) return HttpResponseForbidden("Invalid signature") # Run the wrapped view, and capture the data returned. response = f(request, *args, **kwargs) # If the view returns a string (or a ``twilio.Verb`` object), we'll # assume it is XML TwilML data and pass it back with the appropriate # mimetype. We won't check the XML data because that would be too time # consuming for every request. Instead, we'll let the errors pass # through to be dealt with by the developer. if isinstance(response, six.text_type): return HttpResponse(response, mimetype="application/xml") elif isinstance(response, Verb): return HttpResponse(force_text(response), mimetype="application/xml") else: return response return decorator
Equality test
def _is_equal(self, test_color): """Equality test""" if test_color is None: ans = False elif test_color.color_type != self.color_type: ans = False elif self.name is not None and self.name == test_color.name: ans = True elif (self.red == test_color.red and self.blue == test_color.blue and self.green == test_color.green): ans = True else: ans = False return ans
Adobe output string for defining colors
def _get_color_string(self): """Adobe output string for defining colors""" s = '' if self.color_type == 'd': if self.name is "black": s = '%.3f G' % 0 else: s = '%.3f %.3f %.3f RG' % ( self.red / 255.0, self.green / 255.0, self.blue / 255.0) elif self.color_type == 'f' or self.color_type == 't': if self.name is "black": s = '%.3f g' % 0 else: s = '%.3f %.3f %.3f rg' % ( self.red / 255.0, self.green / 255.0, self.blue / 255.0) return s
Select a font ; size given in points
def _set_font(self, family=None, style=None, size=None): """Select a font; size given in points""" if style is not None: if 'B' in style: family += '_bold' if 'I' in style: family += '_italic' self._set_family(family) self._get_diffs() self._set_style(style) self._set_metrics() self._set_size(size) self._set_font_key()
Get width of a string in the current font
def _string_width(self, s): """Get width of a string in the current font""" s = str(s) w = 0 for char in s: char = ord(char) w += self.character_widths[char] return w * self.font_size / 1000.0
Given a search path find file with requested extension
def get_ttf(self): """ Given a search path, find file with requested extension """ font_dict = {} families = [] rootdirlist = string.split(self.search_path, os.pathsep) #for rootdir in rootdirlist: # rootdir = os.path.expanduser(rootdir) for dirName, subdirList, filelist in itertools.chain.from_iterable(os.walk(path) for path in rootdirlist): for item in filelist: root, ext = os.path.splitext(item) if ext == '.ttf': if root[0].lower() in english: source = os.path.join(dirName, item) name = root.lower().replace('_', ' ') if ' bold' in name: name = name.replace(' bold', '_bold') if ' italic' in name: name = name.replace(' italic', '_italic') elif 'bold' in name: name = name.replace('bold', '_bold') if 'italic' in name: name = name.replace('italic', '_italic') elif ' italic' in name: name = name.replace(' italic', '_italic') elif 'italic' in name: name = name.replace('italic', '_italic') elif 'oblique' in name: name = name.replace('oblique', '_italic') else: families.append(name) font_dict[name] = source else: source = os.path.join(dirName, item) name = root.lower().replace('_', ' ') font_dict[name] = source families.append(name) self.font_dict = font_dict self.families = families
May be used to compress PDF files. Code is more readable for testing and inspection if not compressed. Requires a boolean.
def _set_compression(self, value): """ May be used to compress PDF files. Code is more readable for testing and inspection if not compressed. Requires a boolean. """ if isinstance(value, bool): self.compression = value else: raise Exception( TypeError, "%s is not a valid option for compression" % value)
PDF objects #1 through #3 are typically saved for the Zeroth Catalog and Pages Objects. This program will save the numbers but outputs the individual Page and Content objects first. The actual Catalog and Pages objects are calculated after.
def _create_placeholder_objects(self): """ PDF objects #1 through #3 are typically saved for the Zeroth, Catalog, and Pages Objects. This program will save the numbers, but outputs the individual Page and Content objects first. The actual Catalog and Pages objects are calculated after. """ self.objects.append("Zeroth") self.objects.append("Catalog") self.objects.append("Pages")