Exemplo n.º 1
0
    def run_query(self):
        """
        In a sample run,
            year_query, quarter_query, table_query
        are all initialized with a random variable of a size 1 list
        """
        for year in self.year_query:
            for quarter in self.quarter_query:
                for table in self.table_query:
                    # In a specific result
                    self.set_table(year, quarter, table)

                    constant = self.get_table(1)
                    page_all = constant[0]
                    data = constant[1]
                    start_page = 1
                    end_page = int(
                        page_all.group(1))  # page_all is a regex outcome

                    if self.random_query:
                        print(' ' + self.date, end='')
                        print(len(data))
                        break

                    # Main job
                    self.write_header(table, data)
                    for page in range(start_page, end_page):
                        clk = clock.Clock(2)
                        print('\nDownloading page #{}/{}, {}, table {}...'.
                              format(page, end_page, self.date, table))
                        func = self.get_table(page)
                        data = func[1]
                        page = func[2]
                        self.write_table(table, data, page)
Exemplo n.º 2
0
 def __init__(self):
     self.clock = cl.Clock(self)
     self.week = cl.Week(self)
     self.calendar = cl.SecularCalendar()
     self.productionAI = ai.ProductionAI(self)
     self.jobPoster = ai.JobPoster(self)
     self.hirer = ai.Hirer(self)
     self.firer = ai.Firer(self)
     self.startupAI = ai.StartupAI()
     self.builder = ai.Builder(self)
     self.salaryPayer = ai.SalaryPayer(self)
     ourGen = generator.generator(self)
     self.ourWorld = ourGen.generateWorld(10000, 10, 10)
     Jonestown = d.getLocality()[0]
     #char
     address = Jonestown.find_property()
     yourHome = u.House(Jonestown, address)
     Jonestown.claim_node(address, yourHome)
     self.char = ai.Character(self, "Markemus", "Williamson", 0, Jonestown,
                              yourHome,
                              d.getReligions()[0])
     yourHome.addTenant(self.char)
     spouse = p.People(self, "Susan", "Spinster", 1, Jonestown, yourHome,
                       d.getReligions()[0])
     yourHome.addTenant(spouse)
     self.char.addCapital(10000)
     #makes
     ourGen.makeSpouses()
     ourGen.makeFriends()
     ourGen.makeBosses()
     ourGen.makeChurches(Jonestown)
     ourGen.assignChurches()
     self.gui = gui.gui(self.char)
Exemplo n.º 3
0
    def add_head(self):
        top = QFrame()
        top.setFrameShape(QFrame.WinPanel)
        top.setFrameShadow(QFrame.Raised)
        top.setMaximumHeight(100)
        top.setStyleSheet("background-color: red;")

        clk = clock.Clock(parent=top)
        clk.setFrameShape(QFrame.NoFrame)
        clk.setStyleSheet("background-color:none; color: white;")
        clk.move(-75, -75)
        clk.setMinimumWidth(250)
        clk.setMinimumHeight(250)

        next_bus = QLabel(top)
        next_bus.setFont(QFont("Sans-serif", 42, QFont.Bold))
        bus = self.l[0][0]
        time = self.l[0][1]
        next_bus.setText("<font color='white'>Next Bus: " + bus + " in " +
                         time + "</font>")
        next_bus.move(int(self.screen.width() / 2) - 400, 25)

        weather = QLabel(top)
        weather.setFont(QFont("Sans-serif", 42, QFont.Bold))
        w = forecast('c505a8dedfcf4bc235046f56138a67d9', 51.0253, -114.0499)
        temp = round(w['currently']['temperature'])
        weather.setText("<font color='white'>" + str(temp) + "°</font>")
        weather.move(self.screen.width() - 130, 25)
        self.layout.addWidget(top)
Exemplo n.º 4
0
 def test_time_func_and_now(self):
     """Standard behavior of now(). Calling it invokes the time function."""
     c = clock.Clock(
         time_func=lambda: datetime.datetime(2016, 1, 18, tzinfo=pytz.utc))
     self.assertEqual(c.now(), clock.DateTimeTs(2016,
                                                1,
                                                18,
                                                tzinfo=pytz.utc))
Exemplo n.º 5
0
    def __init__(self):

        self._rang = 0
        self._digits = 0
        self._units = []
        self._numbers = []
        self._result = []
        self._clock = clock.Clock()
