work out flight time for a log file
541741
def flight_time(logfile):
    ''''''
    print("Processing log %s" % filename)
    mlog = mavutil.mavlink_connection(filename)

    in_air = False
    start_time = 0.0
    total_time = 0.0
    total_dist = 0.0
    t = None
    last_msg = None
    last_time_usec = None

    while True:
        m = mlog.recv_match(type=['GPS','GPS_RAW_INT'], condition=args.condition)
        if m is None:
            if in_air:
                total_time += time.mktime(t) - start_time
            if total_time > 0:
                print("Flight time : %u:%02u" % (int(total_time)/60, int(total_time)%60))
            return (total_time, total_dist)
        if m.get_type() == 'GPS_RAW_INT':
            groundspeed = m.vel*0.01
            status = m.fix_type
            time_usec = m.time_usec
        else:
            groundspeed = m.Spd
            status = m.Status
            time_usec = m.TimeUS
        if status < 3:
            continue
        t = time.localtime(m._timestamp)
        if groundspeed > args.groundspeed and not in_air:
            print("In air at %s (percent %.0f%% groundspeed %.1f)" % (time.asctime(t), mlog.percent, groundspeed))
            in_air = True
            start_time = time.mktime(t)
        elif groundspeed < args.groundspeed and in_air:
            print("On ground at %s (percent %.1f%% groundspeed %.1f  time=%.1f seconds)" % (
                time.asctime(t), mlog.percent, groundspeed, time.mktime(t) - start_time))
            in_air = False
            total_time += time.mktime(t) - start_time

        if last_msg is None or time_usec > last_time_usec or time_usec+30e6 < last_time_usec:
            if last_msg is not None:
                total_dist += distance_two(last_msg, m)
            last_msg = m
            last_time_usec = time_usec
    return (total_time, total_dist)
836606
def logged_timer(message):
    ""
    tick = time.time()
    yield
    tock = time.time()
    logging.info("%s: %.3f seconds", message, (tock - tick))
671265
def log_date_time_string(self):
        """"""
        now = time.time()
        year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
        s = "%02d/%3s/%04d %02d:%02d:%02d" % (
                day, self.monthname[month], year, hh, mm, ss)
        return s
1279293
def accessed(filename):
    '''
    
    '''
    if isinstance(filename, file):
        filename = filename.name

    return duration(os.stat(filename)[stat.ST_ATIME])
315457
def _get_timestamp(self):
        """"""
        filename_date = _find_date(os.path.basename(self._path))
        if filename_date:
            return filename_date
116222
def write_log(self, fs=None):
        
        log = StringIO.StringIO()
        log.write(self.setup_src)

        # If the function is not bound, write the test score to the log
        if not self.is_class_method:
            time_avg = convert_time_units(self.time_average_seconds)
            log.write("\nAverage time: {0} \n".format(time_avg))

        if fs:
            with open(fs, 'w') as _f:
                _f.write(log.getvalue())
622804
def _calculate_bounds(self):
        """"""
        if self._bounds_calculated:
            # Assume no need to recalc bounds for lifetime of a Logfile object
            return

        if self.from_stdin:
            return False

        # we should be able to find a valid log line within max_start_lines
        max_start_lines = 10
        lines_checked = 0

        # get start datetime
        for line in self.filehandle:
            logevent = LogEvent(line)
            lines_checked += 1
            if logevent.datetime:
                self._start = logevent.datetime
                self._timezone = logevent.datetime.tzinfo
                self._datetime_format = logevent.datetime_format
                self._datetime_nextpos = logevent._datetime_nextpos
                break
            if lines_checked > max_start_lines:
                break

        # sanity check before attempting to find end date
        if (self._start is None):
            raise SystemExit("Error: <%s> does not appear to be a supported "
                             "MongoDB log file format" % self.filehandle.name)

        # get end datetime (lines are at most 10k,
        # go back 30k at most to make sure we catch one)
        self.filehandle.seek(0, 2)
        self._filesize = self.filehandle.tell()
        self.filehandle.seek(-min(self._filesize, 30000), 2)

        for line in reversed(self.filehandle.readlines()):
            logevent = LogEvent(line)
            if logevent.datetime:
                self._end = logevent.datetime
                break

        # if there was a roll-over, subtract 1 year from start time
        if self._end < self._start:
            self._start = self._start.replace(year=self._start.year - 1)
            self._year_rollover = self._end
        else:
            self._year_rollover = False

        # reset logfile
        self.filehandle.seek(0)
        self._bounds_calculated = True

        return True
298384
def projects(logfile, time_format):
  ""

  print '\n'.join(server.list_projects(read(logfile, time_format)))
1314470
def analyze_logfile_object(self, file_object):
        """"""
        log_parser = LogParser()

        if self._start_time is None:
            self._start_time = datetime.now()
            if self._timeout != 0:
                self._end_time = self._start_time + timedelta(minutes=self._timeout)
            else:
                self._end_time = None

        # For each line in the logfile ...
        for line in file_object:
            if self._end_time is not None and datetime.now() > self._end_time:
                self._run_stats['timedOut'] = True
                self._run_stats['timeoutInMinutes'] = self._timeout
                break
            self._process_query(line, log_parser)

        return 0
