コード例 #1
0
    def train_generator(self, x_gen, epochs, batch_size, steps_per_epoch,
                        sav_dir):
        time = Time()
        time.start()
        print(
            'LSTM network training starts, with %s epochs, %s batchsize and %s batched per epoch'
            % (epochs, batch_size, steps_per_epoch))
        sav_filename = os.path.join(
            sav_dir, '%s-e%s.h5' %
            (dt.datetime.now().strftime('%d%m%Y-%H%M%S'), str(epochs)))

        callbacks = [
            ModelCheckpoint(filepath=sav_filename,
                            monitor='loss',
                            save_best_only=True)
        ]

        self.lstm_nn.fit(x_gen,
                         steps_per_epoch=steps_per_epoch,
                         epochs=epochs,
                         callbacks=callbacks,
                         workers=1)

        print('LSTM network training completed. Model saved as %s' %
              sav_filename)
        time.stop()
コード例 #2
0
    def build_nn(self, configs):
        time = Time()
        time.start()

        for layer in configs['model']['layers']:
            neurons = layer['neurons'] if 'neurons' in layer else None
            dropout_rate = layer['rate'] if 'rate' in layer else None
            activation = layer['activation'] if 'activation' in layer else None
            return_seq = layer['return_seq'] if 'return_seq' in layer else None
            input_timesteps = layers[
                'input_timesteps'] if 'input_timesteps' in layer else None
            input_dim = layers['input_dim'] if 'input_dim' in layer else None

            if layer['type'] == 'dense':
                self.lstm_nn.add(Dense(neurons, activation=activation))

            if layer['type'] == 'lstm':
                self.lstm_nn.add(
                    LSTM(neurons,
                         input_shape=(input_timesteps, input_dim),
                         return_sequences=return_seq))
            if layer['type'] == 'dropout':
                self.lstm_nn.add(Dropout(neurons, dropout_rate=dropout_rate))

        self.lstm_nn.compile(loss=configs['model']['loss'],
                             optimizer=configs['model']['optimiser'])

        print('LSTM neural network finished compiling')
        time.stop()
コード例 #3
0
ファイル: test_timer.py プロジェクト: equilet/sms2popmail
def main():
    result = 1
    print 'starting time: ' , time.ctime()

    result = raw_input('press g to start timer, s to stop.\n')
    while(result is 'g'):
	print_something(True)
	result = ''

    result = None
    time.stop()
コード例 #4
0
ファイル: TheOgrelordCometh.py プロジェクト: MSPigl/CSIS-110
def theOgreLordCometh():
    theShrekoning = makePicture(getMediaPath("The Ogrelord.gif"))
    for p in getPixels(theShrekoning):
        setRed(p, 125)
        if getRed(p) < 200:
            setGreen(p, 255)
    show(theShrekoning)

    time.stop(3)

    dogFort = makePicture(pickAFile())
    show(dogFort)
コード例 #5
0
    def train(self, x, y, epochs, batch_size, sav_dir):
        time = Time()
        time.start()
        print('LSTM network training starts, with %s epochs and batchsize %s' % (epochs, batch_size))
        sav_filename = os.path.join(sav_dir, '%s-e%s.h5' % (dt.datetime.now().strftime('%d%m%Y-%H%M%S'), str(epochs)))

        callbacks = [
            EarlyStopping(monitor='val_loss', patience=2),
            ModelCheckpoint(filepath=sav_filename, monitor='val_loss', save_best_only=True)
        ]
        self.lstm_nn.fit(x, y, epochs=epochs, batch_size=batch_size, callbacks=callbacks)
        self.lstm_nn.save(sav_filename)
        print('LSTM network training completed. Model saved as %s' %sav_filename)
        time.stop()