Exemplo n.º 6
0
    def __init__(self, starting_x, starting_y, flowtime):

        self.starting_x = starting_x
        self.starting_y = starting_y
        self.flowtime = flowtime
        self.clock = clock.Clock()
        self.is_flowing = False
        self.x = self.starting_x
        self.y = self.starting_y
Exemplo n.º 7
0
 def __init__(self, count=2, curses_window=None):
     # we'll write stuff here
     self.curses_window = curses_window
     self.sequences = [Sequence() for i in range(0, count)]
     self.sequences[0].set_end(5)
     self.sequences[0].begin_edit(1)
     self.sequences[0].set_edit_value(1)
     self.clock = clock.Clock()
     self.clock.add_listener(self)
Exemplo n.º 8
0
def main(dummy):
    if not dummy:
        g = gui.GuiScreen((1, 0))
    else:
        g = gui.GuiCurses(dummy['win'])

    with g.refreshHold:
        vg = gui.VGroup([1, 2, 8, 2])
        g.add(vg)

        statusbar = gui.HGroup([4, 4, 1, 1, 1, 6])
        vg.getMember(0).add(statusbar)

        tabs = gui.HGroup([1] * 6)
        vg.getMember(1).add(tabs)

        mainbox = vg.getMember(2)

        keylabels = gui.HGroup([1] * 4)
        vg.getMember(3).add(keylabels)

        t1 = gui.TextBox()
        statusbar.getMember(0).add(t1)

        def cb1(temp):
            with t1.refreshHold:
                t1.text = '%2.1f' % (temp * 9.0 / 5.0 + 32)
            t1.refresh()

        if not dummy:
            ts = thermocouple.max6675((0, 0))
        else:
            ts = thermocouple.max6675(None)
        ts.report(cb1)

        t2 = gui.TextBox()
        statusbar.getMember(5).add(t2)

        def cb2(tm):
            with t2.refreshHold:
                tm = tm.split('$')
                tm[1] = int(tm[1])
                t2.text = '%s %u:%s %s' % tuple(tm)
            t2.refresh()

        clk = clock.Clock()
        clk.reportLocal(None, '%a$%I$%M$%p', cb2)

    while True:
        try:
            time.sleep(100)
        except KeyboardInterrupt:
            break
Exemplo n.º 9
0
 def get(self, key, timeStamp):
     """
     return according to API specification.
     """
     if timeStamp is None or clock.isHappenBefore(
             0, clock.Clock(timeStamp), 0, self.serverProxy.timeStamp):
         try:
             return self.fileDict.data[key]['value']
         except KeyError:
             return config.KEY_ERROR if timeStamp is None else config.ERR_DEP
     else:
         return config.ERR_DEP
Exemplo n.º 10
0
    def play_intro(self):

        if self._MUSIC:
            pygame.mixer.music.load("soundtrack.ogg")
            pygame.mixer.music.play(-1)

        if self._TESTING:
            num_players = 3

            self._players.append(Player("Ege", "boot"))
            self._players.append(Player("Evan", "phone"))
            #self._players.append(Player("Kingsley", "hat"))

            #self._players.append(ai.AI("bot1", "boot"))
            #self._players.append(ai.AI("bot2", "phone"))
            self._players.append(ai.AI("bot3", "hat"))

            self._mode = ["Full", "Abridged"][1]
            self._clock = clock.Clock()
            self._clock.set_time_limit("0:10:00")

        else:
            num_players = GUI.game_intro()
            player_names, ai_info = GUI.select(num_players)
            for i in range(len(player_names)):
                player_name = player_names[i]
                new_token = self._tokens[i]
                if ai_info[i] == 0:
                    new_player = Player(player_name, new_token)
                else:
                    new_player = ai.AI(player_name, new_token)

                self._players.append(new_player)

            selected_mode, selected_duration = GUI.mode_select()
            self._mode = selected_mode
            self._clock = clock.Clock()
            self._clock.set_time_limit(selected_duration)
