INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Basic FastCGI support via flup. This web server has many many options. Please see the Flup project documentation for details.
def serve(application, host='127.0.0.1', port=8080, socket=None, **options): """Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details. """ # Allow either on-disk socket (recommended) or TCP/IP socket use. if not socket: bindAddress = (ho...
Helper method. Returns kwargs needed to filter the correct object.
def _get_method_kwargs(self): """ Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object. """ method_kwargs = { 'user': self.user, 'content_type': self.ctype, 'object_id': self.content...
Adds a subscription for the given user to the given object.
def save(self, *args, **kwargs): """Adds a subscription for the given user to the given object.""" method_kwargs = self._get_method_kwargs() try: subscription = Subscription.objects.get(**method_kwargs) except Subscription.DoesNotExist: subscription = Subscription...
Add the usual suspects to the context. This adds request response and path to the RequestContext instance.
def prepare(self, context): """Add the usual suspects to the context. This adds `request`, `response`, and `path` to the `RequestContext` instance. """ if __debug__: log.debug("Preparing request context.", extra=dict(request=id(context))) # Bridge in WebOb `Request` and `Response` objects. # Ext...
Called as dispatch descends into a tier. The base extension uses this to maintain the current url.
def dispatch(self, context, consumed, handler, is_endpoint): """Called as dispatch descends into a tier. The base extension uses this to maintain the "current url". """ request = context.request if __debug__: log.debug("Handling dispatch event.", extra=dict( request = id(context), consum...
Render empty responses.
def render_none(self, context, result): """Render empty responses.""" context.response.body = b'' del context.response.content_length return True
Return binary responses unmodified.
def render_binary(self, context, result): """Return binary responses unmodified.""" context.response.app_iter = iter((result, )) # This wraps the binary string in a WSGI body iterable. return True
Perform appropriate metadata wrangling for returned open file handles.
def render_file(self, context, result): """Perform appropriate metadata wrangling for returned open file handles.""" if __debug__: log.debug("Processing file-like object.", extra=dict(request=id(context), result=repr(result))) response = context.response response.conditional_response = True modified ...
Attempt to serve generator responses through stream encoding. This allows for direct use of cinje template functions which are generators as returned views.
def render_generator(self, context, result): """Attempt to serve generator responses through stream encoding. This allows for direct use of cinje template functions, which are generators, as returned views. """ context.response.encoding = 'utf8' context.response.app_iter = ( (i.encode('utf8') if isinst...
CherryPy - based WSGI - HTTP server.
def serve(application, host='127.0.0.1', port=8080): """CherryPy-based WSGI-HTTP server.""" # Instantiate the server with our configuration and application. server = CherryPyWSGIServer((host, int(port)), application, server_name=host) # Try to be handy as many terminals allow clicking links. print("serving on ...
Returns the colored string
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None): '''Returns the colored string''' if not isinstance(string, str): string = str(string) if rgb is None and ansi is None: raise TerminalColorMapException( 'colorize: must specify one name...
Render serialized responses.
def render_serialization(self, context, result): """Render serialized responses.""" resp = context.response serial = context.serialize match = context.request.accept.best_match(serial.types, default_match=self.default) result = serial[match](result) if isinstance(result, str): result = result.decod...
Eventlet - based WSGI - HTTP server. For a more fully - featured Eventlet - capable interface see also [ Spawning ] ( http:// pypi. python. org/ pypi/ Spawning/ ).
def serve(application, host='127.0.0.1', port=8080): """Eventlet-based WSGI-HTTP server. For a more fully-featured Eventlet-capable interface, see also [Spawning](http://pypi.python.org/pypi/Spawning/). """ # Instantiate the server with a bound port and with our application. server(listen(host, int(port)), app...
Main
def main(args=None): """Main""" vs = [(v-100)*0.001 for v in range(200)] for f in ['IM.channel.nml','Kd.channel.nml']: nml_doc = pynml.read_neuroml2_file(f) for ct in nml_doc.ComponentType: ys = [] for v in vs: req_variables = {'v':'%sV'%v,...
Parse command - line arguments.
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser( description=("A script which can be run to generate a LEMS " "file to analyse the behaviour of channels in " "NeuroML 2")) parser.ad...
A single IV curve
def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs): """A single IV curve""" grid = plt_kwargs.pop('grid',True) same_fig = plt_kwargs.pop('same_fig',False) if not len(plt_args): plt_args = ('ko-',) if 'label' not in plt_kwargs: plt_kwargs['label'] = 'Current' if not sa...
Multipart AJAX request example. See: http:// test. getify. com/ mpAjax/ description. html
def root(context): """Multipart AJAX request example. See: http://test.getify.com/mpAjax/description.html """ response = context.response parts = [] for i in range(12): for j in range(12): parts.append(executor.submit(mul, i, j)) def stream(parts, timeout=None): try: for future in as_complete...
Get a file and render the content of the template_file_name with kwargs in a file: param file: A File Stream to write: param template_file_name: path to route with template name: param ** kwargs: Args to be rendered in template
def render_template_with_args_in_file(file, template_file_name, **kwargs): """ Get a file and render the content of the template_file_name with kwargs in a file :param file: A File Stream to write :param template_file_name: path to route with template name :param **kwargs: Args to be rendered in tem...
Creates a file or open the file with file_name name: param file_name: String with a filename: param initial_template_file_name: String with path to initial template: param args: from console to determine path to save the files
def create_or_open(file_name, initial_template_file_name, args): """ Creates a file or open the file with file_name name :param file_name: String with a filename :param initial_template_file_name: String with path to initial template :param args: from console to determine path to save the files ...
In general we have a initial template and then insert new data so we dont repeat the schema for each module: param module_name: String with module name: paran ** kwargs: Args to be rendered in template
def generic_insert_module(module_name, args, **kwargs): """ In general we have a initial template and then insert new data, so we dont repeat the schema for each module :param module_name: String with module name :paran **kwargs: Args to be rendered in template """ file = create_or_open( ...
Verify if the work folder is a django app. A valid django app always must have a models. py file: return: None
def sanity_check(args): """ Verify if the work folder is a django app. A valid django app always must have a models.py file :return: None """ if not os.path.isfile( os.path.join( args['django_application_folder'], 'models.py' ) ): print("django...
In general if we need to put a file on a folder we use this method
def generic_insert_with_folder(folder_name, file_name, template_name, args): """ In general if we need to put a file on a folder, we use this method """ # First we make sure views are a package instead a file if not os.path.isdir( os.path.join( args['django_application_folder'], ...
The recommended development HTTP server. Note that this server performs additional buffering and will not honour chunked encoding breaks.
def serve(application, host='127.0.0.1', port=8080, threads=4, **kw): """The recommended development HTTP server. Note that this server performs additional buffering and will not honour chunked encoding breaks. """ # Bind and start the server; this is a blocking process. serve_(application, host=host, port=int...
Plot the result of the simulation once it s been intialized
def show(self): """ Plot the result of the simulation once it's been intialized """ from matplotlib import pyplot as plt if self.already_run: for ref in self.volts.keys(): plt.plot(self.t, self.volts[ref], label=ref) plt...
Multiply two values together and return the result via JSON. Python 3 function annotations are used to ensure that the arguments are integers. This requires the functionality of web. ext. annotation: AnnotationExtension. There are several ways to execute this method: * POST http:// localhost: 8080/ mul * GET http:// lo...
def mul(self, a: int = None, b: int = None) -> 'json': """Multiply two values together and return the result via JSON. Python 3 function annotations are used to ensure that the arguments are integers. This requires the functionality of `web.ext.annotation:AnnotationExtension`. There are several ways to ex...
Returns the colored string to print on the terminal.
def colorize(string, rgb=None, ansi=None, bg=None, ansi_bg=None, fd=1): '''Returns the colored string to print on the terminal. This function detects the terminal type and if it is supported and the output is not going to a pipe or a file, then it will return the colored string, otherwise it will retur...
Inspect and potentially mutate the given handler s arguments. The args list and kw dictionary may be freely modified though invalid arguments to the handler will fail.
def mutate(self, context, handler, args, kw): """Inspect and potentially mutate the given handler's arguments. The args list and kw dictionary may be freely modified, though invalid arguments to the handler will fail. """ def cast(arg, val): if arg not in annotations: return cast = annotations[...
Transform the value returned by the controller endpoint. This extension transforms returned values if the endpoint has a return type annotation.
def transform(self, context, handler, result): """Transform the value returned by the controller endpoint. This extension transforms returned values if the endpoint has a return type annotation. """ handler = handler.__func__ if hasattr(handler, '__func__') else handler annotation = getattr(handler, '__ann...
Parse command - line arguments.
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser( description=("A script which can be run to tune a NeuroML 2 model against a number of target properties. Work in progress!")) parser.add_argument('prefix', ...
Parse command - line arguments.
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A file for overlaying POVRay files generated from NeuroML by NeuroML1ToPOVRay.py with cell activity (e.g. as generated from a neuroConstruct simulation)") parser.add_argument('prefix', ...
Tornado s HTTPServer. This is a high quality asynchronous server with many options. For details please visit: http:// www. tornadoweb. org/ en/ stable/ httpserver. html#http - server
def serve(application, host='127.0.0.1', port=8080, **options): """Tornado's HTTPServer. This is a high quality asynchronous server with many options. For details, please visit: http://www.tornadoweb.org/en/stable/httpserver.html#http-server """ # Wrap our our WSGI application (potentially stack) in a Torn...
Parse command line arguments
def parse_arguments(): """Parse command line arguments""" import argparse parser = argparse.ArgumentParser( description=('pyNeuroML v%s: Python utilities for NeuroML2' % __version__ + "\n libNeuroML v%s"%(neuroml.__version__) + "\n jNe...
Or better just use nml2_doc. summary ( show_includes = False )
def quick_summary(nml2_doc): ''' Or better just use nml2_doc.summary(show_includes=False) ''' info = 'Contents of NeuroML 2 document: %s\n'%nml2_doc.id membs = inspect.getmembers(nml2_doc) for memb in membs: if isinstance(memb[1], list) and len(memb[1])>0 \ and not...
Execute a command in specific working directory
def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'], prefix="Output: ", env=None): """Execute a command in specific working directory""" if os.name == 'nt': directory = os.path.normpath(directory) print_comment("Executing: (%s) in direc...
print_comment_v ( exec_str )
def evaluate_component(comp_type, req_variables={}, parameter_values={}): print_comment('Evaluating %s with req:%s; params:%s'%(comp_type.name,req_variables,parameter_values)) exec_str = '' return_vals = {} from math import exp for p in parameter_values: exec_str+='%s = %s\n'%(p, get_va...
Executed after dispatch has returned and the response populated prior to anything being sent to the client.
def after(self, context, exc=None): """Executed after dispatch has returned and the response populated, prior to anything being sent to the client.""" duration = context._duration = round((time.time() - context._start_time) * 1000) # Convert to ms. delta = unicode(duration) # Default response augmentatio...
Apply a flat namespace transformation to recreate ( in some respects ) a rich structure. This applies several transformations which may be nested: foo ( singular ): define a simple value named foo foo ( repeated ): define a simple value for placement in an array named foo foo []: define a simple value for placement in ...
def _process_flat_kwargs(source, kwargs): """Apply a flat namespace transformation to recreate (in some respects) a rich structure. This applies several transformations, which may be nested: `foo` (singular): define a simple value named `foo` `foo` (repeated): define a simple value for placement in an arr...
Parse command - line arguments.
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A file for converting NeuroML v2 files into POVRay files for 3D rendering") parser.add_argument('neuroml_file', type=str, metavar='<NeuroML file>', help='NeuroML ...
Prepare the incoming configuration and ensure certain expected values are present. For example this ensures BaseExtension is included in the extension list and populates the logging config.
def _configure(self, config): """Prepare the incoming configuration and ensure certain expected values are present. For example, this ensures BaseExtension is included in the extension list, and populates the logging config. """ config = config or dict() # We really need this to be there. if 'extensio...
Initiate a web server service to serve this application. You can always use the Application instance as a bare WSGI application of course. This method is provided as a convienence. Pass in the name of the service you wish to use and any additional configuration options appropriate for that service. Almost all services ...
def serve(self, service='auto', **options): # pragma: no cover """Initiate a web server service to serve this application. You can always use the Application instance as a bare WSGI application, of course. This method is provided as a convienence. Pass in the name of the service you wish to use, and any...
Process a single WSGI request/ response cycle. This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware the __call__ attribute of the Application instance will either become this or become the outermost middleware callable. Most apps won t utilize middleware the extension ...
def application(self, environ, start_response): """Process a single WSGI request/response cycle. This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware, the `__call__` attribute of the Application instance will either become this, or become the outermost midd...
Swaps the alignment so that the reference becomes the query and vice - versa. Swaps their names coordinates etc. The frame is not changed
def _swap(self): '''Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed''' self.ref_start, self.qry_start = self.qry_start, self.ref_start self.ref_end, self.qry_end = self.qry_end, self.ref_end self.hit...
Returns a pyfastaq. intervals. Interval object of the start and end coordinates in the query sequence
def qry_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence''' return pyfastaq.intervals.Interval(min(self.qry_start, self.qry_end), max(self.qry_start, self.qry_end))
Returns a pyfastaq. intervals. Interval object of the start and end coordinates in the reference sequence
def ref_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence''' return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end))
Returns true iff the direction of the alignment is the same in the reference and the query
def on_same_strand(self): '''Returns true iff the direction of the alignment is the same in the reference and the query''' return (self.ref_start < self.ref_end) == (self.qry_start < self.qry_end)
Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity
def is_self_hit(self): '''Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity''' return self.ref_name == self.qry_name \ and self.ref_start == self.qry_start \ and self.ref_end == self.qry_end \ ...
Changes the coordinates as if the query sequence has been reverse complemented
def reverse_query(self): '''Changes the coordinates as if the query sequence has been reverse complemented''' self.qry_start = self.qry_length - self.qry_start - 1 self.qry_end = self.qry_length - self.qry_end - 1
Changes the coordinates as if the reference sequence has been reverse complemented
def reverse_reference(self): '''Changes the coordinates as if the reference sequence has been reverse complemented''' self.ref_start = self.ref_length - self.ref_start - 1 self.ref_end = self.ref_length - self.ref_end - 1
Returns the alignment as a line in MSPcrunch format. The columns are space - separated and are: 1. score 2. percent identity 3. match start in the query sequence 4. match end in the query sequence 5. query sequence name 6. subject sequence start 7. subject sequence end 8. subject sequence name
def to_msp_crunch(self): '''Returns the alignment as a line in MSPcrunch format. The columns are space-separated and are: 1. score 2. percent identity 3. match start in the query sequence 4. match end in the query sequence 5. query sequence name ...
Given a reference position and a list of variants ( [ variant. Variant ] ) works out the position in the query sequence accounting for indels. Returns a tuple: ( position True|False ) where second element is whether or not the ref_coord lies in an indel. If it is then returns the corresponding start position of the ind...
def qry_coords_from_ref_coord(self, ref_coord, variant_list): '''Given a reference position and a list of variants ([variant.Variant]), works out the position in the query sequence, accounting for indels. Returns a tuple: (position, True|False), where second element is whether o...
Construct the nucmer command
def _nucmer_command(self, ref, qry, outprefix): '''Construct the nucmer command''' if self.use_promer: command = 'promer' else: command = 'nucmer' command += ' -p ' + outprefix if self.breaklen is not None: command += ' -b ' + str(self.breakl...
Construct delta - filter command
def _delta_filter_command(self, infile, outfile): '''Construct delta-filter command''' command = 'delta-filter' if self.min_id is not None: command += ' -i ' + str(self.min_id) if self.min_length is not None: command += ' -l ' + str(self.min_length) ret...
Construct show - coords command
def _show_coords_command(self, infile, outfile): '''Construct show-coords command''' command = 'show-coords -dTlro' if not self.coords_header: command += ' -H' return command + ' ' + infile + ' > ' + outfile
Write commands into a bash script
def _write_script(self, script_name, ref, qry, outfile): '''Write commands into a bash script''' f = pyfastaq.utils.open_file_write(script_name) print(self._nucmer_command(ref, qry, 'p'), file=f) print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f) print(self._s...
Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory
def run(self): ''' Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory ''' qry = os.path.abspath(self.qry) ref = os.path.abspath(self.ref) outfile = os.path.abspath(self.outf...
Indels are reported over multiple lines 1 base insertion or deletion per line. This method extends the current variant by 1 base if it s an indel and adjacent to the new SNP and returns True. If the current variant is a SNP does nothing and returns False
def update_indel(self, nucmer_snp): '''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False''' new_v...
Helper function to open the results file ( coords file ) and create alignment objects with the values in it
def reader(fname): '''Helper function to open the results file (coords file) and create alignment objects with the values in it''' f = pyfastaq.utils.open_file_read(fname) for line in f: if line.startswith('[') or (not '\t' in line): continue yield alignment.Alignment(line) ...
Converts a coords file to a file in MSPcrunch format ( for use with ACT most likely ). ACT ignores sequence names in the crunch file and just looks at the numbers. To make a compatible file the coords all must be shifted appropriately which can be done by providing both the ref_fai and qry_fai options. Both or neither ...
def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None): '''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely). ACT ignores sequence names in the crunch file, and just looks at the numbers. To make a compatible file, the coords all must be shifted appro...
Common handler for all the HTTP requests.
def _request(self, method, url, params=None, headers=None, data=None): """Common handler for all the HTTP requests.""" if not params: params = {} # set default headers if not headers: headers = { 'accept': '*/*' } if method...
Sphinx role for linking to a user profile. Defaults to linking to Github profiles but the profile URIS can be configured via the issues_user_uri config value.
def user_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text a...
Sphinx role for linking to a CVE on https:// cve. mitre. org.
def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a CVE on https://cve.mitre.org. Examples: :: :cve:`CVE-2018-17175` """ options = options or {} content = content or [] has_explicit_title, title, target = split_explicit_title...
Write the given iterable of values ( line ) to the file as items on the same line. Any argument that stringifies to a string legal as a TSV data item can be written. Does not copy the line or build a big string in memory.
def list_line(self, line): """ Write the given iterable of values (line) to the file as items on the same line. Any argument that stringifies to a string legal as a TSV data item can be written. Does not copy the line or build a big string in memory. """ ...
Parse metadata to obtain list of mustache templates then load those templates.
def prepare(doc): """ Parse metadata to obtain list of mustache templates, then load those templates. """ doc.mustache_files = doc.get_metadata('mustache') if isinstance(doc.mustache_files, basestring): # process single YAML value stored as string if not doc.mustache_files: ...
Apply combined mustache template to all strings in document.
def action(elem, doc): """ Apply combined mustache template to all strings in document. """ if type(elem) == Str and doc.mhash is not None: elem.text = doc.mrenderer.render(elem.text, doc.mhash) return elem
Determine the name of the callback to wrap around the json output.
def get_callback(self, renderer_context): """ Determine the name of the callback to wrap around the json output. """ request = renderer_context.get('request', None) params = request and get_query_params(request) or {} return params.get(self.callback_parameter, self.defaul...
Renders into jsonp wrapping the json output in a callback function.
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders into jsonp, wrapping the json output in a callback function. Clients may set the callback function name using a query parameter on the URL, for example: ?callback=exampleCallbackName """ ...
Analyses the measurement with the given parameters: param measurementId:: return:
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Loading raw data for ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.C...
Return Julian day count of given ISO year week and day
def to_jd(year, week, day): '''Return Julian day count of given ISO year, week, and day''' return day + n_weeks(SUN, gregorian.to_jd(year - 1, 12, 28), week)
Return tuple of ISO ( year week day ) for Julian day
def from_jd(jd): '''Return tuple of ISO (year, week, day) for Julian day''' year = gregorian.from_jd(jd)[0] day = jwday(jd) + 1 dayofyear = ordinal.from_jd(jd)[1] week = trunc((dayofyear - day + 10) / 7) # Reset year if week < 1: week = weeks_per_year(year - 1) year = year ...
Number of ISO weeks in a year
def weeks_per_year(year): '''Number of ISO weeks in a year''' # 53 weeks: any year starting on Thursday and any leap year starting on Wednesday jan1 = jwday(gregorian.to_jd(year, 1, 1)) if jan1 == THU or (jan1 == WED and isleap(year)): return 53 else: return 52
For STScI GEIS files need to do extra steps.
def stsci(hdulist): """For STScI GEIS files, need to do extra steps.""" instrument = hdulist[0].header.get('INSTRUME', '') # Update extension header keywords if instrument in ("WFPC2", "FOC"): rootname = hdulist[0].header.get('ROOTNAME', '') filetype = hdulist[0].header.get('FILETYPE',...
For STScI GEIS files need to do extra steps.
def stsci2(hdulist, filename): """For STScI GEIS files, need to do extra steps.""" # Write output file name to the primary header instrument = hdulist[0].header.get('INSTRUME', '') if instrument in ("WFPC2", "FOC"): hdulist[0].header['FILENAME'] = filename
Input GEIS files input will be read and a HDUList object will be returned.
def readgeis(input): """Input GEIS files "input" will be read and a HDUList object will be returned. The user can use the writeto method to write the HDUList object to a FITS file. """ global dat cardLen = fits.Card.length # input file(s) must be of the form *.??h and *.??d ...
Parse two input arguments and return two lists of file names
def parse_path(f1, f2): """Parse two input arguments and return two lists of file names""" import glob # if second argument is missing or is a wild card, point it # to the current directory f2 = f2.strip() if f2 == '' or f2 == '*': f2 = './' # if the first argument is a directory...
Recursively parse user input based upon the irafglob program and construct a list of files that need to be processed. This program addresses the following deficiencies of the irafglob program::
def parseinput(inputlist,outputname=None, atfile=None): """ Recursively parse user input based upon the irafglob program and construct a list of files that need to be processed. This program addresses the following deficiencies of the irafglob program:: parseinput can extract filenames from asso...
Determine if the filename provided to the function belongs to an association.
def checkASN(filename): """ Determine if the filename provided to the function belongs to an association. Parameters ---------- filename: string Returns ------- validASN : boolean value """ # Extract the file extn type: extnType = filename[filename.rfind('_')+1:filena...
Determine the number of inputfiles provided by the user and the number of those files that are association tables
def countinputs(inputlist): """ Determine the number of inputfiles provided by the user and the number of those files that are association tables Parameters ---------- inputlist : string the user input Returns ------- numInputs: int number of inputs provided by th...
show a summary of all projects
def summary(logfile, time_format): "show a summary of all projects" def output(summary): width = max([len(p[0]) for p in summary]) + 3 print '\n'.join([ "%s%s%s" % (p[0], ' ' * (width - len(p[0])), colored(minutes_to_txt(p[1]), 'red')) for p in summary]) output(server.summarize(read(logfil...
show current status
def status(logfile, time_format): "show current status" try: r = read(logfile, time_format)[-1] if r[1][1]: return summary(logfile, time_format) else: print "working on %s" % colored(r[0], attrs=['bold']) print " since %s" % colored( server.date_to_txt(r[1][0], time_format...
start tracking for <project >
def start(project, logfile, time_format): "start tracking for <project>" records = read(logfile, time_format) if records and not records[-1][1][1]: print "error: there is a project already active" return write(server.start(project, records), logfile, time_format) print "starting work on %s" % color...
stop tracking for the active project
def stop(logfile, time_format): "stop tracking for the active project" def save_and_output(records): records = server.stop(records) write(records, logfile, time_format) def output(r): print "worked on %s" % colored(r[0], attrs=['bold']) print " from %s" % colored( server.date_t...
parses a stream with text formatted as a Timed logfile and shows a summary
def parse(logfile, time_format): "parses a stream with text formatted as a Timed logfile and shows a summary" records = [server.record_from_txt(line, only_elapsed=True, time_format=time_format) for line in sys.stdin.readlines()] # TODO: make this code better. def output(summary): width = max([len(p[0]...
prints a newline - separated list of all projects
def projects(logfile, time_format): "prints a newline-separated list of all projects" print '\n'.join(server.list_projects(read(logfile, time_format)))
Returns a formatted string with the current local time.
def getLTime(): """Returns a formatted string with the current local time.""" _ltime = _time.localtime(_time.time()) tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime) return tlm_str
Returns a formatted string with the current date.
def getDate(): """Returns a formatted string with the current date.""" _ltime = _time.localtime(_time.time()) date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime) return date_str
Convert DATE string into a decimal year.
def convertDate(date): """Convert DATE string into a decimal year.""" d, t = date.split('T') return decimal_date(d, timeobs=t)
Convert DATE - OBS ( and optional TIME - OBS ) into a decimal year.
def decimal_date(dateobs, timeobs=None): """Convert DATE-OBS (and optional TIME-OBS) into a decimal year.""" year, month, day = dateobs.split('-') if timeobs is not None: hr, min, sec = timeobs.split(':') else: hr, min, sec = 0, 0, 0 rdate = datetime.datetime(int(year), int(month),...
Converts an integer input into its component bit values as a list of power of 2 integers.
def interpretDQvalue(input): """ Converts an integer 'input' into its component bit values as a list of power of 2 integers. For example, the bit value 1027 would return [1, 2, 1024] """ nbits = 16 # We will only support integer values up to 2**128 for iexp in [16, 32, 64, 128]: ...
Returns -------- isFits: tuple An ( isfits fitstype ) tuple. The values of isfits and fitstype are specified as:
def isFits(input): """ Returns -------- isFits: tuple An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and ``fitstype`` are specified as: - ``isfits``: True|False - ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None Notes ----- ...
Checks whether files are writable. It is up to the calling routine to raise an Exception if desired.
def verifyWriteMode(files): """ Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out...
Returns a comma - separated string of filter names extracted from the input header ( PyFITS header object ). This function has been hard - coded to support the following instruments:
def getFilterNames(header, filternames=None): """ Returns a comma-separated string of filter names extracted from the input header (PyFITS header object). This function has been hard-coded to support the following instruments: ACS, WFPC2, STIS This function relies on the 'INSTRUME' keywor...
Build rootname for a new file.
def buildNewRootname(filename, extn=None, extlist=None): """ Build rootname for a new file. Use 'extn' for new filename if given, does NOT append a suffix/extension at all. Does NOT check to see if it exists already. Will ALWAYS return a new filename. """ # Search known suffixes to r...
Build a new rootname for an existing file and given extension.
def buildRootname(filename, ext=None): """ Build a new rootname for an existing file and given extension. Any user supplied extensions to use for searching for file need to be provided as a list of extensions. Examples -------- :: >>> rootname = buildRootname(filename, ext=['_dth...
General write - safe method for returning a keyword value from the header of a IRAF recognized image.
def getKeyword(filename, keyword, default=None, handle=None): """ General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string. """ # Insure that there is at least 1 extension specified... if filename.find('[') < 0: ...
Return a copy of the PRIMARY header along with any group/ extension header for this filename specification.
def getHeader(filename, handle=None): """ Return a copy of the PRIMARY header, along with any group/extension header for this filename specification. """ _fname, _extn = parseFilename(filename) # Allow the user to provide an already opened PyFITS object # to derive the header from... # ...
Add/ update keyword to header with given value.
def updateKeyword(filename, key, value,show=yes): """Add/update keyword to header with given value.""" _fname, _extn = parseFilename(filename) # Open image whether it is FITS or GEIS _fimg = openImage(_fname, mode='update') # Address the correct header _hdr = getExtn(_fimg, _extn).header ...
Build a new FITS filename for a GEIS input image.
def buildFITSName(geisname): """Build a new FITS filename for a GEIS input image.""" # User wants to make a FITS copy and update it... _indx = geisname.rfind('.') _fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits' return _fitsname
Opens file and returns PyFITS object. Works on both FITS and GEIS formatted images.
def openImage(filename, mode='readonly', memmap=False, writefits=True, clobber=True, fitsname=None): """ Opens file and returns PyFITS object. Works on both FITS and GEIS formatted images. Notes ----- If a GEIS or waivered FITS image is used as input, it will convert it to a ...
Parse out filename from any specified extensions.
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. """ # Parse out any extension specified in filename _indx = filename.find('[') if _indx > 0: # Read extension name provided _fname = fil...
Parse a string representing a qualified fits extension name as in the output of parseFilename and return a tuple ( str ( extname ) int ( extver )) which can be passed to astropy. io. fits functions using the ext kw.
def parseExtn(extn=None): """ Parse a string representing a qualified fits extension name as in the output of `parseFilename` and return a tuple ``(str(extname), int(extver))``, which can be passed to `astropy.io.fits` functions using the 'ext' kw. Default return is the first extension in a fit...