コード例 #6
0
def function2(message):

    if (message.text.lower()).find("событие без текста") != -1:
        bot.delete_message(message.chat.id, message.message_id)
    elif (message.text).find("https://") != -1:

        text = (message.text)
        text = text.replace('\t', " ")
        text = text.replace('\n', " ")
        list = text.split(" ")

        for i in list:
            #print(list)
            if i.find("https://") != -1 and i.find("Автор:https://") == -1:
                if i not in links:
                    links.append(i)
                else:
                    bot.delete_message(message.chat.id, message.message_id)

    time.stop(30)
コード例 #7
0
def run_solver(solver_binary_path,
               instance_id,
               instance_path,
               arguments,
               timeout=20):
    logging.info(
        f"Running {solver_binary_path} on instance {instance_path}: {arguments}, timeout={timeout}"
    )
    result_obj = {
        'instance_id': instance_id,
        'node_name': config.SMTLAB_NODE_NAME
    }
    time = Timer()

    timeout_ms = int(timeout * 1000.0)

    try:
        argument_array = json.loads(arguments)
        out = subprocess.check_output([solver_binary_path] + argument_array +
                                      [instance_path],
                                      timeout=timeout).decode('UTF-8').strip()
    except subprocess.TimeoutExpired:
        time.stop()
        result_obj['result'] = "timeout"
        result_obj['stdout'] = ""
        result_obj['runtime'] = timeout_ms
        logging.info(f"timeout, result is {result_obj}")
        return result_obj
    except subprocess.CalledProcessError as e:
        time.stop()
        result_obj['result'] = "error"
        result_obj['stdout'] = f"stdout: {e.stdout} stderr: {e.stderr}"
        result_obj['runtime'] = time.getTime_ms()
        logging.info(f"process exited with an error, result is {result_obj}")
        return result_obj

    time.stop()

    result_obj['stdout'] = out
    result_obj['runtime'] = time.getTime_ms()

    if "unsat" in out:
        result_obj['result'] = "unsat"
    elif "sat" in out:
        result_obj['result'] = "sat"
    elif time.getTime() >= timeout:
        # sometimes python's subprocess does not terminate eagerly
        result_obj['result'] = "timeout"
        result_obj['runtime'] = timeout_ms
    elif "unknown" in out:
        result_obj['result'] = "unknown"
    else:
        result_obj['result'] = "error"

    logging.info(f"result is {result_obj}")
    return result_obj
コード例 #8
0
    servoPos = 90

    def __init__(self):
        print "I'm a little robot car. Beep Beep."

    #named after the GoPiGo version of stop()
    def stop(self):
        self.isMoving = False
        while stop() !=1:
            time.sleep(.1)
            print "Whoops,sorry boss. Can't stop."


    def fwd(self):
        self.isMoving = True
        while fwd() != 1:
            time.sleep(.1)
            print "Can't do the vroom vroom."

    #####
    ##### COMPLEX METHODS
    #####

    #####
    ##### MAIN APP STARTS HERE
    #####
tina = Pigo()
tina.fwd()
time.sleep(2)
time.stop()
コード例 #9
0
    bot1prevchoice, bot1choice = bot1(0,0,"Tied!") #inital assuming previous choice was rock and current choice is rock
    bot2prevchoice, bot2choice = bot2(0,0,"Tied!") #inital assuming previous choice was rock and current choice is rock (result would be tied in that case)
    results = checkWin(bot1choice,bot2choice)
    if (results == "Win!"):
      results2 = "Lose!"
    elif (results == "Lose!"):
      results2 = "Win!"
    else:
      results2 = "Tied!"

 start = time.start()
	
    fight(100000)

 stop = time.stop()
 print(stop - start)

def fight(rounds):
    global bot1prevchoice
    global bot1choice
    global bot2prevchoice
    global bot2choice
    global results
    global results2
    global bot1score
    global bot2score
    choose = ["Rock","Paper","Scissors"]
    for i in range(0,rounds):
        bot1prevchoice, bot1choice = bot1(bot2prevchoice,bot2choice,results2)
        #print ("Bot 1 chose %s" % choose[bot1choice])