Exemplo n.º 11
0
def make_pump_manager(moisture_threshold, sleep_windows, raspberry_pi_io,
                      wiring_config, pump_amount, db_connection, pump_interval,
                      water_level_sensor):
    """Creates a pump manager instance.

    Args:
        moisture_threshold: The minimum moisture level below which the pump
            turns on.
        sleep_windows: Sleep windows during which pump will not turn on.
        raspberry_pi_io: pi_io instance for the GreenPiThumb.
        wiring_config: Wiring configuration for the GreenPiThumb.
        pump_amount: Amount (in mL) to pump on each run of the pump.
        db_connection: Database connection to use to retrieve pump history.
        pump_interval: Maximum amount of hours between pump runs.
        water_level_sensor: Interface to the water level sensor.

    Returns:
        A PumpManager instance with the given settings.
    """
    water_pump = pump.Pump(raspberry_pi_io, clock.Clock(),
                           wiring_config.gpio_pins.pump)
    pump_scheduler = pump.PumpScheduler(clock.LocalClock(), sleep_windows)
    pump_timer = clock.Timer(clock.Clock(), pump_interval)
    last_pump_time = pump_history.last_pump_time(
        db_store.WateringEventStore(db_connection))
    if last_pump_time:
        logger.info('last watering was at %s', last_pump_time)
        time_remaining = max(datetime.timedelta(seconds=0),
                             (last_pump_time + pump_interval) -
                             clock.Clock().now())
    else:
        logger.info('no previous watering found')
        #~ time_remaining = datetime.timedelta(seconds=0)   # !!!WARNING!!! Immediately water plants if no previous watering event was found !!!WARNING!!!
        time_remaining = pump_interval  # Schedule the first mandatory plant watering event in pump_interval hours
    logger.info('time until until next watering: %s', time_remaining)
    pump_timer.set_remaining(time_remaining)
    return pump.PumpManager(water_pump, pump_scheduler, moisture_threshold,
                            pump_amount, pump_timer, water_level_sensor)
Exemplo n.º 12
0
 def __init__(self, dev, menu, mqtt):
     self.device = dev
     self.menu = menu
     self.current_item = 0
     self.current_view = 'clock'
     self.clock = clock.Clock(self.device)
     self.current_radio = ""
     self.fan = ""
     GPIO.add_event_detect( 20, GPIO.FALLING, callback=self.menu_item_down, bouncetime=300)
     GPIO.add_event_detect( 23, GPIO.FALLING, callback=self.menu_item_up, bouncetime=300)
     GPIO.add_event_detect( 26, GPIO.FALLING, callback=self.execute, bouncetime=300)
     GPIO.add_event_detect( 21, GPIO.FALLING, callback=self.go_home, bouncetime=300)
     GPIO.add_event_detect( 22, GPIO.FALLING, callback=self.go_home, bouncetime=300)
     mqtt.on_message = self.on_mqtt_message
Exemplo n.º 13
0
 def put_internal(self, item):
     """
     Put request comes from peer servers
     :param item: a dictionary with "key", "value", "serverId", "timeStamp"
     :return:
     """
     key = item['key']
     value = item['value']
     timeStamp = item['timeStamp']
     serverId = item['serverId']
     messageId = item['messageId']
     # log.msg("Key [{}] received[internal]: {}".format(key, item), system=self.serverProxy.tag)
     if key not in self.fileDict or clock.isHappenBefore(
             self.fileDict[key]['serverId'],
             clock.Clock(self.fileDict[key]['timeStamp']), serverId,
             clock.Clock(timeStamp)):
         # Our server doesn't have this KV pair or our KV pair is outdated
         self.fileDict.put(item)
     self.serverProxy.sendMessage({
         "ReceiverId": serverId,
         "MessageId": messageId,
         "Method": "Ack",
         "Payload": self.serverProxy.serverId
     })
Exemplo n.º 14
0
def make_camera_manager(rotation, image_path, light_sensor):
    """Creates a camera manager instance.

    Args:
        rotation: The amount (in whole degrees) to rotate the camera image.
        image_path: The directory in which to save images.
        light_sensor: A light sensor instance.

    Returns:
        A CameraManager instance with the given settings.
    """
    #~ camera = picamera.PiCamera(resolution=picamera.PiCamera.MAX_RESOLUTION)
    #~ camera.rotation = 0
    return camera_manager.CameraManager(image_path, clock.Clock(),
                                        light_sensor)
