def upload_data(ui):
    caffeine.on(display=False)
    tmp_dir_name = ui.tmp_dir_name
    dataset_type = ui.current_dataset_type
    csv_file_name = ui.selected_csv[dataset_type]
    s3 = ui.session.resource('s3')
    s3_objects, status = list_objects_in_dataset_bucket(
        ui.session, ui.region, ui.s3_bucket_name, ui.dataset_group_name)
    if status == 'failure':
        caffeine.off()
        return status
    file_prefix = "/" + ui.dataset_group_name + "/datasets/" + dataset_type.lower(
    ) + '_'
    file_name = os.path.basename(csv_file_name)
    new_file_name = file_name
    ds_number = 0
    while file_prefix + new_file_name in s3_objects:
        ds_number += 1
        new_file_name = os.path.splitext(file_name)[0] + '_' + str(
            ds_number) + '.csv'

    status = multi_part_upload_with_s3(
        s3, ui.s3_bucket_name, ui.dataset_group_name + '/' + "datasets/" +
        dataset_type.lower() + '_' + new_file_name,
        os.path.join(tmp_dir_name, "tmp_dataset.csv"), ui.upload_progress_bar)
    if status != 'failure':
        ui.dataset_path[
            dataset_type] = ui.s3_bucket_path + file_prefix + new_file_name
    caffeine.off()
    return status
Example #2
0
 def run(self):
     caffeine.on(display=True)
     self.welcome()
     # self.trainer.introduce()
     self.print_info()
     for section in self.sections:
         untimed_rest()
         # self.trainer.say_phrase()
         section.run()
     caffeine.off()
Example #3
0
def do_parallel(fn, loop, n_jobs=-1, progress=True, keep_alive=True):
    if progress:
        loop = tqdm(loop)
    with joblib.Parallel(n_jobs=-1) as par:
        if keep_alive and can_caffeinate():
            caffeine.on(display=True)
            res = par(joblib.delayed(fn)(l) for l in loop)
            caffeine.off()
        else:
            res = par(joblib.delayed(fn)(l) for l in loop)
    return res
    def osx_standby(self, system=True, display=True):
        try:
            if system:
                caffeine.off()
            else:
                caffeine.on(display)

        except NameError:
            self.log_warning(_("Unable to change power state"), _("caffeine lib not found"))

        except Exception, e:
            self.log_warning(_("Unable to change power state"), e)
Example #5
0
    def osx_standby(self, system=True, display=True):
        try:
            if system:
                caffeine.off()
            else:
                caffeine.on(display)

        except NameError:
            self.log_warning(_("Unable to change power state"),
                             _("caffeine lib not found"))

        except Exception as e:
            self.log_warning(_("Unable to change power state"), e)
Example #6
0
                    (By.XPATH, "//a[.//span[text()='Washington']]"))).click()
        except:
            wait.until(
                EC.element_to_be_clickable(
                    (By.XPATH, "//a[.//span[text()='Washington']]"))).click()

        status = wait.until(
            EC.element_to_be_clickable((
                By.XPATH,
                "//span[@class='city' and contains(text(), \"seattle, WA\")]/parent::td/parent::tr//span[@class=\"status\"]"
            ))).text
        if (status == "Available"):
            print("available")
            message = client.messages.create(
                body="There is a CVS COVID vaccine available in Seattle",
                from_='+15868001122',
                to=config('MY_NUMBER'))
            chrome_driver.close()
            break
        else:
            print("not available")

            #don't try again for another 5 min
            time.sleep(300)


if __name__ == "__main__":
    caffeine.on(display=False)
    findVaccines()
    caffeine.off()
