当前位置: 首页>>代码示例>>Python>>正文


Python utils.old_div方法代码示例

本文整理汇总了Python中past.utils.old_div方法的典型用法代码示例。如果您正苦于以下问题:Python utils.old_div方法的具体用法?Python utils.old_div怎么用?Python utils.old_div使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在past.utils的用法示例。


在下文中一共展示了utils.old_div方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: RGBToXTerm

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def RGBToXTerm(red, green, blue):
    """Convert RGB values (0-255) to the closes XTerm color."""
    sred = ChannelStepFunction(red)
    sgreen = ChannelStepFunction(green)
    sblue = ChannelStepFunction(blue)

    # Greyscale starts at xterm 232 and has 12 shades. Black and white are part
    # of the 16-color range at the base of the spectrum.
    if sred == sgreen == sblue:
        avg = old_div((red + green + blue), 3)
        if avg < 0x8:
            return 0
        elif avg > 0xee:
            return 15
        else:
            return 232 + GreyscaleStepFunction(avg)

    return (16  # base offset
            + ChannelStepFunction(blue)  # Blue increases in the inner loop.
            + ChannelStepFunction(green) * 6  # Green increases in the middle.
            + ChannelStepFunction(red) * 6 ** 2)  # Outer loop for red. 
开发者ID:google,项目名称:rekall,代码行数:23,代码来源:colors.py

示例2: test_timeout

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def test_timeout():

    duration = 0.005
    below_duration = duration - old_div(duration, 2)
    above_duration = duration + old_div(duration, 2)

    def func():
        time.sleep(duration)
        return 42

    def errfunc():
        raise ValueError('Something went wrong')

    assert timeout(func, timeout_secs=below_duration) is False
    assert timeout(func, timeout_secs=above_duration) == 42

    # FIXME: Better catch and report the exception?
    # FIXME: Derive "timeout_secs" from "duration"
    with pytest.raises(ValueError) as excinfo:
        timeout(errfunc, timeout_secs=0.10, default='foobar')
        excinfo.message == 'Something went wrong' 
开发者ID:jpmens,项目名称:mqttwarn,代码行数:23,代码来源:test_util.py

示例3: nsec_to_clock_t

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def nsec_to_clock_t(self, x):
        """Convers nanoseconds to a clock_t. Introduced in 3.17.

        http://lxr.free-electrons.com/source/kernel/time/time.c?v=3.17#L703
        """
        NSEC_PER_SEC = 1000000000
        USER_HZ = 100

        if NSEC_PER_SEC % USER_HZ == 0:
            return old_div(x, (old_div(NSEC_PER_SEC, USER_HZ)))
        elif USER_HZ % 512 == 0:
            return old_div((old_div((x * USER_HZ), 512)), (old_div(NSEC_PER_SEC, 512)))
        else:
            return old_div((x*9), (old_div((9 * NSEC_PER_SEC + (old_div(USER_HZ,2))), USER_HZ)))


# Legacy for old profiles 
开发者ID:google,项目名称:rekall,代码行数:19,代码来源:linux.py

示例4: get_owners

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def get_owners(self, subsection=None):
        """Returns a list of _EPROCESS, virtual offsets for owners."""
        result = []
        if subsection is None:
            subsection = self.get_subsection()

        if subsection:
            for details in self.session.GetParameter("subsections").get(
                    subsection.v(), []):
                task = self.session.profile._EPROCESS(details["task"])
                vad = self.session.profile.Object(offset=details["vad"],
                                                  type_name=details["type"])

                # Find the virtual address.
                size_of_pte = self.session.profile.get_obj_size("_MMPTE")
                relative_offset = old_div((
                    self.pte_address - vad.FirstPrototypePte.v()), size_of_pte)

                virtual_address = (
                    relative_offset * 0x1000 + vad.Start + self.page_offset)

                result.append((task, virtual_address))

        return result 
开发者ID:google,项目名称:rekall,代码行数:26,代码来源:pagefile.py