Exemplo n.º 15
0
def make_dht22_sensors(wiring_config):
    """Creates sensors derived from the DHT22 sensor.

    Args:
        wiring_config: Wiring configuration for the GreenPiThumb.

    Returns:
        A two-tuple where the first element is a temperature sensor and the
        second element is a humidity sensor.
    """
    local_dht22 = dht22.CachingDHT22(
        lambda: Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, wiring_config.
                                        gpio_pins.dht22), clock.Clock())
    return temperature_sensor.TemperatureSensor(
        local_dht22), humidity_sensor.HumiditySensor(local_dht22),
Exemplo n.º 16
0
def main():
    args = parse_args(sys.argv[1:])
    if args.time < 200:
        print('error: --time values <200ms are not supported.\n'
              'Uploading a frame takes ~180ms...')
        sys.exit(1)

    bl = blinken.Blinken(gamma=args.gamma,
                         debug=args.verbose,
                         dev=args.device,
                         speed=args.speed)

    if args.reset:
        bl.command('RST')

    # Render a splash screen to ensure there's always
    # one animation in the queue as our "framebuffer"
    # and cause people seizures as we fetch calendar data ;-)
    splash(bl)
    clk = clock.Clock(10)
    cal = Cal(args.calendar)

    frame = 0
    start = time.clock_gettime(time.CLOCK_MONOTONIC)
    while True:
        now = arrow.now()
        buf = Image.new(mode='RGB', size=(16, 16))
        draw = ImageDraw.Draw(buf)
        cal.Draw(draw, now)
        clk.Draw(draw)
        with bl.animation(1100, start_next=True) as anim:
            anim.frame_from_image(buf, 1100)
        # Keep calendar updates in the dead time between frame draws.
        # Update for *next* second because that's when it'll be rendered.
        # TODO: put it on a separate thread, fetching and parsing 500kb
        #   of ICS data with raw python is multiple-seconds slow and will
        #   cause a noticeable period of blank screen.
        cal.UpdateBoxes(now.shift(seconds=1))
        frame += 1
        frametime = (start +
                     ((args.time / 1000) * frame)) - time.clock_gettime(
                         time.CLOCK_MONOTONIC)
        if frametime < 0:
            print('Negative frame time, things are taking too long :-O')
            continue
        time.sleep(frametime)
Exemplo n.º 17
0
def make_sensor_pollers(poll_interval, photo_interval, record_queue,
                        mqtt_client, temperature_sensor, humidity_sensor,
                        water_level_sensor, soil_moisture_sensor, drain_sensor,
                        light_sensor, camera_manager, pump_manager):
    """Creates a poller for each GreenPiThumb sensor.

    Args:
        poll_interval: The frequency at which to poll non-camera sensors.
        photo_interval: The frequency at which to capture photos.
        record_queue: Queue on which to put sensor reading records.
        mqtt_client: The mqtt client for sending updates to openhab
        temperature_sensor: Sensor for measuring temperature.
        humidity_sensor: Sensor for measuring humidity.
        water_level_sensor: Sensor for measuring the reservoir water level.
        soil_moisture_sensor: Sensor for measuring soil moisture.
        drain_sensor: Sensor for measuring wheather water has drained through the plant pot.
        light_sensor: Sensor for measuring light levels.
        camera_manager: Interface for capturing photos.
        pump_manager: Interface for turning water pump on and off.

    Returns:
        A list of sensor pollers.
    """
    logger.info('creating sensor pollers (poll interval=%ds")',
                poll_interval.total_seconds())
    utc_clock = clock.Clock()

    make_scheduler_func = lambda: poller.Scheduler(utc_clock, poll_interval)
    photo_make_scheduler_func = lambda: poller.Scheduler(
        utc_clock, photo_interval)
    poller_factory = poller.SensorPollerFactory(make_scheduler_func,
                                                record_queue, mqtt_client)
    camera_poller_factory = poller.SensorPollerFactory(
        photo_make_scheduler_func, record_queue, mqtt_client)

    return [
        poller_factory.create_temperature_poller(temperature_sensor),
        poller_factory.create_humidity_poller(humidity_sensor),
        poller_factory.create_water_level_poller(water_level_sensor),
        poller_factory.create_soil_watering_poller(
            soil_moisture_sensor, drain_sensor, pump_manager),
        poller_factory.create_light_poller(light_sensor),
        camera_poller_factory.create_camera_poller(camera_manager)
    ]  # yapf: disable