234947
def calculate_file_access_time(workflow_workspace):
    """"""
    access_times = {}
    for subdir, dirs, files in os.walk(workflow_workspace):
        for file in files:
            file_path = os.path.join(subdir, file)
            access_times[file_path] = os.stat(file_path).st_atime
    return access_times
681089
def _log_info(self):
        """"""
        if self.cloud == 'ssh':
            self.results['info'] = {
                'platform': self.cloud,
                'distro': self.distro_name,
                'image': self.instance_ip,
                'timestamp': self.time_stamp,
                'log_file': self.log_file,
                'results_file': self.results_file
            }
        else:
            self.results['info'] = {
                'platform': self.cloud,
                'region': self.region,
                'distro': self.distro_name,
                'image': self.image_id,
                'instance': self.running_instance_id,
                'timestamp': self.time_stamp,
                'log_file': self.log_file,
                'results_file': self.results_file
            }

        self._write_to_log(
            '\n'.join(
                '%s: %s' % (key, val) for key, val
                in self.results['info'].items()
            )
        )
80114
def extract_capture_time(self):
        '''
        
        '''
        time_string = exif_datetime_fields()[0]
        capture_time, time_field = self._extract_alternative_fields(
            time_string, 0, str)
        if time_field in exif_gps_date_fields()[0]:
            capture_time = self.extract_gps_time()
            return capture_time

        if capture_time is 0:
            # try interpret the filename
            try:
                capture_time = datetime.datetime.strptime(os.path.basename(
                    self.filename)[:-4] + '000', '%Y_%m_%d_%H_%M_%S_%f')
            except:
                return None
        else:
            capture_time = capture_time.replace(" ", "_")
            capture_time = capture_time.replace(":", "_")
            capture_time = capture_time.replace(".", "_")
            capture_time = capture_time.replace("-", "_")
            capture_time = capture_time.replace(",", "_")
            capture_time = "_".join(
                [ts for ts in capture_time.split("_") if ts.isdigit()])
            capture_time, subseconds = format_time(capture_time)
            sub_sec = "0"
            if not subseconds:
                sub_sec = self.extract_subsec()
            capture_time = capture_time + \
                datetime.timedelta(seconds=float("0." + sub_sec))

        return capture_time
195798
def lock_time(logfile):
    ''''''
    print("Processing log %s" % filename)
    mlog = mavutil.mavlink_connection(filename)

    locked = False
    start_time = 0.0
    total_time = 0.0
    t = None
    m = mlog.recv_match(type=['GPS_RAW_INT','GPS_RAW'], condition=args.condition)
    if m is None:
        return 0

    unlock_time = time.mktime(time.localtime(m._timestamp))

    while True:
        m = mlog.recv_match(type=['GPS_RAW_INT','GPS_RAW'], condition=args.condition)
        if m is None:
            if locked:
                total_time += time.mktime(t) - start_time
            if total_time > 0:
                print("Lock time : %u:%02u" % (int(total_time)/60, int(total_time)%60))
            return total_time
        t = time.localtime(m._timestamp)
        if m.fix_type >= 2 and not locked:
            print("Locked at %s after %u seconds" % (time.asctime(t),
                                                     time.mktime(t) - unlock_time))
            locked = True
            start_time = time.mktime(t)
        elif m.fix_type == 1 and locked:
            print("Lost GPS lock at %s" % time.asctime(t))
            locked = False
            total_time += time.mktime(t) - start_time
            unlock_time = time.mktime(t)
        elif m.fix_type == 0 and locked:
            print("Lost protocol lock at %s" % time.asctime(t))
            locked = False
            total_time += time.mktime(t) - start_time
            unlock_time = time.mktime(t)
    return total_time
571430
function logtime() {
  var d = new Date()
    , space = ' '
    , delimiter = ':'
    , str = d.toString()
    , month = str.split(' ')[1];
  return d.getDate()
    + space + month + space
    + d.getHours() + delimiter
    + pad(d.getMinutes()) + delimiter
    + pad(d.getSeconds())
    + '.'
    + pad(d.getMilliseconds(), 3);
}
1332203
def _parse_logline_timestamp(t):
    
    date, time = t.split(' ')
    month, day = date.split('-')
    h, m, s = time.split(':')
    s, ms = s.split('.')
    return (month, day, h, m, s, ms)
1182101
def log_last_error(fname, context=None):
    """"""
    fd = open(fname, 'a')
    log_time(fd)
    if context:
        print("Context", file=fd)
        print("-------", file=fd)
        print("", file=fd)
        if PY2:
            print(u' '.join(context).encode('utf-8').strip(), file=fd)
        else:
            print(context, file=fd)
        print("", file=fd)
        print("Traceback", file=fd)
        print("---------", file=fd)
        print("", file=fd)
    traceback.print_exc(file=fd)
    print("", file=fd)
    print("", file=fd)
398245
def timeit (func, log, limit):
    """"""

    def newfunc (*args, **kwargs):
        """Execute function and print execution time."""
        t = time.time()
        res = func(*args, **kwargs)
        duration = time.time() - t
        if duration > limit:
            print(func.__name__, "took %0.2f seconds" % duration, file=log)
            print(args, file=log)
            print(kwargs, file=log)
        return res
    return update_func_meta(newfunc, func)