示例5: Report

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def Report(self, readptr):
        """This will be called periodically to report the progress.

        Note that readptr is specified relative to the start of the range
        operation (WriteStream and CopyToStream)
        """
        readptr = readptr + self.start
        now = self.now()
        if now > self.last_time + old_div(1000000,4):
            # Rate in MB/s.
            rate = ((readptr - self.last_offset) /
                    (now - self.last_time) * 1000000 / 1024/1024)

            sys.stdout.write(" Reading %sMiB / %sMiB  %s MiB/s\r\n" % (
                readptr/1024/1024,
                self.length/1024/1024,
                rate))
            sys.stdout.flush()

            self.last_time = now
            self.last_offset = readptr

        if aff4_abort_signaled:
            sys.stdout.write("\n\nAborted!\n")
            raise RuntimeError("Aborted") 
开发者ID:aff4,项目名称:pyaff4,代码行数:27,代码来源:aff4.py

示例6: _main_loop

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def _main_loop(self):
        '''
        Continuous loop that reads from a kafka topic and tries to validate
        incoming messages
        '''
        self.logger.debug("Processing messages")
        old_time = 0
        while True:
            self._process_messages()
            if self.settings['STATS_DUMP'] != 0:
                new_time = int(old_div(time.time(), self.settings['STATS_DUMP']))
                # only log every X seconds
                if new_time != old_time:
                    self._dump_stats()
                    old_time = new_time

            self._report_self()
            time.sleep(self.settings['SLEEP_TIME']) 
开发者ID:istresearch,项目名称:scrapy-cluster,代码行数:20,代码来源:kafka_monitor.py

示例7: time_extractor

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def time_extractor(columns):
        if not isinstance(columns, tuple):
            columns = (columns,)

        def t_extractor(data):
            for column in columns:
                if column in data:
                    break

            time_stamp = int(data[column])
            hours = old_div(time_stamp, 3600)
            minutes = old_div((time_stamp % 3600), 60)
            seconds = time_stamp % 60

            return "%02d:%02d:%02d" % (hours, minutes, seconds)

        return t_extractor 
开发者ID:aerospike,项目名称:aerospike-admin,代码行数:19,代码来源:table.py

示例8: size

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def size(bytes, system=byte):
    """
    Human-readable file size.
    """
    for factor, suffix in system:
        if bytes >= factor:
            break
    amount = old_div(bytes, factor)
    if isinstance(suffix, tuple):
        singular, multiple = suffix
        if amount == 1:
            suffix = singular
        else:
            suffix = multiple
    if type(amount) == float:
        return "%0.3f%s" % (amount, suffix)
    else:
        return str(amount) + suffix 
开发者ID:aerospike,项目名称:aerospike-admin,代码行数:20,代码来源:filesize.py

示例9: is_server_log_file

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def is_server_log_file(self, file=""):
        if not file:
            return False
        try:
            out, err = shell_command(['head -n 10 "%s"' % (file)])
        except Exception:
            return False
        if err or not out:
            return False
        lines = out.strip().split('\n')
        matched_count = 0
        for line in lines:
            try:
                if re.search(self.server_log_file_identifier_pattern, line):
                    matched_count += 1
            except Exception:
                pass
        if matched_count > (old_div(len(lines),2)):
            return True
        return False 
开发者ID:aerospike,项目名称:aerospike-admin,代码行数:22,代码来源:reader.py

示例10: _get_sensor_details

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def _get_sensor_details(self, index):
        try:
            details = dict()

            entPhysicalNamePrefixIndex = entPhysicalNamePrefix + u'.' + index
            entSensorValueIndex = entSensorValue + u'.' + index
            # https://github.com/PyCQA/pylint/issues/1694
            details[u'sensor_value'] = int(self.sensor_entity_map[entSensorValueIndex])  # pylint: disable=E1136

            # https://github.com/PyCQA/pylint/issues/1694
            entity_description = self.entity_physical_entries_map[entPhysicalNamePrefixIndex]  # pylint: disable=E1136
            if entity_description in MILLI_ENT_STRINGS:
                # TODO how many sig digs?
                details[u'sensor_value'] = old_div(details[u'sensor_value'], 1000)

            sensor_scale_code = int(self.sensor_entity_map[entSensorScale + u'.' + index])  # pylint: disable=E1136
            details[u'sensor_scale'] = sensor_scale_code
            return details
        except Exception as e:
            raise e 