Exemplo n.º 18
0
def make_sensor_pollers(poll_interval, photo_interval, record_queue,
                        temperature_sensor, humidity_sensor,
                        soil_moisture_sensor, light_sensor, camera_manager,
                        pump_manager):
    """Creates a poller for each GreenPiThumb sensor.

    Args:
        poll_interval: The frequency at which to poll non-camera sensors.
        photo_interval: The frequency at which to capture photos.
        record_queue: Queue on which to put sensor reading records.
        temperature_sensor: Sensor for measuring temperature.
        humidity_sensor: Sensor for measuring humidity.
        soil_moisture_sensor: Sensor for measuring soil moisture.
        light_sensor: Sensor for measuring light levels.
        camera_manager: Interface for capturing photos.
        pump_manager: Interface for turning water pump on and off.

    Returns:
        A list of sensor pollers.
    """
    logger.info('creating sensor pollers (poll interval=%ds")',
                poll_interval.total_seconds())
    utc_clock = clock.Clock()

    make_scheduler_func = lambda: poller.Scheduler(utc_clock, poll_interval)
    photo_make_scheduler_func = lambda: poller.Scheduler(
        utc_clock, photo_interval)
    poller_factory = poller.SensorPollerFactory(make_scheduler_func,
                                                record_queue)
    camera_poller_factory = poller.SensorPollerFactory(
        photo_make_scheduler_func, record_queue=None)

    return [
        poller_factory.create_temperature_poller(temperature_sensor),
        poller_factory.create_humidity_poller(humidity_sensor),
        poller_factory.create_soil_watering_poller(
            soil_moisture_sensor,
            pump_manager),
        poller_factory.create_light_poller(light_sensor),
        camera_poller_factory.create_camera_poller(camera_manager)
    ]  # yapf: disable
Exemplo n.º 19
0
    def __init__(self, master, controller):
        """Creates MirrorDisplay frame and places all plugin frames inside.

        Args:
            master: parent of this frame, usually direct container.
            controller: main window class providing public functions
                for control of the application from this frame's
                level.
        """
        tk.Frame.__init__(self,
                          master,
                          width=1080,
                          height=2560,
                          cursor='none',
                          bg='black')

        self._controller = controller

        # Binding keyboard event to application's main window.
        controller.bind('<Tab>', self._edit_mode)

        self._framename_coords_dict = controller.get_framename_coords_dict()
        self._window_in_edit_mode = False

        # Initializing frames passing self as a master and controller
        # into the init functions.
        self._clock = clock.Clock(self, controller)
        self._weather = weather.Weather(self, controller)
        self._greeter = greeter.Greeter(self, controller)
        self._smartcalendar = smartcalendar.Calendar(self, controller)

        # Placing frames on the main frame using place geometry
        # manager (module's frames should be placed only with place
        # manager).
        self._place_frames()

        # Setting keyboard focus so we can use keyboard bindings
        # without clicking on the window first.
        self.focus_set()
Exemplo n.º 20
0
 def __init__(self):
     self.io_daemon = pi_io.PigpioDaemon()
     self.clock = clock.Clock()
     self.alarm_manager = alarm_manager.AlarmManager()
Exemplo n.º 21
0
import os
import time
import threading
from time import gmtime, strftime
from flask import Flask, request, render_template, request, url_for, redirect, Markup, Response, send_file, send_from_directory, make_response, jsonify
import mraa
import clock
app = Flask(__name__)
'''class Clock(object):
	def __init__(object):
		strftime("%Y-%m-%d %H:%M:%S", gmtime())'''

touch = mraa.Gpio(32)
touch.dir(mraa.DIR_IN)
clock = clock.Clock()


@app.route('/clear/', methods=['POST'])
def clear():
    os.system('sudo ./clear')
    return redirect(url_for('index'))


@app.route('/write/<text1>', methods=['POST'])
@app.route('/write/<text1>/<text2>', methods=['POST'])
def write(text1, text2=""):
    print text1
    print text2
    os.system('sudo ./main "{}" "{}"'.format(text1, text2))
    return redirect(url_for('index'))
Exemplo n.º 22
0
 def startClock(self):
     self.clock = clock.Clock(self)
     self.run(self.clock.tickLoop)
