python类floor()的实例源码

PCA9685.py 文件源码 项目:Adafruit_Python_PCA9685 作者: adafruit 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def set_pwm_freq(self, freq_hz):
        """Set the PWM frequency to the provided value in hertz."""
        prescaleval = 25000000.0    # 25MHz
        prescaleval /= 4096.0       # 12-bit
        prescaleval /= float(freq_hz)
        prescaleval -= 1.0
        logger.debug('Setting PWM frequency to {0} Hz'.format(freq_hz))
        logger.debug('Estimated pre-scale: {0}'.format(prescaleval))
        prescale = int(math.floor(prescaleval + 0.5))
        logger.debug('Final pre-scale: {0}'.format(prescale))
        oldmode = self._device.readU8(MODE1);
        newmode = (oldmode & 0x7F) | 0x10    # sleep
        self._device.write8(MODE1, newmode)  # go to sleep
        self._device.write8(PRESCALE, prescale)
        self._device.write8(MODE1, oldmode)
        time.sleep(0.005)
        self._device.write8(MODE1, oldmode | 0x80)
video_editing_mouse.py 文件源码 项目:Blender-power-sequencer 作者: GDquest 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def invoke(self, context, event):
        sequencer = bpy.ops.sequencer

        # get current frame and channel the mouse hovers
        x, y = context.region.view2d.region_to_view(
            x=event.mouse_region_x,
            y=event.mouse_region_y)
        frame, channel = round(x), floor(y)

        # Strip selection
        sequencer.select_all(action='DESELECT')
        to_select = find_strips_mouse(frame, channel)

        if not to_select:
            return {"CANCELLED"}

        for s in to_select:
            s.mute = not s.mute
        return {"FINISHED"}
__init__.py 文件源码 项目:PyPlanet 作者: PyPlanet 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def create_vote(self, action, player, finished_event):
        new_vote = Vote()
        new_vote.action = action
        new_vote.requester = player
        new_vote.votes_current = []
        needed_votes = math.ceil(self.instance.player_manager.count_players / 2)
        if needed_votes == math.floor(self.instance.player_manager.count_players / 2):
            needed_votes += 1
        if needed_votes > self.instance.player_manager.count_players:
            needed_votes = self.instance.player_manager.count_players
        new_vote.votes_required = needed_votes
        new_vote.vote_added = self.vote_added
        new_vote.vote_removed = self.vote_removed
        new_vote.vote_finished = finished_event

        asyncio.ensure_future(self.vote_reminder(new_vote))

        return new_vote
__init__.py 文件源码 项目:PyPlanet 作者: PyPlanet 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def pay_to_player(self, player, data, **kwargs):
        try:
            amount = abs(int(data.amount))

            planets = await self.instance.gbx('GetServerPlanets')
            if amount <= (planets - 2 - math.floor(amount * 0.05)):
                async with self.lock:
                    bill_id = await self.instance.gbx('Pay', data.login, amount, 'Payment from the server')
                    self.current_bills[bill_id] = dict(bill=bill_id, admin=player, player=data.login, amount=-amount)
            else:
                message = '$i$f00Insufficient balance for paying $fff{}$f00 ($fff{}$f00 inc. tax) planets, only got $fff{}$f00.'.format(
                    amount, (amount + 2 + math.floor(amount * 0.05)), planets
                )
                await self.instance.chat(message, player)
        except ValueError:
            message = '$z$s$fff» $i$f00The amount should be a numeric value.'
            await self.instance.chat(message, player)
times.py 文件源码 项目:PyPlanet 作者: PyPlanet 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def format_time(time):
    """
    Format time from integer milliseconds to string format that could be displayed to the end-user.

    :param time: Integer time in milliseconds.
    :type time: int
    :return: String output
    :rtype: str
    """
    hours = math.floor((time / 1000 / 60 / 60))
    minutes = math.floor((time - (hours * 60 * 60 * 1000)) / 1000 / 60)
    seconds = math.floor((time - (hours * 60 * 60 * 1000) - (minutes * 60 * 1000)) / 1000)
    millis = (time - (hours * 60 * 60 * 1000) - (minutes * 60 * 1000) - (seconds * 1000))

    formatted_time = ''
    if hours > 0:
        formatted_time += '{:02d}:{:02d}:'.format(hours, minutes)
    else:
        formatted_time += '{}:'.format(str(minutes))
    return formatted_time + '{:02d}.{:03d}'.format(seconds, millis)
