Ejemplo n.º 1
0
def main():
    global mode
    print("running main()")
    # play_startup()
    while True:
        distance = ping()
        print('Distance:', distance)
        
        # standby mode
        if mode == 0:
            stop()
            # signal to start driving
            if distance < TURN_DISTANCE:
                mode = 1
                forward()
                sleep(1)
        # drive mode
        else:
            if distance < TURN_DISTANCE:
                play_turn()
                # back up for a bit
                reverse()
                sleep(REVERSE_TIME)
                # half right and half left turns
                if urandom.random() < .5:
                    turn_right()
                else:
                    turn_left()
                sleep(TURN_TIME)
                forward()
            else:
                print('forward')
                forward()
            led_show_dist(distance)
Ejemplo n.º 2
0
def makeMultipartBody(params):

    print("makeMultipartBody")
    mylib.collectMemory()
    #print(mylib.reportMemory())  # for debug
    uniq_str = sha1Hash(str(utime.time() * random()))
    bodyTMPfile = '/sd/' + 'tmp' + uniq_str[5:
                                            10]  # make tmp file name (len:3+5)
    boundary = uniq_str[0:16]  # take string (len:16)
    fp = open(bodyTMPfile, 'wb')
    for key in params:
        fp.write(('--' + boundary).encode())
        fp.write(CRLF)
        value = params[key]

        if key == 'file':
            if len(value) == 1:
                file_name = value[0]
                file_body = None
            if len(value) == 2:
                (file_name, file_body) = value
            else:
                print("Error in makeMultipartBody")
                print("file entity illegal")
                fp.close()
                return None

            fp.write(TMPL_CD_FILE.format(file_name).encode())
            fp.write(CRLF)
            fp.write(TMPL_CT_JPEG)
            fp.write(CRLF * 2)
            if file_body is None:
                with open(file_name, "rb") as fp_body:
                    buffer = bytearray(FILEBUFSIZE)
                    while True:
                        if DBG_MEMORY_REPORT:
                            print(mylib.reportMemory())  # for debug
                        size = fp_body.readinto(buffer, FILEBUFSIZE)
                        if size == 0:
                            break
                        else:
                            fp.write(buffer, FILEBUFSIZE)
                    buffer = None
        else:
            fp.write(TMPL_CD.format(key).encode())
            fp.write(CRLF * 2)
            if isinstance(value, str):
                fp.write(value.encode())
            else:
                print("Error in makeMultipartBody")
                print("entity is not string")
                fp.close()
                return None

        fp.write(CRLF)

    fp.write(('--' + boundary + '--').encode())
    fp.close()
    return (boundary, bodyTMPfile)
def adhan(sidx):
    global _stopadhan
    _stopadhan = False
    wbutton.irq(irq_stop_adhan, Pin.IRQ_FALLING,
                machine.SLEEP | machine.DEEPSLEEP)
    print('Adhan %s' % SALATS[sidx])
    led.value(1)

    if sidx == 1:  #chorok : beep only
        player.volume(30)
        player.say_salat_name(1)
        return

    urandom.seed(time.mktime(localtime()))
    # RNG needs some heetup to get a good enough quality
    for k in range(1, 10):
        urandom.random()

    player.wakeup()
    player.volume(sdb.getsvolume(sidx))

    if sidx == 0:  #Fajr special ringing
        for i in range(1, 17):
            led.value(1)
            time.sleep_ms(100)
            led.value(0)
            if _stopadhan: return
            time.sleep_ms(300 if i % 4 == 0 else 50)
        led.value(1)
        player.play_adhan(FAJR_ADHAN_FOLDER)

    else:
        for i in range(0, sidx):
            led.value(1)
            time.sleep_ms(100)
            led.value(0)
            if _stopadhan: return
            time.sleep_ms(500)
        led.value(1)
        _, _, _, h, mi, _, _, _ = localtime()
        player.say_current_time(h, mi)
        time.sleep_ms(500)
        player.play_adhan(ALL_ADHAN_FOLDER)
Ejemplo n.º 4
0
 def _get_action(self, state, episode):
     eps = 0.9 * (1 / episode * 0.001 + 1)
     if eps < random():
         # suit act
         next_action = self._mlp.QLearningPredictBestActionIndex(state)
         if next_action is None:
             next_action = choice([0, 1, 2])
     else:
         next_action = choice([0, 1, 2])
     return next_action