Exemplo n.º 23
0
 def __init__(self, gui, dia):
     self.gui = gui
     self.dia = dia
     self.menuActive = True
     
     if "arm" in platform.machine():
         print("ARM Detected, so probably Rapberry")
         import rpi_backlight as bl
         import lircradio
        
         # Backlight
         bl.set_brightness(100) # start up with full brightness
         
         # LIRC remote
         lircQueue = queue.Queue()
         
         self.LircObject = lircradio.LircInterface(lircQueue)
         self.LircObject.start()
         
         self.LircHandler = lircradio.LircHandler(lircQueue)
         self.lircTimer = QtCore.QTimer()
         self.lircTimer.timeout.connect(self.LircHandler.timerCall)
         self.lircTimer.start(1000)
         self.LircHandler.addCallback("ok", self.ok_clicked)
         self.LircHandler.addCallback("back", self.back_clicked)
         self.LircHandler.addCallback("up", self.up_clicked)
         self.LircHandler.addCallback("down", self.down_clicked)
         self.LircHandler.addCallback("left", self.left_clicked)
         self.LircHandler.addCallback("right", self.right_clicked)
         self.LircHandler.addCallback("power", self.power_clicked)
     else:
         print("No ARM, so no Rapberry")
         
     self.sDialog = station.SelectStation()
     dia.setStyleSheet("QWidget#Dialog {background-image: url(Music-Record-Vinyl-800-480.jpg);}")
     self.cDialog = clock.Clock(self)
     
     self.infoTimer = QtCore.QTimer()
     self.infoTimer.timeout.connect(self.timercall)
     self.infoTimer.start(5000)
     
     font = QtGui.QFont()
     font.setFamily("Droid Sans")
     font.setPointSize(28)
     font.setBold(True)
     font.setWeight(75)
     
     self.labelStation = labelClickable.QLabelClickable(self.dia)
     self.labelStation.setFont(font)
     self.labelStation.setGeometry(28, 415, 750, 60)
     self.labelStation.setText("<font color='lightGray'> Back </font>")
     self.labelStation.clicked.connect(self.selectStation_clicked)
     self.showArtist("")
     self.showSong("")
     self.getLastPlayed()
     
     self.showStation(self.last_name)
     self.showTime()
     self.showPicture(self.last_image)
     
     self.client = mpd.MPDClient()       # create client object
     self.client.timeout = 2             # network timeout in seconds (floats allowed), default: None
     self.client.idletimeout = None      # timeout for fetching the result of the idle command is handled seperately, default: None
     
     self.number = 0
     self.clear()
     self.addStation(self.lasturl)
     print("Starting")
     self.play(self.number)
     self.status = "playing"
     self.getShowInfo()
Exemplo n.º 24
0
        value = complemento2(dato[0])*(16**2) + dato[1]
    elif medicion == 'FechaHora':
        pass
    elif medicion == 'Temperatura':
        pass
    return value

def complemento2(dato):
    number = dato
    if dato >> 7 == 1:
        number = -1 * (dato & 0x7F)
    return number

hora = [0x01,0x06,0x00,0x17,0x03,0x06,0x12,0x19]

sensor_aceleraciones = acelerometro.Acelerometro(0x1C)
clock = clock.Clock( hora )
temperatura = ds18b20.DS18B20()

tareas.append( Repetir(1, actualizar_mediciones) )
tareas.append( Repetir(.1, actualizar_valores))


for tarea in tareas:
    tarea.start()


App.mainloop()                      #corremos la App
    