Example #7
0
def create_predictor_and_forecast(ui):
    try:
        # Using caffeine to prevent pc from sleeping.
        caffeine.on(display=False)

        forecast_export_name = forecast_name = predictor_name = ui.new_forecast_line_edit.text(
        )
        forecast_horizon = ui.predictor_forecast_horizon_spinbox.value()
        forecast_client = ui.forecast_client
        dataset_group_arn = ui.dataset_group_arn
        auto_ml = ui.auto_ml_checkbox.isChecked()

        # Check if a country is selected to use its holidays for forecasting.
        holidays = None
        if ui.country_checkbox.isChecked():
            holidays = selected_country(ui)

        # Check if location is a dimension in the data
        location_in_datasets, status = is_location_in_datasets(
            forecast_client, dataset_group_arn)
        if status == 'failure':
            caffeine.off()
            return status

        # Check if auto machine learning is selected
        algorithm = None
        if not auto_ml:
            algorithm = ui.algorithms[ui.algorithm_combobox.currentText()]
            print(algorithm)

        # Get frequency from combobox
        forecast_frequency = combobox_to_freq(ui, 'FORECAST')

        # Create a predictor
        predictor_arn, status = create_predictor(
            forecast_client, predictor_name, algorithm, auto_ml,
            forecast_horizon, forecast_frequency, dataset_group_arn,
            location_in_datasets, holidays)
        if status == 'failure':
            caffeine.off()
            return status

        # Wait until predictor is created
        response = forecast_client.describe_predictor(
            PredictorArn=predictor_arn)
        while response['Status'] != 'ACTIVE' and response[
                'Status'] != 'CREATE_FAILED':
            response = forecast_client.describe_predictor(
                PredictorArn=predictor_arn)
            time.sleep(10)
        if response['Status'] == 'CREATE_FAILED':
            caffeine.off()
            return 'failure'

        # Create a forecast
        forecast_arn, status = create_forecast(forecast_client, forecast_name,
                                               predictor_arn)
        if status == 'failure':
            caffeine.off()
            return status

        # Wait until forecast is created
        response = forecast_client.describe_forecast(ForecastArn=forecast_arn)
        while response['Status'] != 'ACTIVE' and response[
                'Status'] != 'CREATE_FAILED':
            response = forecast_client.describe_forecast(
                ForecastArn=forecast_arn)
            time.sleep(10)
        if response['Status'] == 'CREATE_FAILED':
            caffeine.off()
            return 'failure'
        s3_path = ui.s3_bucket_path + "/" + ui.dataset_group_name + "/forecast/" + forecast_name + "/"
        s3_role_arn = ui.s3_role_arn

        # Create a forecast export
        forecast_export_arn, status = create_forecast_export(
            ui.forecast_client, forecast_export_name, forecast_arn, s3_path,
            s3_role_arn)
        if status == 'failure':
            caffeine.off()
            return status

        # Wait until forecast export is created
        while response['Status'] != 'ACTIVE' and response[
                'Status'] != 'CREATE_FAILED':
            response = forecast_client.describe_forecast_export_job(
                ForecastExportJobArn=forecast_export_arn)
            time.sleep(10)
        if response['Status'] == 'CREATE_FAILED':
            caffeine.off()
            return 'failure'

        # Wait 30 seconds to make sure exported files show on S3 (this should be immediate)
        time.sleep(30)

        # Create a database in AWS Glue
        status = create_database(ui.glue_client)
        if status == 'failure':
            caffeine.off()
            return status

        # Create a crawler in AWS Glue
        status = create_crawler(ui.glue_client, s3_role_arn, s3_path,
                                forecast_name)
        if status == 'failure':
            caffeine.off()
            return status

        # Run the created crawler
        status = run_crawler(forecast_name, ui.glue_client)
        if status == 'failure':
            caffeine.off()
            return status

        caffeine.off()
        return 'success'
    except Exception as e:
        caffeine.off()
        error(str(e))
        return 'failure'