def main():
    global counter, dist, current_dist
    current_mode = mode
    current_mode_function = mode_function
    current_function_value = function_value
    print('in main')
    while True:
        dist = ping()
        if dist != current_dist and dist < MAX_DIST and mode != 2:
            print("Distance:", dist, " cm")
            current_dist = dist
        update_display()
        
        # run mode
        if mode == 1:
            if dist < TURN_DIST:
                play_reverse()
                reverse()
                sleep(REVERSE_TIME)
                # half right and half left turns
                if urandom.random() < .5:
                    turn_right()
                    play_turn_right()
                else:
                    turn_left()
                    play_turn_left()
                sleep(TURN_TIME)
                forward()
            else:
                print('forward')
                forward()

        # program mode
        if mode == 2:
            stop()
        
        # only print on change
        if current_mode != mode:
            print('mode:', mode)
            current_mode = mode
        if current_mode_function != mode_function:
            print('mode function:', mode_function)
            current_mode_function = mode_function
        sleep(0.2)
        counter += 1
Ejemplo n.º 6
0
def power_iteration(A, iterations):
    """
    Iterative algo. to find the eigenvector of a matrix A corresponding to the largest
    eigenvalue.

    TODO: Establish some measure or heuristic of min number of iterations required
    """
    # choose random initial vector to reduce risk of choosing one orthogonal to
    # target eigen vector
    b_k = np.array([urandom.random() for i in range(len(A))])

    for _ in range(iterations):
        b_k1 = np.dot(A, b_k)
        b_k1_norm = np.linalg.norm(b_k1)
        # re normalize the vector
        b_k = b_k1 / b_k1_norm

    return b_k1_norm, b_k
Ejemplo n.º 7
0
def main():
    global valid_distance
    print("running main()")
    
    play_startup()
    
    while True:
        if mode == 0:
            stop()
            run_lights()
        else:
            distance = ping()
            print('Distance:', distance)
            if distance > MAX_DISTANCE:
                # only print if we used to have a valid distance
                if valid_distance == 1:
                    print('no signal')      
                valid_distance = 0
            else:
                print(distance)
                if distance < TURN_DISTANCE:
                    play_turn()
                    # back up for a bit
                    reverse()
                    utime.sleep(REVERSE_TIME)
                    # half right and half left turns
                    if urandom.random() < .5:
                        turn_right()
                    else:
                        turn_left()
                    utime.sleep(TURN_TIME)
                    forward()
                else:
                    print('forward')
                    forward()
                valid_distance = 1
                led_show_dist(distance)
            utime.sleep(0.05)
Ejemplo n.º 8
0
    utime.sleep(5)
    checknet.poweron_print_once()
    '''
    如果用户程序包含网络相关代码,必须执行 wait_network_connected() 等待网络就绪(拨号成功);
    如果是网络无关代码,可以屏蔽 wait_network_connected()
    【本例程可以屏蔽下面这一行!】
    '''
    # checknet.wait_network_connected()

    # urandom.randint(start, end)
    # 随机1 ~ 4之间
    num = random.randint(1, 4)
    random_log.info(num)

    # random between 0~1
    num = random.random()
    random_log.info(num)

    # urandom.unifrom(start, end)
    # 在开始和结束之间生成浮点数
    num = random.uniform(2, 4)
    random_log.info(num)

    # urandom.randrange(start, end, step)
    # 2-bit binary,the range is [00~11] (0~3)
    num = random.getrandbits(2)
    random_log.info(num)

    # 8-bit binary,the range is [0000 0000~1111 11111] (0~255)
    num = random.getrandbits(8)
    random_log.info(num)
Ejemplo n.º 9
0
    assert 0 <= random.randint(0, 4) <= 4
    assert 2 <= random.randint(2, 6) <= 6
    assert -2 <= random.randint(-2, 2) <= 2

# empty range
try:
    random.randint(2, 1)
except ValueError:
    print('ValueError')

print('choice')
lst = [1, 2, 5, 6]
for i in range(50):
    assert random.choice(lst) in lst

# empty sequence
try:
    random.choice([])
except IndexError:
    print('IndexError')

print('random')
for i in range(50):
    assert 0 <= random.random() < 1