开发者ID:yahoo,项目名称:panoptes,代码行数:22,代码来源:plugin_polling_asr_device_metrics.py

示例11: download_worker_fn

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def download_worker_fn(scraper, img_url, pbar, status_flags, status_lock):
    """ Stnadalone function that downloads images. """
    failed = False
    size_failed = False
    try:
        scraper.download_image(img_url)
    except ImageDownloadError:
        failed = True
    except ImageSizeError:
        size_failed = True
    status_lock.acquire(True)
    if failed:
        status_flags['failed'] += 1
    elif size_failed:
        status_flags['under_min_or_over_max_filesize'] += 1
    status_flags['percent'] = status_flags[
        'percent'] + old_div(100.0, scraper.no_to_download)
    pbar.update(status_flags['percent'] % 100)
    status_lock.release()
    return True 
开发者ID:sananth12,项目名称:ImageScraper,代码行数:22,代码来源:utils.py

示例12: _format_widgets

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def _format_widgets(self):
        r = []
        hfill_inds = []
        num_hfill = 0
        currwidth = 0
        for i, w in enumerate(self.widgets):
            if isinstance(w, ProgressBarWidgetHFill):
                r.append(w)
                hfill_inds.append(i)
                num_hfill += 1
            elif isinstance(w, str):
                r.append(w)
                currwidth += len(w)
            else:
                weval = w.update(self)
                currwidth += len(weval)
                r.append(weval)
        for iw in hfill_inds:
            r[iw] = r[iw].update(
                self, old_div((self.term_width - currwidth), num_hfill))
        return r 
开发者ID:sananth12,项目名称:ImageScraper,代码行数:23,代码来源:progressbar.py

示例13: test_shebang_blank_with_future_division_import

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def test_shebang_blank_with_future_division_import(self):
        """
        Issue #43: Is shebang line preserved as the first
        line by futurize when followed by a blank line?
        """
        before = """
        #!/usr/bin/env python

        import math
        1 / 5
        """
        after = """
        #!/usr/bin/env python

        from __future__ import division
        from past.utils import old_div
        import math
        old_div(1, 5)
        """
        self.convert_check(before, after) 
开发者ID:hughperkins,项目名称:kgsgo-dataset-preprocessor,代码行数:22,代码来源:test_futurize.py

示例14: test_safe_division

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def test_safe_division(self):
        """
        Tests whether Py2 scripts using old-style division still work
        after futurization.
        """
        before = """
        x = 3 / 2
        y = 3. / 2
        assert x == 1 and isinstance(x, int)
        assert y == 1.5 and isinstance(y, float)
        """
        after = """
        from __future__ import division
        from past.utils import old_div
        x = old_div(3, 2)
        y = old_div(3., 2)
        assert x == 1 and isinstance(x, int)
        assert y == 1.5 and isinstance(y, float)
        """
        self.convert_check(before, after) 
开发者ID:hughperkins,项目名称:kgsgo-dataset-preprocessor,代码行数:22,代码来源:test_futurize.py

示例15: path_tz_fix

# 需要导入模块: from past import utils [as 别名]
# 或者: from past.utils import old_div [as 别名]
def path_tz_fix(file_name):
  if is_windows():
      # Calculate the offset between UTC and local time
      tz_shift = old_div((datetime.fromtimestamp(0) -
                  datetime.utcfromtimestamp(0)).seconds,3600)
      # replace timestamp in file_name
      m = re.search('(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})',file_name)
      t_date = datetime.fromtimestamp(time.mktime(time.strptime(m.group(0), '%Y-%m-%d_%H-%M-%S')))
      s_date_fix = (t_date-timedelta(hours=tz_shift)).strftime('%Y-%m-%d_%H-%M-%S')
      return re.sub('\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}',s_date_fix,file_name)
  else:
      return file_name

# time_convert(s_time)
# Change s_time (struct_time) by the offset
# between UTC and local time
# (Windows only) 
开发者ID:jmathai,项目名称:elodie,代码行数:19,代码来源:helper.py


注:本文中的past.utils.old_div方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。