classifier_tf.py 文件源码 项目:human-rl 作者: gsastry 项目源码 文件源码 阅读 49 收藏 0 点赞 0 评论 0
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test])
classifier_tf.py 文件源码 项目:human-rl 作者: gsastry 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test])
classifier_tf.py 文件源码 项目:human-rl 作者: gsastry 项目源码 文件源码 阅读 56 收藏 0 点赞 0 评论 0
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test])
classifier_tf.py 文件源码 项目:human-rl 作者: gsastry 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def split_episodes(self, episode_paths, n_train, n_valid, n_test, seed=None, use_all=True):
        """Split episodes between training, validation and test sets.

        seed: random seed (have split performed consistently every time)"""
        if seed is not None:
            random_state = np.random.get_state()
            np.random.seed(seed)
            np.random.shuffle(episode_paths)
            np.random.set_state(random_state)
        else:
            np.random.shuffle(episode_paths)
        if use_all:
            multiplier = float(len(episode_paths)) / float(n_train + n_valid + n_test)
            n_train = int(math.floor(multiplier * n_train))
            n_valid = int(math.floor(multiplier * n_valid))
            n_test = int(math.floor(multiplier * n_test))

        assert n_train + n_valid + n_test <= len(episode_paths)
        return (episode_paths[:n_train], episode_paths[n_train:n_train + n_valid],
                episode_paths[n_train + n_test:n_train + n_test + n_test])
5_trick_feature.py 文件源码 项目:Tencent2017_Final_Rank28_code 作者: Dojocat-GO 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def interclick(clicktime1, clicktime2):
    second1 = clicktime1 % 100
    clicktime1 = clicktime1 // 100
    min1 = clicktime1 % 100
    hour1 = math.floor((clicktime1 % 10000) / 100)
    day1 = math.floor(clicktime1 / 10000)

    second2 = clicktime2 % 100
    clicktime2 = clicktime2 // 100
    min2 = clicktime2 % 100
    hour2 = math.floor((clicktime2 % 10000) / 100)
    day2 = math.floor(clicktime2 / 10000)
    interclicktime_min = ((day2 * 1440 + hour2 * 60 + min2) - (day1 * 1440 + hour1 * 60 + min1))
    interclicktime_second = ((day2 * 1440 + hour2 * 60 + min2) * 60 + second2) - (
    (day1 * 1440 + hour1 * 60 + min1) * 60 + second1)
    return interclicktime_min, interclicktime_second
findcve.py 文件源码 项目:findcve 作者: garethr 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def lumogon(file):
    """
    Lumogon scans the output from the lumogon container
    inspection tool
    """
    cve_data = load_vulnerability_database()
    containers = load_data(file)["containers"]
    for container in containers:
        click.secho("==> Scanning %s" % containers[container]["container_name"], fg="blue")
        packages = containers[container]["capabilities"]["dpkg"]["payload"]
        host = containers[container]["capabilities"]["host"]["payload"]
        os = DEBIAN_CODENAMES[math.floor(float(host["platformversion"]))]
        for package in sorted(packages):
            version = packages[package]
            vulns = determine_cves(package, version, os, cve_data)
            print_vulns(package, vulns)
graphics.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __nearest_pow_2(self,x):
        """
        Find power of two nearest to x
        >>> _nearest_pow_2(3)
        2.0
        >>> _nearest_pow_2(15)
        16.0
        :type x: float
        :param x: Number
        :rtype: Int
        :return: Nearest power of 2 to x
        """
        a = math.pow(2, math.ceil(np.log2(x)))
        b = math.pow(2, math.floor(np.log2(x)))
        if abs(a - x) < abs(b - x):
            return a
        else:
            return b

    # calculate spectrogram of signals
func_tools.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _nearest_pow_2(x):
    """
    Find power of two nearest to x
    >>> _nearest_pow_2(3)
    2.0
    >>> _nearest_pow_2(15)
    16.0
    :type x: float
    :param x: Number
    :rtype: Int
    :return: Nearest power of 2 to x
    """
    a = M.pow(2, M.ceil(np.log2(x)))
    b = M.pow(2, M.floor(np.log2(x)))
    if abs(a - x) < abs(b - x):
        return a
    else:
        return b
func_tools.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _nearest_pow_2(x):
    """
    Find power of two nearest to x
    >>> _nearest_pow_2(3)
    2.0
    >>> _nearest_pow_2(15)
    16.0
    :type x: float
    :param x: Number
    :rtype: Int
    :return: Nearest power of 2 to x
    """
    a = M.pow(2, M.ceil(np.log2(x)))
    b = M.pow(2, M.floor(np.log2(x)))
    if abs(a - x) < abs(b - x):
        return a
    else:
        return b
