text
stringlengths
81
112k
Just the last entry. def get_last(self, table=None): """Just the last entry.""" if table is None: table = self.main_table query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table return self.own_cursor.execute(query).fetchone()
Get a specific entry by its number. def get_number(self, num, table=None): """Get a specific entry by its number.""" if table is None: table = self.main_table self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num)) return self.own_cursor.fetchone()
Get a specific entry. def get_entry(self, key, column=None, table=None): """Get a specific entry.""" if table is None: table = self.main_table if column is None: column = "id" if isinstance(key, basestring): key = key.replace("'","''") query = 'SELECT * from "%s" where "%s"=="...
Create a table and populate it with data from a dataframe. def insert_df(self, table_name, df): """Create a table and populate it with data from a dataframe.""" df.to_sql(table_name, con=self.own_connection)
Get specific entries and order them in the same way. def get_and_order(self, ids, column=None, table=None): """Get specific entries and order them in the same way.""" command = """ SELECT rowid, * from "data" WHERE rowid in (%s) ORDER BY CASE rowid %s END; ...
Copy a table from another SQLite database to this one. def import_table(self, source, table_name): """Copy a table from another SQLite database to this one.""" query = "SELECT * FROM `%s`" % table_name.lower() df = pandas.read_sql(query, source.connection) df.to_sql(table_name, con=self...
Returns a representation of the error in a jsonic form that is compatible with flask's error handling. Keyword arguments allow custom error handlers to override parts of the exception when it is jsonified def jsonify(self, status_code=None, message=None, headers=None): """ Retu...
Provides a generic error function that packages a flask_buzz exception so that it can be handled nicely by the flask error handler:: app.register_error_handler( FlaskBuzz, FlaskBuzz.build_error_handler(), ) Additionally, extra tasks may be applied to the error p...
Provides a generic error function that packages a flask_buzz exception so that it can be handled by the flask-restplus error handler:: @api.errorhandler(SFBDError) def do_it(error): return SFBDError.build_error_handler_for_flask_restplus()() or:: ap...
Registers an error handler for FlaskBuzz derived errors that are currently imported. This is useful since flask-restplus (prior to 0.11.0) does not handle derived errors. This is probably the easist way to register error handlers for FlaskBuzz errors with flask-restplus:: Fl...
Returns a dict containing the humanized data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned dict. ``exclude`` is an optional list of field names. If provid...
Find the needed city server information. def find_info(name=None): """Find the needed city server information.""" if not name: return list(servers.keys()) name = name.lower() if name in servers: info = servers[name] else: raise CityNotFound("Could not find the specified cit...
Return path of bin. Python clone of /usr/bin/which. from salt.util - https://www.github.com/saltstack/salt - license apache :param exe: Application to search PATHs for. :type exe: str :param default_path: Application to search PATHs for. :type default_path: list :rtype: str def which( exe...
Run 'cmd' in a shell and return the combined contents of stdout and stderr (Blocking). Throws an exception if the command exits non-zero. :param cmd: list of str (or single str, if shell==True) indicating the command to run :param shell: boolean indicating whether we are using advanced shell ...
Add additional context information for loggers. def process(self, msg, kwargs): """Add additional context information for loggers.""" prefixed_dict = {} prefixed_dict['repo_vcs'] = self.bin_name prefixed_dict['repo_name'] = self.name kwargs["extra"] = prefixed_dict ret...
Notes: Sequence works a bit different than other nodes. This method (like others) expectes a list. However, sequence matches against the list, whereas other nodes try to match against elements of the list. def pop(self, sexp): ''' Notes: Sequence works a bit different than other...
All branches in a list def branches(self): """All branches in a list""" result = self.git(self.default + ['branch', '-a', '--no-color']) return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')]
Clone again, somewhere else def re_clone(self, repo_dir): """Clone again, somewhere else""" self.git('clone', self.remote_url, repo_dir) return GitRepo(repo_dir)
Iterate over all parent nodes and one-self. def path(self): """Iterate over all parent nodes and one-self.""" yield self if not self.parent: return for node in self.parent.path: yield node
Iterate over all nodes of the tree excluding one self and one's children. def others(self): """Iterate over all nodes of the tree excluding one self and one's children.""" if not self.parent: return yield self.parent for sibling in self.parent.children.values(): if sibling.n...
Iterate over all children (until a certain level) and one-self. def get_children(self, depth=1): """Iterate over all children (until a certain level) and one-self.""" yield self if depth == 0: return for child in self.children.values(): for node in child.get_children(depth-1...
Get all nodes that are exactly this far away. def get_level(self, level=2): """Get all nodes that are exactly this far away.""" if level == 1: for child in self.children.values(): yield child else: for child in self.children.values(): for node in child.ge...
Cut all branches over a certain length making new leaves at *length*. def trim(self, length): """Cut all branches over a certain length making new leaves at *length*.""" if length > 0: for child in self.children.values(): child.trim(length-1) else: if hasattr(self, 'coun...
Cut all branches from this node to its children and adopt all nodes at certain level. def mend(self, length): """Cut all branches from this node to its children and adopt all nodes at certain level.""" if length == 0: raise Exception("Can't mend the root !") if length == 1: retu...
Get data from distroinfo instance. :param apply_tag: apply supplied tag to info :param info_dicts: return packages and releases as dicts :return: parsed info metadata def get_info(self, apply_tag=None, info_dicts=False): """ Get data from distroinfo instance. :param ap...
Run a Tornado create_application. :param create_application: function to call to create a new application instance :param dict|None settings: optional configuration dictionary that will be passed through to ``create_application`` as kwargs. :param dict|None log_config: optional logg...
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes doesn't work with a ssh:// scheme (e.g. Github). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. The manpage fo...
Retrieve the repository, clone if doesn't exist. def obtain(self): """Retrieve the repository, clone if doesn't exist.""" self.check_destination() url = self.url cmd = ['clone', '--progress'] if self.git_shallow: cmd.extend(['--depth', '1']) if self.tls_ver...
Return remotes like git remote -v. :rtype: dict of tuples def remotes_get(self): """Return remotes like git remote -v. :rtype: dict of tuples """ remotes = {} cmd = self.run(['remote']) ret = filter(None, cmd.split('\n')) for remote_name in ret: ...
Get the fetch and push URL for a specified remote name. :param remote: the remote name used to define the fetch and push URL :type remote: str :returns: remote name and url in tuple form :rtype: tuple def remote_get(self, remote='origin'): """Get the fetch and push URL for a sp...
Set remote with name and URL like git remote add. :param url: defines the remote URL :type url: str :param name: defines the remote name. :type name: str def remote_set(self, url, name='origin'): """Set remote with name and URL like git remote add. :param url: defines ...
Return clean VCS url from RFC-style url :param url: url :type url: str :rtype: str :returns: url as VCS software would accept it :seealso: #14 def chomp_protocol(url): """Return clean VCS url from RFC-style url :param url: url :type url: str :rt...
Logs the message to the sys.stdout or sys.stderr stream. When color is defined and the TERM environemnt variable contains the string "color", then the output will be colored. def _log(self, message, stream, color=None, newline=False): ''' Logs the message to the sys.stdout or sys.stder...
Logs an informational message to stdout. This method should only be used by the Runner. def info(self, message): ''' Logs an informational message to stdout. This method should only be used by the Runner. ''' return self._log( message=message.upper(), ...
Logs as whole test result as PASSED. This method should only be used by the Runner. def passed(self, message): ''' Logs as whole test result as PASSED. This method should only be used by the Runner. ''' return self._log( message=message.upper(), ...
Logs as whole test result as FAILED. This method should only be used by the Runner. def failed(self, message): ''' Logs as whole test result as FAILED. This method should only be used by the Runner. ''' return self._log( message=message.upper(), ...
Decorator to run a function in a different thread. It can be used to execute a command in a non-blocking way like this:: @non_blocking def add_one(n): print 'starting' import time time.sleep(2) print 'ending' return n+1 thread...
Used to return a base media URL. Depending on whether we're serving media remotely or locally, this either hands the decision off to the backend, or just uses the value in settings.STATIC_URL. args: with_ssl: (bool) If True, return an HTTPS url (depending on how ...
Find the log directory and return all the logs sorted. def logs(self): """Find the log directory and return all the logs sorted.""" if not self.parent.loaded: self.parent.load() logs = self.parent.p.logs_dir.flat_directories logs.sort(key=lambda x: x.mod_time) return logs
A convenience method to run the same result as a SLURM job but locally in a non-blocking way. def run_locally(self, steps=None, **kwargs): """A convenience method to run the same result as a SLURM job but locally in a non-blocking way.""" self.slurm_job = LoggedJobSLURM(self.command(ste...
Run the steps via the SLURM queue. def run_slurm(self, steps=None, **kwargs): """Run the steps via the SLURM queue.""" # Optional extra SLURM parameters # params = self.extra_slurm_params params.update(kwargs) # Mandatory extra SLURM parameters # if 'time' not in p...
Returns a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet, ...
Set the name of the machine. def rename(self, name): """Set the name of the machine.""" self.ec2.create_tags(Resources = [self.instance_id], Tags = [{'Key': 'Name', 'Value': name}]) self.refresh_info()
Put the DNS into the ssh config file. def update_ssh_config(self, path="~/.ssh/config"): """Put the DNS into the ssh config file.""" # Read the config file # import sshconf config = sshconf.read_ssh_config(os.path.expanduser(path)) # In case it doesn't exist # if not con...
Updates widget choices with special choice iterator that removes blank values and adds none value to clear filter data. :param widget: widget with choices :return: updated widget with filter choices def _update_widget_choices(self, widget): """ Updates widget choices with specia...
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering. def get_widget(self, request): """ Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering. """ retu...
Table view is not able to get form field from reverse relation. Therefore this widget returns similar form field as direct relation (ModelChoiceField). Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to count objects in the queryset. def...
strip proto:// | openstack/ prefixes and .git | -distgit suffixes def strip_project_url(url): """strip proto:// | openstack/ prefixes and .git | -distgit suffixes""" m = re.match(r'(?:[^:]+://)?(.*)', url) if m: url = m.group(1) if url.endswith('.git'): url, _, _ = url.rpartition('.') ...
Return revision options. from pip pip.vcs.subversion. def get_rev_options(url, rev): """Return revision options. from pip pip.vcs.subversion. """ if rev: rev_options = ['-r', rev] else: rev_options = [] r = urlparse.urlsplit(url) if hasattr(r, 'username'): # ...
Return revision for a file. def get_revision_file(self, location): """Return revision for a file.""" current_rev = self.run(['info', location]) _INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M) info_list = _INI_RE.findall(current_rev) return int(dict(info_list)['Revision'])
publish_path joins the publish_paths for the chat type and the channel. def get_publish_path(self, obj): """ publish_path joins the publish_paths for the chat type and the channel. """ return os.path.join( obj.chat_type.publish_path, obj.publish_path.lstrip("/") )
Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>. For example: name_es (name attribute in Spanish) @param attr Attribute whose name will form the name translated attribute. @param lang ISO Language code that will be the suffix of the translated attribute. @return: string with t...
Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done. def _init_module_cache(): """ Module caching, it helps with not having to import again and again same modules. @return: boolean, Tr...
Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting orphan translations (translations without a parent object associated). def _load_source_model(self): """ Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only wh...
Loads related object in a dynamic attribute and returns it. def _load_source_object(self): """ Loads related object in a dynamic attribute and returns it. """ if hasattr(self, "source_obj"): self.source_text = getattr(self.source_obj, self.field) return self.source_obj self._load_source_model() self...
Delete orphan translations. This method needs refactoring to be improve its performance. def delete_orphan_translations(condition=None): """ Delete orphan translations. This method needs refactoring to be improve its performance. """ if condition is None: condition = {} # TODO: optimize using one SQL ...
Updates FieldTranslations table def update_translations(condition=None): """ Updates FieldTranslations table """ if condition is None: condition = {} # Number of updated translations num_translations = 0 # Module caching FieldTranslation._init_module_cache() # Current languages dict LANGUAG...
Static method that constructs a translation based on its contents. def factory(obj, field, source_text, lang, context=""): """ Static method that constructs a translation based on its contents. """ # Model name obj_classname = obj.__class__.__name__ # Module name obj_module = obj.__module__ # Comp...
Save object in database, updating the datetimes accordingly. def save(self, *args, **kwargs): """ Save object in database, updating the datetimes accordingly. """ # Now in UTC now_datetime = timezone.now() # If we are in a creation, assigns creation_datetime if not self.id: self.creation_datetime ...
Parse raw rdoinfo metadata inplace. :param raw_info: raw info to parse :param apply_tag: tag to apply :returns: dictionary containing all packages in rdoinfo def parse_info(raw_info, apply_tag=None): """ Parse raw rdoinfo metadata inplace. :param raw_info: raw info to parse :param apply_t...
Return info with: 1) `packages` list replaced by a 'packages' dict indexed by 'project' 2) `releases` list replaced by a 'releases' dict indexed by 'name' def info2dicts(info, in_place=False): """ Return info with: 1) `packages` list replaced by a 'packages' dict indexed by 'project' 2) `rele...
Return info with: 1) `packages` dict replaced by a 'packages' list with indexes removed 2) `releases` dict replaced by a 'releases' list with indexes removed info2list(info2dicts(info)) == info def info2lists(info, in_place=False): """ Return info with: 1) `packages` dict replaced by a 'pac...
Make an ultra-safe, ASCII version a string. For instance for use as a filename. \w matches any alphanumeric character and the underscore. def alphanumeric(text): """Make an ultra-safe, ASCII version a string. For instance for use as a filename. \w matches any alphanumeric character and the undersco...
Make a safe representation of a string. Note: the `\s` special character matches any whitespace character. This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace). def sanitize_text(text): """Make a safe representation of a string. Note: the `\s` special character matches any whitespace ...
Will convert CamelCaseStrings to snake_case_strings. >>> camel_to_snake('CamelCase') 'camel_case' >>> camel_to_snake('CamelCamelCase') 'camel_camel_case' >>> camel_to_snake('Camel2Camel2Case') 'camel2_camel2_case' >>> camel_to_snake('getHTTPResponseCode') 'get_http_response_code' >>>...
Different possibilities for True: ☑️✔︎✓✅👍✔️ Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴 def bool_to_unicode(b): """Different possibilities for True: ☑️✔︎✓✅👍✔️ Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴""" b = bool(b) if b is True: return u"✅" if b is False: return u"...
Access a dictionary like if it was an object with properties. If no "new_value", then it's a getter, otherwise it's a setter. >>> {'characters': {'cast': 'Jean-Luc Picard', 'featuring': 'Deanna Troi'}} >>> access_dict_like_obj(startrek, 'characters.cast', 'Pierce Brosnan') def access_dict_like_obj(obj, pro...
Generate all combinations of a given list of items. def all_combinations(items): """Generate all combinations of a given list of items.""" return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)))
Given a multiline string, add whitespaces to every line so that every line has the same length. def pad_equal_whitespace(string, pad=None): """Given a multiline string, add whitespaces to every line so that every line has the same length.""" if pad is None: pad = max(map(len, string.split('\n'))) + 1 ...
Zip two strings together, line wise def concatenate_by_line(first, second): """Zip two strings together, line wise""" return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n')))
Group a list of strings by pairs, by matching those with only one character difference between each other together. def sort_string_by_pairs(strings): """Group a list of strings by pairs, by matching those with only one character difference between each other together.""" assert len(strings) % 2 == 0 ...
Return the number of characters in two strings that don't exactly match def count_string_diff(a,b): """Return the number of characters in two strings that don't exactly match""" shortest = min(len(a), len(b)) return sum(a[i] != b[i] for i in range(shortest))
Iterative flatten. def iflatten(L): """Iterative flatten.""" for sublist in L: if hasattr(sublist, '__iter__'): for item in iflatten(sublist): yield item else: yield sublist
Same order unique list using only a list compression. def uniquify_list(L): """Same order unique list using only a list compression.""" return [e for i, e in enumerate(L) if L.index(e) == i]
Iterative mean. def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
Gets the next item of an iterable. If the iterable is exhausted, returns None. def get_next_item(iterable): """Gets the next item of an iterable. If the iterable is exhausted, returns None.""" try: x = iterable.next() except StopIteration: x = None except AttributeError: x = None return x
Returns some thing like '2019-02-15 15:58:22 CET+0100 def pretty_now(): """Returns some thing like '2019-02-15 15:58:22 CET+0100'""" import datetime, tzlocal time_zone = tzlocal.get_localzone() now = datetime.datetime.now(time_zone) return now.strftime("%Y-%m-%d %H:%M:%S %Z%z")
Given a list of strings will join them with commas and a final "and" word. >>> andify(['Apples', 'Oranges', 'Mangos']) 'Apples, Oranges and Mangos' def andify(list_of_strings): """ Given a list of strings will join them with commas and a final "and" word. >>> andify(['Apples', 'Oranges', ...
1 becomes 1st, 2 becomes 2nd, etc. def num_to_ith(num): """1 becomes 1st, 2 becomes 2nd, etc.""" value = str(num) before_last_digit = value[-2] last_digit = value[-1] if len(value) > 1 and before_last_digit == '1': return value +'th' if last_digit == '1': return value + 'st' ...
Down-sample an enumerable list of things def isubsample(full_sample, k, full_sample_len=None): """Down-sample an enumerable list of things""" # Determine length # if not full_sample_len: full_sample_len = len(full_sample) # Check size coherence # if not 0 <= k <= full_sample_len: raise Valu...
This is essentially a convolving operation. Several option exist for dealing with the border cases. * None: Here the returned signal will be smaller than the inputted interval. * zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original inte...
Wait until the predicate turns true and display a turning ball. def wait(predicate, interval=1, message=lambda: "Waiting..."): """Wait until the predicate turns true and display a turning ball.""" ball, next_ball = u"|/-\\", "|" sys.stdout.write(" \033[K") sys.stdout.flush() while not predicate(...
Sort strings that contain numbers correctly. Works in Python 2 and 3. >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1'] >>> l.sort(key=natural_sort) >>> l.__repr__() "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" def natural_sort(item): """ Sort strings t...
Splits a number on thousands. >>> split_thousands(1000012) "1'000'012" def split_thousands(s): """ Splits a number on thousands. >>> split_thousands(1000012) "1'000'012" """ # Check input # if s is None: return "0" # If it's a string # if isinstance(s, basestring): s = flo...
Reverse a SeqIO sequence, but keep its name intact. def reverse_compl_with_name(old_seq): """Reverse a SeqIO sequence, but keep its name intact.""" new_seq = old_seq.reverse_complement() new_seq.id = old_seq.id new_seq.description = old_seq.description return new_seq
Load a file with the json module, but report errors better if it fails. And have it ordered too ! def load_json_path(path): """Load a file with the json module, but report errors better if it fails. And have it ordered too !""" with open(path) as handle: try: return json.load(handle, object_pai...
Compute the md5 of a file. Pretty fast. def md5sum(file_path, blocksize=65536): """Compute the md5 of a file. Pretty fast.""" md5 = hashlib.md5() with open(file_path, "rb") as f: for block in iter(lambda: f.read(blocksize), ""): md5.update(block) return md5.hexdigest()
Download a file from an URL and place it somewhere. Like wget. Uses requests and tqdm to display progress if you want. By default it will uncompress files. #TODO: handle case where destination is a directory def download_from_url(source, destination, progress=False, uncompress=False): """Download a fil...
Generate the lines of file in reverse order. def reversed_lines(path): """Generate the lines of file in reverse order.""" with open(path, 'r') as handle: part = '' for block in reversed_blocks(handle): for c in reversed(block): if c == '\n' and part: ...
Generate blocks of file's contents in reverse order. def reversed_blocks(handle, blocksize=4096): """Generate blocks of file's contents in reverse order.""" handle.seek(0, os.SEEK_END) here = handle.tell() while 0 < here: delta = min(blocksize, here) here -= delta handle.seek(he...
TODO: * Add a random string to the backup file. * Restore permissions after copy. def prepend_to_file(path, data, bufsize=1<<15): """TODO: * Add a random string to the backup file. * Restore permissions after copy. """ # Backup the file # backupname = path + os.extsep + 'bak' # Remo...
ERROR: type should be string, got "https://github.com/jc0n/python-which\n\ndef which(cmd, safe=False):\n \"\"\"https://github.com/jc0n/python-which\"\"\"\n from autopaths.file_path import FilePath\n def is_executable(path):\n return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)\n path, name = os.path.split(cmd)\n if path:\n if is_executable(cmd): return FilePath(cmd)\n else:\n for path in os.environ['PATH'].split(os.pathsep):\n candidate = os.path.join(path, cmd)\n if is_executable(candidate): return FilePath(candidate)\n if not safe: raise Exception('which failed to locate a proper command path \"%s\"' % cmd)"
Renders a tag to include the stylesheet. It takes an optional second parameter for the media attribute; the default media is "screen, projector". Usage:: {% css "<somefile>.css" ["<projection type(s)>"] %} Examples:: {% css "myfile.css" %} {% css "myfile.css" "screen, projec...
Shortcut to render CSS as a print stylesheet. Usage:: {% css_print "myfile.css" %} Which is equivalent to {% css "myfile.css" "print" %} def css_print_tag(parser, token): """ Shortcut to render CSS as a print stylesheet. Usage:: {% css_print...
Looks at the RequestContext object and determines if the client supports gzip encoded content. If the client does, we will send them to the gzipped version of files that are allowed to be compressed. Clients without gzip support will be served the original media. def supports_gzip(self, context...
Checks to see whether to use the normal or the secure media source, depending on whether the current page view is being sent over SSL. The USE_SSL setting can be used to force HTTPS (True) or HTTP (False). NOTE: Not all backends implement SSL media. In this case, they'll just re...
Assembles various components to form a complete resource URL. args: url: (str) A base media URL. path: (str) The path on the host (specified in 'url') leading up to the file. filename: (str) The file name to serve. gzip: (bool) True if clien...
Renders a <link> tag for the stylesheet(s). def linktag(self, url, path, filename, media, context): """ Renders a <link> tag for the stylesheet(s). """ if msettings['DOCTYPE'] == 'xhtml': markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s" />""" e...
Renders a <script> tag for the JS file(s). def scripttag(self, url, path, filename, context): """ Renders a <script> tag for the JS file(s). """ if msettings['DOCTYPE'] == 'html5': markup = """<script src="%s"></script>""" else: markup = """<script type="...
Wrap a tornado application in a callback-aware wrapper. :param tornado.web.Application application: application to wrap. :param list|NoneType before_run: optional list of callbacks to invoke before the IOLoop is started. :param list|NoneType on_start: optional list of callbacks to register ...