print('uniform')
for i in range(50):
    assert 0 <= random.uniform(0, 4) <= 4
    assert 2 <= random.uniform(2, 6) <= 6
    assert -2 <= random.uniform(-2, 2) <= 2
Ejemplo n.º 10
0
    return array('f', [math.exp(xi) for xi in x])


@micropython.asm_thumb
def f2i(r0):
    vldr(s0, [r0, 0])
    vmov(r0, s0)


@micropython.asm_thumb
def i2f(r0, r1):
    vmov(s0, r0)
    vstr(s0, [r1, 0])


x = array('f', [(float(i) + random() - 0.5) for i in range(-30, 31)])
y = array('f', [0.0] * len(x))

n = float_array_exp(y, len(y), x)

cum_error = 0.0
for xi, yi in zip(x, y):
    yi_m = math.exp(xi)
    e = abs(yi - yi_m)
    data = xi, yi, yi_m, e, e / yi_m
    print(data)
    cum_error += e / yi_m

print("\nAverage % error compared to math.exp:"
      " {}".format(cum_error * 100 / len(x)))
Ejemplo n.º 11
0
    def func():
        # dummy memory assignment
        import urandom

        x = [urandom.random() for i in range(100)]
        return
Ejemplo n.º 12
0
def random(a, b):
    result = urandom.random() / 256
    result *= b - a
    result += a
    return int(result)
Ejemplo n.º 13
0
def main():
    global valid_distance
    print("running main()")

    play_startup()
    oled_count = 0  # repeat every
    oled_count_max = 0  # times through loop
    servo_count = 0
    servo_count_max = 0  # when to update
    servo_degrees = 0
    servo(servo_degrees)  # start in that pos

    # loop forever
    while True:
        if mode == 0:
            stop()
            run_lights()
        else:
            distance = ping()
            print('Distance:', distance)
            oled_count += 1
            if oled_count > oled_count_max:
                oled.fill(0)  # Black
                oled.text("Distance:", 5, 5)
                oled.text("{:f}".format(distance), 5, 15)
                oled.show()
                oled_count = 0

            servo_count += 1
            if servo_count > servo_count_max:
                if distance > MAX_DISTANCE:
                    servo_degrees = 0
                else:
                    servo_degrees = 180 - distance / MAX_DISTANCE * 180
                servo(servo_degrees)
                servo_count = 0

            if distance > MAX_DISTANCE:
                # only print if we used to have a valid distance
                if valid_distance == 1:
                    print('no signal')
                valid_distance = 0
            else:
                print(distance)
                #note=distance*10
                #playnote(note, .025)

                if distance < TURN_DISTANCE:
                    play_turn()
                    # back up for a bit
                    reverse()
                    utime.sleep(REVERSE_TIME)
                    # half right and half left turns
                    if urandom.random() < .5:
                        turn_right()
                    else:
                        turn_left()
                    utime.sleep(TURN_TIME)
                    forward()
                else:
                    print('forward')
                    forward()
                valid_distance = 1
                led_show_dist(distance)
            utime.sleep(0.05)
Ejemplo n.º 14
0
def float_array_random(n, min=-1e6, max=1e6):
    return array('f', [random()*(max - min) + min for i in range(n)])
Ejemplo n.º 15
0
cum_error = 0.0
for i in exponents:
    float_array_pow_int(y, len(y), x, i)
    for yi, ymi in zip(y, math_float_array_pow_int(x, i)):
        if yi != ymi:
            cum_error += abs(yi - ymi)
    print(" {:3d}: {}".format(i, y))

print(cum_error)
print("\nCumulative absolute error compared to math.pow:"
      " {}".format(cum_error))

n = 1000
i0, i1 = -8, 9
x = array('f', [random() - 0.5 for i in range(n)])
y = array('f', [0]*n)
print("\nPerformance on array of length {} for i in range({}, {})"
      ":".format(n, i0, i1))

results = {}
for i in range(i0, i1):
    times = []
    for j in range(5):
        t = utime.ticks_us()
        r = float_array_pow_int(y, len(y), x, i)
        #r = math_float_array_pow_int(x, i)
        delta = utime.ticks_diff(utime.ticks_us(), t)
        times.append(delta/1000)
    avg_time = sum(times)/len(times)
    sum_value = sum(y)
Ejemplo n.º 16
0
 def RandomFloat():
     if 'rng' in globals():
         return rng() / (2**24)
     return random()