util.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def compute_logarithmic_scale(min_, max_, min_scale, max_scale):
    """Compute an optimal scale for logarithmic"""
    if max_ <= 0 or min_ <= 0:
        return []
    min_order = int(floor(log10(min_)))
    max_order = int(ceil(log10(max_)))
    positions = []
    amplitude = max_order - min_order
    if amplitude <= 1:
        return []
    detail = 10.
    while amplitude * detail < min_scale * 5:
        detail *= 2
    while amplitude * detail > max_scale * 3:
        detail /= 2
    for order in range(min_order, max_order + 1):
        for i in range(int(detail)):
            tick = (10 * i / detail or 1) * 10 ** order
            tick = round_to_scale(tick, tick)
            if min_ <= tick <= max_ and tick not in positions:
                positions.append(tick)
    return positions
recipe-511478.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def percentile(N, percent, key=lambda x:x):
    """
    Find the percentile of a list of values.

    @parameter N - is a list of values. Note N MUST BE already sorted.
    @parameter percent - a float value from 0.0 to 1.0.
    @parameter key - optional key function to compute value from each element of N.

    @return - the percentile of the values
    """
    if not N:
        return None
    k = (len(N)-1) * percent
    f = math.floor(k)
    c = math.ceil(k)
    if f == c:
        return key(N[int(k)])
    d0 = key(N[int(f)]) * (c-k)
    d1 = key(N[int(c)]) * (k-f)
    return d0+d1

# median is 50th percentile.
__init__.py 文件源码 项目:BookCloud 作者: livro-aberto 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def package():
    sent_package = {}
    sent_package['get_requests'] = get_requests
    def has_requests(project, branch):
        return len(get_requests(project, branch)) > 0
    sent_package['has_requests'] = has_requests
    sent_package['get_log_diff'] = get_log_diff
    sent_package['last_modified'] = last_modified
    sent_package['get_branch_by_name'] = get_branch_by_name
    sent_package['hash'] = lambda x: hashlib.sha256(x).hexdigest()
    sent_package['_'] = _
    sent_package['url_encode'] = lambda x: urllib.quote(x, safe='')
    sent_package['current_user'] = current_user
    sent_package['floor'] = math.floor
    sent_package['len'] = len
    sent_package['getattr'] = getattr
    sent_package['commit_diff'] = commit_diff
    return sent_package
adventure.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def stop_foraging(self):
        if self.last_action and self.last_action[0] == "foraging":
            item = self.last_action[1]
            time_spent = math.ceil(time.time() - self.last_action_time) / 60
            self.last_action = None
            self.last_action_time = None
            item_amount = math.floor(time_spent * self.foraging_rate)
            self.inventory[item] = self.inventory.get(item, 0) + item_amount
            if self.inventory[item] == 0:
                del self.inventory[item]
            self.foraging_xp += item_amount
            secondary_item = forageables[item][0]
            tertiary_item = forageables[item][1]
            secondary_amount = random.randint(0, item_amount)
            tertiary_amount = math.floor(random.randint(0, item_amount) / 100)
            self.inventory[secondary_item] = self.inventory.get(secondary_item, 0) + secondary_amount
            if self.inventory[secondary_item] == 0:
                del self.inventory[secondary_item]
            self.inventory[tertiary_item] = self.inventory.get(tertiary_item, 0) + tertiary_amount
            if self.inventory[tertiary_item] == 0:
                del self.inventory[tertiary_item]
            self.write_data()
            return item, time_spent, item_amount, secondary_amount, tertiary_amount
        else:
            return False, self.last_action
adventure.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def stop_woodcutting(self):
        if self.last_action and self.last_action[0] == "woodcutting":
            wood_type = self.last_action[1]
            time_spent = math.ceil(time.time() - self.last_action_time) / 60
            self.last_action = None
            self.last_action = None
            current_wood_lvl = wood_lvl(wood_type)
            wood_amount = math.floor(time_spent * self.wood_rate(wood_type) * self.woodcutting_rate)
            xp_amount = current_wood_lvl * wood_amount
            self.inventory[wood_type] = self.inventory.get(wood_type, 0) + wood_amount
            if self.inventory[wood_type] == 0:
                del self.inventory[wood_type]
            self.woodcutting_xp += xp_amount
            self.write_data()
            return wood_type, time_spent, wood_amount, xp_amount
        else:
            return False, self.last_action