コード例 #10
0
    def main_loop(self):
        def process_keys():
            nonlocal rawimage, raw_demo, blacklevel, lut, output
            while True:
                key = self.window.get_key()
                if key is None:
                    break
                cey = chr(key)
                incdec = lambda d: d if cey < "_" else -d
                if cey == "o":
                    self.draw_overlay = not self.draw_overlay
                elif cey == "h":
                    self.draw_hist = not self.draw_hist
                elif cey == "+":
                    self.downsample = max(1, self.downsample // 2)
                elif cey == "-":
                    self.downsample = min(32, self.downsample * 2)
                elif cey in "gG":
                    self.gamma += incdec(0.05)
                    lut = None
                elif cey in "rR":
                    self.gain_r += incdec(0.05)
                    lut = None
                elif cey in "bB":
                    self.gain_b += incdec(0.05)
                    lut = None
                elif cey == "m":
                    self.ccm_matrix = not self.ccm_matrix
                    lut = None
                elif cey in "iI":
                    self.temperature = min(
                        10000, max(2000, self.temperature + incdec(250)))
                    lut = None
                elif cey in "sS":
                    self.saturation = min(
                        1.0, max(0.0, self.saturation + incdec(0.05)))
                    lut = None
                elif cey in "lL":
                    self.brightness += incdec(0.05)
                    lut = None
                elif cey in "kK":
                    self.contrast += incdec(0.05)
                    lut = None
                elif cey in "tT":
                    self.shutter *= 2**incdec(0.5)
                elif cey == "w":
                    print("Setting White Balance")
                    area = self.window.select_roi()
                    if area is not None:
                        region = region_reparent(area, self.crop_region)
                        region[2] = max(region[2], region[0] + 1)
                        region[3] = max(region[3], region[1] + 1)
                        roi = extract_region(raw_demo, region)
                        avgcol = np.mean(roi, axis=(0, 1)) - blacklevel
                        print("average color = ", avgcol)
                        g = avgcol[1]
                        b = avgcol[0].mean() / g
                        r = avgcol[2].mean() / g
                        self.gain_b = 1 / b
                        self.gain_r = 1 / r
                        lut = None
                        print(
                            f"ratios: {r:.3f}r/g {b:.3f}b/g -> gain_r={self.gain_r:.3f} gain_b={self.gain_b:.3f}"
                        )
                elif cey == "c":
                    print("Setting Crop Region")
                    area = self.window.select_roi(from_center=False)
                    if area is not None:
                        self.crop_region = region_reparent(
                            area, self.crop_region)
                elif cey == "C":
                    print("Cleared Crop Region")
                    self.crop_region = None
                elif cey == "P":
                    f = f"{int(time.time())}-bayer.raw"
                    print("Raw snapshot: ", f)
                    np.save(f, rawimage)
                elif cey == "p":
                    f = f"{int(time.time())}-dev.png"
                    print("Exposed snapshot: ", f)
                    cv2.imwrite(f, output)
                elif key == CVWindow.VK_Escape:
                    return False
            return True

        lut = None
        self.camera_set()
        frametime = 0.05
        time = Stopwatch()
        time.start()
        for buffer in self.capture.raw_captures():
            rawimage = buffer.array
            print("Bayer Frame: %s = %.1f MB (%s)" % (str(
                rawimage.shape), rawimage.nbytes / 1e6, str(rawimage.dtype)))
            print(str(buffer.get_header()))
            self.window.key_loop()

            # process image
            raw_demo = buffer.demosaic()
            if self.downsample > 1:
                raw_demo = cv2.resize(raw_demo,
                                      (raw_demo.shape[1] // self.downsample,
                                       raw_demo.shape[0] // self.downsample),
                                      interpolation=cv2.INTER_AREA)
            bl_y = int(raw_demo.shape[0] * 0.01 + 1)
            bl_x = int(raw_demo.shape[1] * 0.01 + 1)
            blacklevel = calc_black_level(raw_demo, bl_x, bl_y, bl_x, bl_y)
            print(f"Black Level = {blacklevel:.1f}")
            self.window.key_loop()

            if self.crop_region:
                raw_demo = extract_region(raw_demo, self.crop_region)

            if not lut:
                lut = ExposureLut(blacklevel,
                                  2**12 - 1,
                                  np.uint8,
                                  gamma=self.gamma,
                                  gain_b=self.gain_b,
                                  gain_r=self.gain_r,
                                  ccm=self.capture.get_ccm(self.temperature)
                                  if self.ccm_matrix else None,
                                  saturation=self.saturation,
                                  brightess=self.brightness,
                                  contrast=self.contrast)
            white_balanced = lut.apply(raw_demo)

            self.window.key_loop()

            output = white_balanced

            def do_overlay(over_img):
                if self.draw_hist:
                    m = np.where(
                        raw_demo.max(axis=-1) > blacklevel * 1.01, 255,
                        0).astype(np.uint8)
                    hist = histogram_calc(output, mask=m)
                    histogram_draw(over_img, hist)

                text = "\n".join([
                    f"ds = {self.downsample} ft={1000*frametime:.1f}ms",
                    f"gamma = {self.gamma:.2f}",
                    f"gain_r = {self.gain_r:.3f} gain_b = {self.gain_b:.3f} ccm = {self.ccm_matrix} temp = {self.temperature}K sat = {self.saturation:.2f}",
                    f"shutter = {self.shutter:.0f}ms (1/{1000 / self.shutter:.0f})",
                    f"bright = {self.brightness:.3f} contrast = {self.contrast:.3f}",
                ])
                display_shadow_text(over_img, 20, 25, text)

            scale = max(output.shape[0] / 800, output.shape[1] / 1600)
            self.window.display_image(
                output,
                reduction=scale,
                overlay_fn=do_overlay if self.draw_overlay else None)
            print("displayed")

            self.window.key_loop()
            if not process_keys():
                break

            frametime = frametime * 0.5 + time.stop() * 0.5
            time.start()

            self.camera_set()

            print("next -------")
        self.window.destroy_window()
コード例 #11
0
def chuck_norris():
    print(
        "Your traveling through the forest, birds are chirping the wagon rumbles along with its familiar creaks and rattles."
    )
    time.sleep(7)
    print(
        "Eventually, you come to an intersection, the road your on currently is called 'Peace Maker Trail'."
    )
    print(
        "It crosses a gravel path that looks almost brand new, you look down at the map, cross the road and keep going."
    )
    time.sleep(7)
    print(
        "suddenly, you look back at the sign startled by what was read on the map, the street you crossed was called..."
    )
    time.sleep(8)
    print("'Chuck Norris.' Nobody crosses Chuck Norris and lives!")
    time.sleep(7)
    print(
        "Suddenly, Chuck Norris appears infront of the wagon just 20 yards away, glaring at you."
    )
    print("Time is short, your choice right now will determine life or death!")
    time.sleep(7)
    print("Decision 1, you fight Chuck Norris!")
    time.sleep(5)
    print("Decision 2, you negotiate with Chuck Norris!")
    time.sleep(5)
    print("Decision 3, you run away from Chuck Norris!")
    time.sleep(5)
    user = input("What is your choice? '1', '2', '3'")
    if user == "1":
        print(
            "Quickly, you reach for a weapon, which one do you choose? 'Spear' or 'Rifle'"
        )
        time.sleep(3)
        user2 = input("Choose a weapon.").lower()
        if user2.startswith("s"):
            if spear > 0:
                print(
                    "You reach for the spear, chuck is closing in at a calm walk."
                )
                time.sleep(3)
                print(
                    "The spear is thrown, and splinters in mid air from a single roundhouse kick."
                )
                time.sleep(4)
                print(
                    "The sheer force of the kick flips your wagon, your journey is at an end."
                )
            else:
                print("You reach for a spear, yet do not have one.")
                print("Chuck's boot is the last thing you see.")
                time.sleep(4)
        elif user2.startswith("r"):
            if rifle > 0:
                print("You hesitate for a moment, then dive for the rifle.")
                time.sleep(5)
                print(
                    "You take careful aim and fire! But Chuck Norris walks through the smoke unharmed."
                )
                time.sleep(3)
                print("Chuck says, 'if I were a bullet I'd go around too.' ")
                print("You do not survive his attack.")
            else:
                print("You dive for a rifle, but it isn't there...")
                time.sleep(4)
                print(
                    "But Chuck was faster anyways, his mac 10 did all necissary talking."
                )
    elif user == "2":
        print(
            "You think quickly, and say, 'Lets just talk this through.' Chuck just nods and says, 'Its your lucky day.'"
        )
        time.sleep(6)
        print(
            "You try to think of everything, but one question naggs you, are his accolades fact or fiction?"
        )
        user3 = input(
            "Is there anything you can think of that's fictional about Chuck Norris? 'fact'or 'fiction'"
        ).lower()
        if user3 == "fact":
            print(
                "Correct, there are only 'facts' when talking about Chuck Norris."
            )
        else:
            print(
                "Wrong, there are only facts' when talking about Chuck Norris."
            )

        print("Chuck says, 'How many push ups can I do at one time?'")
        user4 = input("Your Answer..." 'No punctuation!').lower()
        if user4 == "all of them":
            print("Correct!")
        else:
            print(
                "Chuck narrows his eyes, and says, I can do 'all of them' ANS: 'all of them'"
            )
            print("Chuck's mac 10 did the rest of the talking that day.")
        print("Chuck says, 'What item do I use in order to donate blood?'")
        user5 = input("You speak nervously and say: ").lower()
        if user5 == "a hand gun":
            print(
                "Correct, All I bring is a hand gun and a bucket to donate blood."
            )
        else:
            print(
                "Chuck simply glares at you and says, 'I use a hand gun.' ANS: 'a hand gun'"
            )
        print("Next question")
        time.sleep(4)
        print(
            "Chuck says, 'I'll let you go if you can answer this question and the one after it, \n How many times have I counted to infinity?'"
        )
        user6 = input("Your answer: (Type a number)")
        if user6 == "2":
            print("Yea, I've counted to infinity twice.")
        else:
            print(
                "'Wrong, I've counted to infinity twice!' Chucks's boot is the last thing you see."
            )
        print("Final Question!")
        print("Chuck says, 'What time of year do I go out hunting?'")
        user7 = input("Your Answer: ").lower()
        if user7.startswith("n"):
            print("'Correct, saying I hunt implies a chance of failure.'")
        else:
            print("'Wrong, saying I hunt implies a chance of failure.'")
    elif user == "3":
        print("Nobody runs from Chuck Norris and gets away with it.")
        time.stop(6)
コード例 #12
0
e = 37
f = 40
g = 38
seg = [a, b, c, d, e, f, g]

power.setmode(power.BOARD)
power.setwarnings(False)
power.setup(a, power.OUT)
power.setup(b, power.OUT)
power.setup(c, power.OUT)
power.setup(d, power.OUT)
power.setup(e, power.OUT)
power.setup(f, power.OUT)
power.setup(g, power.OUT)

zero = [1, 1, 1, 1, 1, 1, 0]
one = [0, 1, 1, 0, 0, 0, 0]
two = [1, 1, 0, 1, 0, 0, 1]
three = [1, 1, 1, 1, 0, 0, 1]
four = [0, 1, 1, 0, 0, 1, 1]
five = [1, 0, 1, 1, 0, 1, 1]
six = [1, 0, 1, 1, 1, 1, 1]
seven = [1, 1, 1, 0, 0, 0, 0]
eight = [1, 1, 1, 1, 1, 1, 1]

num = [zero, one, two, three, four, five, six, seven, eight]
while True:
    for x in range(0, len(num), 1):
        power.output(seg, num[x])
        stop(2)