Exemplo n.º 25
0
def main():
    # get user input from command line args, store it in a list
    cmdLineArgs = getUserInput()

    # get the user input from our list, so we can use it in main
    try:
        num_frames = int(cmdLineArgs[0])
    except:
        print "Number of frames not specified properly."
        print "Usage:  python vmsim.py -n <numframes> -a <opt|clock|aging|lru> [-r <refresh>] <tracefile>"

    algorithm = cmdLineArgs[1]
    if cmdLineArgs[2] is not None:
        refresh = float(cmdLineArgs[2])
    traceFile = cmdLineArgs[3]

    # parse the input and store it
    memory_addresses = parse.parse_trace_file(traceFile)

    # build the model for our page table, 32bit address space
    # initialize our table
    pageTable = pt.PageTable(num_frames)

    # write opt algorithm
    if algorithm == "opt":
        t0 = time.time()
        OptAlgorithm = opt.Opt(pageTable, memory_addresses)
        OptAlgorithm.run_algorithm()
        t1 = time.time()
        total = t1 - t0
        print "TOTAL RUNNING TIME IN MINUTES: " + str(total * 0.0166667)

    # write clock algorithm
    elif algorithm == "clock":
        t0 = time.time()
        clock_algorithm = clock.Clock(pageTable, memory_addresses)
        clock_algorithm.run_algorithm()
        t1 = time.time()
        total = t1 - t0
        print "TOTAL RUNNING TIME IN MINUTES: " + str(total * 0.0166667)

    # write aging algorithm
    elif algorithm == "aging":
        t0 = time.time()
        aging_algorithm = aging.Aging(pageTable, memory_addresses, refresh)
        aging_algorithm.run_algorithm()
        t1 = time.time()
        total = t1 - t0
        print "TOTAL RUNNING TIME IN MINUTES: " + str(total * 0.0166667)

    # write lru algorithm
    elif algorithm == "lru":
        t0 = time.time()
        LRU_algorithm = lru.LRU(pageTable, memory_addresses)
        LRU_algorithm.run_algorithm()
        t1 = time.time()
        total = t1 - t0
        print "TOTAL RUNNING TIME IN MINUTES: " + str(total * 0.0166667)

    else:
        print "Invalid algorithm name. Acceptable choices are:" \
              "\n\t- 'opt' \n\t- 'clock' \n\t- 'aging' \n\t- 'lru' " \
              "\n\n\tNote: algorithm names are case sensitive\n"

        print "Usage:  python vmsim.py -n <numframes> -a <opt|clock|aging|lru> [-r <refresh>] <tracefile>\n"
    return
Exemplo n.º 26
0
 def init_clock(self):
     self.clock = clock.Clock()
Exemplo n.º 27
0
emoji_volume = widget.Volume(
    emoji=True,
    step=5,
)

text_volume = widget.Volume(
    fmt="{:>4}",
    step=5,
    # emoji=True,
)

clock = clock.Clock(
    format="⏳ %H:%M",
    format_alt="📆 %Y-%m-%d %H:%M",
    mouse_callbacks={
        'Button4': kill_calcurse,
        'Button5': open_calcurse
    },
)

systray = widget.Systray()

power = widget.TextBox(
    text="",
    padding=5,
    fontsize=20,
    mouse_callbacks={'Button1': open_power},
)

# WIDGETS SECTION END
Exemplo n.º 28
0
import tkinter as tk
import clock as cl
import pages as pg

App = tk.Tk()

#window settings#

App.geometry('1024x600')
App.resizable(0, 0)

App.rowconfigure(0, weight=1)
App.rowconfigure(1, weight=30)

App.columnconfigure(0, weight=1)
App.columnconfigure(1, weight=2)
App.columnconfigure(2, weight=2)

#widgets
clock = cl.Clock(App).clockFrame
clock.grid(row=0, column=1, sticky='news', columnspan=2)

viewer = pg.Viewer()
viewer.grid(row=1, column=0, columnspan=3, sticky='news')

backButton = pg.BackButton(viewer)
backButton.grid(row=0, column=0, sticky='news')

if __name__ == '__main__':
    App.mainloop()
Exemplo n.º 29
0
#
#   Use this program to test your class.

import clock

t1 = clock.Clock(18, 20)
t2 = clock.Clock(3, 47)

added = t1.add(t2)
subtract1 = t1.subtract(t2)
subtract2 = t2.subtract(t1)

print('Added is ', added)  # should print: Added is 2207
print('Subtract smaller is',
      subtract1)  # should print: Subtract smaller is 1433
print('Subtract larger is', subtract2)  # should print: Subtract larger is 1433

mil_string = input('Enter a military time in format hhmm or ENTER to quit: ')
while mil_string != '':
    am_pm_string = input('Enter a time in hh:mm AM/PM format: ')

    t1 = clock.from_military(mil_string)
    t2 = clock.from_am_pm(am_pm_string)
    t3 = t1.add(t2)
    t4 = t1.subtract(t2)
    print('Times are', t1, 'and', t2)
    print('Add result:', t3)
    print('Subtract result:', t4)
    print()

    mil_string = input(
Exemplo n.º 30
0
 def __init__(self, id):
     super(ClockThread, self).__init__()
     self.id = id
     self.clock = clock.Clock([0] * threads)