supremm_testharness.py 文件源码 项目:supremm 作者: ubccr 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, archivelist):
        self.node_archives = archivelist
        self.jobdir = os.path.dirname(archivelist[0])
        self.job_id = "1"
        self.end_str = "end"
        self.walltime = 9751
        self.nodecount = len(archivelist)
        self.acct = {"end_time": 12312, "id": 1, "uid": "sdf", "user": "werqw"}
        self.nodes = ["node" + str(i) for i in xrange(len(archivelist))]
        self._data = {}

        archive_starts = []
        archive_ends = []
        for archive in archivelist:
            context = pmapi.pmContext(c_pmapi.PM_CONTEXT_ARCHIVE, archive)
            mdata = context.pmGetArchiveLabel()
            archive_starts.append(datetime.datetime.utcfromtimestamp(math.floor(mdata.start)))
            archive_ends.append(datetime.datetime.utcfromtimestamp(math.ceil(context.pmGetArchiveEnd())))

        self.start_datetime = min(archive_starts)
        self.end_datetime = max(archive_ends)
pcparchive.py 文件源码 项目:supremm 作者: ubccr 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def adjust_job_start_end(job):
    """ Set the job node start and end times based on the presence of the special
     job-X-begin and job-X-end archives. Do nothing if these archives are absent
    """

    startarchive = "job-{0}-begin".format(job.job_id)
    endarchive = "job-{0}-end".format(job.job_id)

    for nodename, filepaths in job.rawarchives():
        begin = None
        end = None
        for fname in filepaths:
            filename = os.path.basename(fname)
            if filename.startswith(startarchive):
                context = pmapi.pmContext(c_pmapi.PM_CONTEXT_ARCHIVE, fname)
                mdata = context.pmGetArchiveLabel()
                begin = datetime.datetime.utcfromtimestamp(math.floor(mdata.start))

            if filename.startswith(endarchive):
                context = pmapi.pmContext(c_pmapi.PM_CONTEXT_ARCHIVE, fname)
                end = datetime.datetime.utcfromtimestamp(math.ceil(context.pmGetArchiveEnd()))

        job.setnodebeginend(nodename, begin, end)
util.py 文件源码 项目:TFCommon 作者: MU94W 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, data, batch_size, big_batch=10):
        self.data_inp       = [item + [_EOS_ID] for item in data['input']]
        self.data_spc       = data['speaker_code']
        self.data_out       = data['output']
        self.samples        = len(self.data_inp)
        self.batch_size     = batch_size
        self.big_batch      = big_batch
        self.big_batch_step = 0
        if batch_size == 'all':
            self.batch_size = self.samples
            self.big_batch = 1
        if self.samples < self.big_batch * self.batch_size:
            self.max_batch_step = ceil(self.samples / (self.big_batch * self.batch_size))
        else:
            self.max_batch_step = floor(self.samples / (self.big_batch * self.batch_size)) - 1
        self.run_through    = 0
        self.perm           = None
        self.perm_index     = np.arange(min(self.big_batch * self.batch_size, self.samples))
        self.batch          = None
tilegrids.py 文件源码 项目:lib-gatilegrid 作者: geoadmin 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def tileAddress(self, zoom, point):
        "Returns a tile address based on a zoom level and \
        a point in the tile"
        [x, y] = point
        assert x <= self.extent[2] and x >= self.extent[0]
        assert y <= self.extent[3] and y >= self.extent[1]
        assert zoom in range(0, len(self.RESOLUTIONS))

        tileS = self.tileSize(zoom)
        offsetX = abs(x - self.MINX)
        if self.originCorner == 'bottom-left':
            offsetY = abs(y - self.MINY)
        elif self.originCorner == 'top-left':
            offsetY = abs(self.MAXY - y)
        col = offsetX / tileS
        row = offsetY / tileS
        # We are exactly on the edge of a tile and the extent
        if x in (self.MINX, self.MAXX) and col.is_integer():
            col = max(0, col - 1)
        if y in (self.MINY, self.MAXY) and row.is_integer():
            row = max(0, row - 1)
        return [
            int(math.floor(col)),
            int(math.floor(row))
        ]
resnext.py 文件源码 项目:ResNeXt-DenseNet 作者: D-X-Y 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self, inplanes, planes, cardinality, base_width, stride=1, downsample=None):
    super(ResNeXtBottleneck, self).__init__()

    D = int(math.floor(planes * (base_width/64.0)))
    C = cardinality

    self.conv_reduce = nn.Conv2d(inplanes, D*C, kernel_size=1, stride=1, padding=0, bias=False)
    self.bn_reduce = nn.BatchNorm2d(D*C)

    self.conv_conv = nn.Conv2d(D*C, D*C, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False)
    self.bn = nn.BatchNorm2d(D*C)

    self.conv_expand = nn.Conv2d(D*C, planes*4, kernel_size=1, stride=1, padding=0, bias=False)
    self.bn_expand = nn.BatchNorm2d(planes*4)

    self.downsample = downsample