Example #8
0
def main():
    def send_power_to_arduino(event):

        print('serial write')

        power = str(slider.get())

        if len(power) == 1:

            power = "0" + str(power)

        print(power)

        ser.write("1" + power)

        time.sleep(0.1)

        print(ser.read(ser.inWaiting()))

    def turn_power_off():

        slider.set(0)

        send_power_to_arduino(1)

    def _quit():

        root.quit()  # stops mainloop

        root.destroy()

    def get_temp():

        ser.write("200")

        time.sleep(0.1)

        return ser.read(ser.inWaiting())

    def update_temp():

        global power_list, temp_list, temp_list_filterd, time_list, t0, timer_zeit, P, I, pgain, igain, dgain, reftemp

        print("temp updated")

        temp = get_temp()

        label4.config(text="Temperatur:   " + str(temp) + " C")

        roestzeit = int(time.time() - t0)

        if controlling.get() == 1 and temp_record == 1:

            print "controlling"

            P = slider.get()

            print "roestzeit = ", roestzeit

            if roestzeit > len(reftemp):

                winsound.Beep(2500, 1000)

                P = 0

            else:

                Tc = int(reftemp[roestzeit])

                E = Tc - int(temp)

                print "E=  ", E

                I = I + E

                steig = 0

                if len(time_list) > 25:

                    steig = (temp_list_filterd[-2] -
                             temp_list_filterd[-5]) / 3.0

                    D = -steig + (reftemp[roestzeit - 2] -
                                  reftemp[roestzeit - 5]) / 3.0

                else:

                    D = 0

                P = P + E * pgain + I * igain + D * dgain

                print "P =  ", P, "; Pgain= ", E * pgain, "; Igain= ", I * igain, "; Dgain= ", D * dgain, " Steigung= ", steig, " Ref Steugung = ", (
                    reftemp[roestzeit] - reftemp[roestzeit - d_bin]) / d_bin

                if P <= 0:

                    P = 0

                if P >= 100:

                    P = 100

            slider.set(P)

            send_power_to_arduino(1)

        if temp_record == 1:

            temp_list.append(abs(int(temp)))  #hier abs eingefuegt

            if len(temp_list) > 10:

                temp_list_filterd = butterWorthFilter(temp_list)

            else:

                temp_list_filterd = temp_list

            time_list.append(roestzeit)

            power_list.append(slider.get())

            label5.config(text="Roestzeit:   " + str(roestzeit / 60) +
                          " min  " + str(mod(roestzeit, 60)) + " sec")

            line1[0].set_data(pylab.array(time_list[1:]),
                              pylab.array(temp_list[1:]))

            line1[1].set_data(reftime, reftemp)

            line2[0].set_data(pylab.array(time_list[1:]),
                              pylab.array(power_list[1:]))

            line3[0].set_data(pylab.array(time_list[1:]),
                              pylab.array(temp_list_filterd[1:]))

            line3[0].set_linewidth(3.0)

            line3[0].set_alpha(0.6)

            line3[0].set_color('b')

            if (time.time() - t0) / 60.0 > timer_zeit:

                stop_temp_record()

                turn_power_off()

        canvas.draw()

        rightFrame.after(900, update_temp)

    def start_temp_record():

        global temp_record, t0

        t0 = time.time()

        temp_record = 1

    def stop_temp_record():

        global temp_record

        global temp_list

        global time_list

        thefile = open('test.txt', 'w')

        thefile.write("time \n")

        for item in time_list:

            thefile.write("%s\n" % item)

        thefile.write("temp \n")

        for item in temp_list:

            thefile.write("%s\n" % item)

        thefile.write("temp_avg \n")

        # VAR temp_list_filtered not defined

        # for item in temp_list_filterd:
        #
        #     thefile.write("%s\n" % item)

        temp_record = 0

        temp_list = [0]

        time_list = [0]

    def timer_eingabe():

        global timer_zeit, dgain, pgain, igain, d_bin

        timer_zeit = float(eingabe_timer.get())

        pgain = float(eingabe_p_gain.get())

        dgain = float(eingabe_d_gain.get())

        igain = float(eingabe_i_gain.get())

        d_bin = int(float(eingabe_d_bin.get()))

        print("Timer auf " + str(timer_zeit) +
              " min gestellt und gains upgedated.")

    def movingaverage(temp_data, points_mean):

        temp_data = np.asarray(temp_data, dtype=float)

        if len(temp_data) > points_mean:

            temp_data[-1] = numpy.mean(temp_data[-points_mean:len(temp_data)])

            temp_data = np.round(temp_data, 2)

        return temp_data.tolist()

    def butterWorthFilter(temp_data):

        # First, design the Buterworth filter

        N = 2  # Filter order

        Wn = 0.05  # Cutoff frequency

        B, A = signal.butter(N, Wn, output='ba')

        # Second, apply the filter

        temp_data = signal.filtfilt(B, A, temp_data)

        return temp_data

    ###################################################################################################################
    ##################################### START #######################################################################
    ###################################################################################################################

    if platform.system() == 'Darwin':

        for serialNumber in [411, 641, 14311, 14321, 14421]:

            try:

                ser = serial.Serial('/dev/tty.usbmodem' + str(serialNumber),
                                    9600)

            except:

                pass

    if platform.system() == 'Windows':

        ser = serial.Serial('COM3', 9600)

    print('wait 2 sec')

    time.sleep(2)

    root = Tk()

    controlling = Tkinter.IntVar()

    root.wm_title("Coffe roaster")

    xAchse = pylab.arange(0, 1, 1)

    yAchse = pylab.array([0] * 1)

    fig = pylab.figure(1)

    ax = fig.add_subplot(111)

    ax.grid(True)

    ax.set_title("Roestkurve")

    ax.set_xlabel("Time")

    ax.set_ylabel("Temperature")

    ax.axis([0, (18 * 60), 0, 300])

    reftime = pylab.arange(len(reftemp))

    line1 = ax.plot(xAchse, yAchse, reftime, reftemp)

    line2 = ax.plot(xAchse, yAchse, reftime, reftemp)

    line3 = ax.plot(xAchse, yAchse, reftime, reftemp)

    leftFrame = Frame(root)

    leftFrame.pack(side=LEFT)

    rightFrame = Frame(root)

    rightFrame.pack(side=RIGHT)

    ### Temperatur anzeigen
    label4 = Label(rightFrame, text="Temperatur:   " + str(get_temp()) + " C")

    label4.pack()

    label5 = Label(rightFrame, text="Roestzeit:   " + str(0) + " min")

    label5.pack()

    canvas = FigureCanvasTkAgg(fig, rightFrame)

    canvas.show()

    canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

    toolbar = NavigationToolbar2TkAgg(canvas, rightFrame)

    toolbar.update()

    canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True)

    c = Checkbutton(leftFrame,
                    text="Temperature controlling",
                    variable=controlling,
                    onvalue=1,
                    offvalue=0)

    c.pack()

    label1 = Label(leftFrame, text="Power")

    label1.pack()

    slider = Scale(leftFrame, from_=0, to=99, orient=VERTICAL)

    slider.set(P0)

    slider.bind("<ButtonRelease-1>", send_power_to_arduino)

    slider.pack()

    send_power_to_arduino(1)

    button_off = Tkinter.Button(leftFrame, text="Off", command=turn_power_off)

    button_off.pack()

    button_start = Tkinter.Button(leftFrame,
                                  text="Start",
                                  command=start_temp_record)

    button_start.pack()

    button_stop = Tkinter.Button(leftFrame,
                                 text="Stop",
                                 command=stop_temp_record)

    button_stop.pack()

    label6 = Tkinter.Label(leftFrame, text="Timer in min (integer)")

    label6.pack()

    entryText10 = Tkinter.StringVar()

    eingabe_timer = Tkinter.Entry(leftFrame, textvariable=entryText10)

    entryText10.set("30")

    eingabe_timer.pack()

    label7 = Tkinter.Label(leftFrame, text="P Gain")

    label7.pack()

    entryText1 = Tkinter.StringVar()

    eingabe_p_gain = Tkinter.Entry(leftFrame, textvariable=entryText1)

    entryText1.set(str(pgain))

    eingabe_p_gain.pack()

    label8 = Tkinter.Label(leftFrame, text="D Gain")

    label8.pack()

    entryText2 = Tkinter.StringVar()

    eingabe_d_gain = Tkinter.Entry(leftFrame, textvariable=entryText2)

    entryText2.set(str(dgain))

    eingabe_d_gain.pack()

    label9 = Tkinter.Label(leftFrame, text="I Gain")

    label9.pack()

    entryText3 = Tkinter.StringVar()

    eingabe_i_gain = Tkinter.Entry(leftFrame, textvariable=entryText3)

    entryText3.set(str(igain))

    eingabe_i_gain.pack()

    label10 = Tkinter.Label(leftFrame, text="d_bin")

    label10.pack()

    entryText4 = Tkinter.StringVar()

    eingabe_d_bin = Tkinter.Entry(leftFrame, textvariable=entryText4)

    entryText4.set(str(d_bin))

    eingabe_d_bin.pack()

    button_timer_ok = Tkinter.Button(leftFrame,
                                     text="OK",
                                     command=timer_eingabe)

    button_timer_ok.pack()

    root.protocol("WM_DELETE_WINDOW", _quit)  #thanks aurelienvlg

    root.after(1000, update_temp)

    root.mainloop()

    ser.close()

    # releases any power assertion (os x can go sleep again)
    if platform.system() == 'Darwin':
        caffeine.off()