Networks.py 文件源码 项目:MLPractices 作者: carefree0910 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def predict(self, x):
        x = NNDist._transfer_x(np.asarray(x))
        rs = []
        batch_size = floor(1e6 / np.prod(x.shape[1:]))
        epoch = int(ceil(len(x) / batch_size))
        output = self._sess.graph.get_tensor_by_name(self._output)
        bar = ProgressBar(max_value=epoch, name="Predict")
        bar.start()
        for i in range(epoch):
            if i == epoch - 1:
                rs.append(self._sess.run(output, {
                    self._entry: x[i * batch_size:]
                }))
            else:
                rs.append(self._sess.run(output, {
                    self._entry: x[i * batch_size:(i + 1) * batch_size]
                }))
            bar.update()
        return np.vstack(rs).astype(np.float32)
jholiday.py 文件源码 项目:Qkou_kit 作者: pddg 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _vernal_equinox(y):
    """???????????????????3???????????
"""
    if y <= 1947:
        d = 0
    elif y <= 1979:
        d = math.floor(
            20.8357 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2099:
        d = math.floor(
            20.8431 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2150:
        d = math.floor(
            21.8510 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    else:
        d = 99

    return d
jholiday.py 文件源码 项目:Qkou_kit 作者: pddg 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _autumn_equinox(y):
    """???????????????????9???????????
"""
    if y <= 1947:
        d = 0
    elif y <= 1979:
        d = math.floor(
            23.2588 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2099:
        d = math.floor(
            23.2488 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    elif y <= 2150:
        d = math.floor(
            24.2488 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
    else:
        d = 99

    return d
util.py 文件源码 项目:workflows.kyoyue 作者: wizyoung 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def mask_func(pattern):
    """
    Return the mask function for the given mask pattern.
    """
    if pattern == 0:   # 000
        return lambda i, j: (i + j) % 2 == 0
    if pattern == 1:   # 001
        return lambda i, j: i % 2 == 0
    if pattern == 2:   # 010
        return lambda i, j: j % 3 == 0
    if pattern == 3:   # 011
        return lambda i, j: (i + j) % 3 == 0
    if pattern == 4:   # 100
        return lambda i, j: (math.floor(i / 2) + math.floor(j / 3)) % 2 == 0
    if pattern == 5:  # 101
        return lambda i, j: (i * j) % 2 + (i * j) % 3 == 0
    if pattern == 6:  # 110
        return lambda i, j: ((i * j) % 2 + (i * j) % 3) % 2 == 0
    if pattern == 7:  # 111
        return lambda i, j: ((i * j) % 3 + (i + j) % 2) % 2 == 0
    raise TypeError("Bad mask pattern: " + pattern)  # pragma: no cover
Adafruit_PWM_Servo_Driver.py 文件源码 项目:Solo-Mapper 作者: Escadrone 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def setPWMFreq(self, freq):
    "Sets the PWM frequency"
    prescaleval = 25000000.0    # 25MHz
    prescaleval /= 4096.0       # 12-bit
    prescaleval /= float(freq)
    prescaleval -= 1.0
    if (self.debug):
      print "Setting PWM frequency to %d Hz" % freq      
      print "Estimated pre-scale: %d" % prescaleval      
    prescale = math.floor(prescaleval + 0.5)
    if (self.debug):
      print "Final pre-scale: %d" % prescale      

    oldmode = self.i2c.readU8(self.__MODE1);
    newmode = (oldmode & 0x7F) | 0x10             # sleep
    self.i2c.write8(self.__MODE1, newmode)        # go to sleep
    self.i2c.write8(self.__PRESCALE, int(math.floor(prescale)))
    self.i2c.write8(self.__MODE1, oldmode)
    time.sleep(0.005)
    self.i2c.write8(self.__MODE1, oldmode | 0x80)
SpatialFractionalMaxPooling.py 文件源码 项目:pytorch-dist 作者: apaszke 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _getOutputSizes(self, input):
        outW = self.outW
        outH = self.outH
        if self.ratioW != None and self.ratioH != None:
            assert input.ndimension() == 4
            outW = int(math.floor(input.size(3) * self.ratioW))
            outH = int(math.floor(input.size(2) * self.ratioH))

            # Neither can be smaller than 1
            assert outW > 0
            assert outH > 0
        else:
            assert outW != None and outH != None

        return outW, outH

    # Call this to turn off regeneration of random pooling regions each
    # updateOutput call.


问题


面经


文章

微信
公众号

扫码关注公众号