Example #9
0
            agent.update_target_model()

        #計算max drawdown
        if len(inventory) > 0:
            inventory_value = get_inventory_value(inventory,
                                                  data[t + 1][n_close],
                                                  trading.commission)
            inventory_value *= trading.unit
            profolio = inventory_value + cash
        else:
            profolio = cash
        if profolio - init_cash < 0:  #虧損時才做
            drawdown = (profolio - init_cash) / init_cash
            if drawdown < max_drawdown:
                max_drawdown = drawdown

        if agent.memory.tree.n_entries > agent.batch_size:
            agent.train_model()

        if done:
            print("-" * 124)
            print("Episode " + str(e) + "/" + str(episode_count) +
                  " | Cash: " + formatPrice(cash) + " | Total Profit: " +
                  formatPrice(total_profit) + " | Return Ratio: %.2f%%" %
                  round(100 * total_profit / init_cash, 2) +
                  " | Max DrawDown: %.2f%%" % round(-max_drawdown * 100, 2) +
                  " | Total Reward: " + str(round(total_reward, 2)))
            print("-" * 124)
            if e == episode_count:
                caffeine.off()  #讓電腦回去休眠
Example #10
0
        caffeine.on(display=True)  #Prevents screen to sleep on MacOS

        for name in names:  #Send message to all names list

            firstName = name.split(' ', 1)[0]
            if (msgBase.find('%s') != -1):  #Prepare the message before sending
                msg = msgBase % firstName
            else:
                msg = msgBase

            try:  #Try sending the message
                sendMsg(msg, name, driver)  #Send message
                count = count + 1
            except common.exceptions.NoSuchElementException as e:  #Didn't find the "Back" button.
                pass
            except:  #Click the "Back" button.
                backBut = WebDriverWait(driver, 3).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, '//span[@data-icon="back-light"]')))
                backBut.click()
            time.sleep(3)

        caffeine.off()  #Allows screen to sleep from now and on

        print(
            str(count) + ' messages have been sent out of ' +
            str(names.__len__()))
    else:
        break

driver.close()