Esempio n. 1
0
#!/usr/bin/python
from status import Status

print("Demo of enums in python")
print("")

print("Step 1: creating a variable of type Status with value OPEN")
status = Status.OPEN
print("Status: " + str(status))

print("Step 2: Setting the status with a numeric value")
another_status = Status(2)
print(another_status)

print("Step 2: checking the value of the enum variable...")
if status == Status.COMPLETED:
    print("Congrats, the task is completed")
else:
    print("Sorry, the task is not completed yet")

print("Step 3: See all available values for the enumeration status...")
for status in Status:
    print(status)

print("Step 4: accessing the enum by numeric value: Status(1)")
print(Status(1))
print(
    "Step 5: accessing an enum value that does not exist: Status(4) should not exist"
)
try:
    print(Status(4))
Esempio n. 2
0
"""
This module provides the Plugin class, which is the basic
class which encapsulates a single plugin. This is the class
which should be subclassed when creating new plugins.
"""

import sys
from copy import copy
from optparse import Option, OptionParser, make_option
from range import Range, RangeValueError
from response import Response
from status import Status

# Status constants which contain both the status text and the
# exit status associated with them.
OK = Status("OK", 0)
WARNING = Status("WARN", 1)
CRITICAL = Status("CRIT", 2)
UNKNOWN = Status("UNKNOWN", 3)


def check_pynagios_range(option, opt, value):
    """
    This parses and returns the Nagios range value.
    """
    try:
        return Range(value)
    except RangeValueError, e:
        raise OptionValueError("options %s: %s" % (opt, e.message))

Esempio n. 3
0
def run_game():
    pygame.init()
    Kulami_settings = Settings()
    background = pygame.image.load(Kulami_settings.initial_background)
    pygame.display.set_caption("Kulami")
    while True:
        screen = pygame.display.set_mode(
            (background.get_width(), background.get_height()))
        screen.blit(background, (0, 0))
        startbutton = StartButton(screen)
        startbutton.blitme()
        addbutton = AddButton(screen, startbutton)
        addbutton.blitme()
        reducebutton = ReduceButton(screen, startbutton)
        reducebutton.blitme()
        inputfield = InputFiled(screen, addbutton, reducebutton)
        inputfield.blitme()
        stats = Stats()
        font = pygame.font.Font(Kulami_settings.font, 40)
        surface = font.render(str(stats.width), True,
                              Kulami_settings.font_color)
        screen_rect = screen.get_rect()
        screen.blit(
            surface,
            (int(screen_rect.centerx - 0.5 * surface.get_width()),
             int(reducebutton.rect.centery - 0.5 * surface.get_height())))

        while True:
            gf.check_events(stats, startbutton, addbutton, reducebutton)
            # marble.blitme_xy(0,0)
            inputfield.blitme()
            surface = font.render(str(stats.width), True, (154, 202, 64))
            screen.blit(
                surface,
                (int(screen_rect.centerx - 0.5 * surface.get_width()),
                 int(reducebutton.rect.centery - 0.5 * surface.get_height())))
            pygame.display.flip()
            if stats.game_active:
                break
        screen = pygame.display.set_mode(
            (stats.width * Kulami_settings.hole_size,
             stats.height * Kulami_settings.hole_size))
        board = Board(screen, stats.width, stats.height,
                      Kulami_settings.bg_color, Kulami_settings.hole_size,
                      Kulami_settings.tile_edge_color)
        board.blitme()
        pygame.display.flip()
        gameStatus = Status(stats.width, stats.height)
        board.init_board_feature()
        cnnModel = CNNModel(
            Kulami_settings.trainset_address + "_size_" + str(board.width) +
            ".txt", gameStatus, board, Kulami_settings.robot_turn)
        cnnModel.train()
        robot = Robot(gameStatus, board, screen, Kulami_settings.hole_size,
                      "Minmax", Kulami_settings.robot_turn,
                      Kulami_settings.robot_IQ, cnnModel)
        while True:
            if gameStatus.turn == Kulami_settings.robot_turn:
                robot.play()
                continue
            g = bf.check_events(gameStatus, screen, Kulami_settings.hole_size,
                                board)

            pygame.display.flip()
            if gameStatus.end:
                print("Game over")
                print("red score:", gameStatus.red_score, "black score:",
                      gameStatus.black_score)
                if gameStatus.red_score > gameStatus.black_score:
                    print("RED WIN!")
                    gameStatus.result = 0
                elif gameStatus.black_score > gameStatus.red_score:
                    print("BLACK WIN!")
                    gameStatus.result = 1
                else:
                    print("TIE!")
                    gameStatus.result = 2
                break
        result = Result(screen, Kulami_settings.bg_color, gameStatus,
                        Kulami_settings)
        result.blitme()
        restartbutton = RestartButton(screen)
        restartbutton.blitme()
        pygame.display.flip()
        while True:
            g = rf.check_events(stats, restartbutton)
            if stats.game_restart:
                stats.game_restart = False
                break
Esempio n. 4
0
    async def receive_sync(self, request):
        '''
        Update the checkpoint and fill the bubble when receive sync messages.
        input:
            request: {
                'checkpoint': json_data = {
                    'next_slot': self._next_slot
                    'ckpt': json.dumps(ckpt)
                }
                'commit_certificates':commit_certificates
                    (Elements are commit_certificate.to_dict())
            }
        '''
        self._log.info("%d: on receive sync stage.", self._index)
        json_data = await request.json()

        try:
            # print(len(self._status_by_slot))
            # print(self._ckpt.next_slot, self._last_commit_slot + 1)
            # # print(len(json_data['checkpoint']))
            # print('node :' + str(self._index) +' > '+str(self._blockchain.commit_counter)+' : '+str(self._blockchain.length))
            # print()
            # print()
            self.committed_to_blockchain = False
        except Exception as e:
            traceback.print_exc()
            print('for i = ' + str(i))
            print(e)

        self._ckpt.update_checkpoint(json_data['checkpoint'])
        self._last_commit_slot = max(self._last_commit_slot,
                                     self._ckpt.next_slot - 1)
        # TODO: Only check bubble instead of all slots between lowerbound
        # and upperbound of the commit.

        for slot in json_data['commit_certificates']:
            # Skip those slot not qualified for update.
            if int(slot) >= self._ckpt.get_commit_upperbound() or (
                    int(slot) < self._ckpt.next_slot):
                continue

            certificate = json_data['commit_certificates'][slot]
            if slot not in self._status_by_slot:
                self._status_by_slot[slot] = Status(self._f)
                commit_certificate = Status.Certificate(View(
                    0, self._node_cnt))
                commit_certificate.dumps_from_dict(certificate)
                self._status_by_slot[
                    slot].commit_certificate = commit_certificate
            elif not self._status_by_slot[slot].commit_certificate:
                commit_certificate = Status.Certificate(View(
                    0, self._node_cnt))
                commit_certificate.dumps_from_dict(certificate)
                self._status_by_slot[
                    slot].commit_certificate = commit_certificate

        # Commit once the next slot of the last_commit_slot get commit certificate
        while (str(self._last_commit_slot + 1) in self._status_by_slot
               and self._status_by_slot[str(self._last_commit_slot +
                                            1)].commit_certificate):
            self._last_commit_slot += 1

            # When commit messages fill the next checkpoint,
            # propose a new checkpoint.
            if (self._last_commit_slot + 1) % self._checkpoint_interval == 0:
                await self._ckpt.propose_vote(self.get_commit_decisions())

                self._log.info(
                    "%d: During rev_sync, Propose checkpoint with l "
                    "ast slot: %d. In addition, current checkpoint's next_slot is: %d",
                    self._index, self._last_commit_slot, self._ckpt.next_slot)

        await self.dump_to_file()

        return web.Response()
Esempio n. 5
0
def main__1st_run_from_commandline(args=None, debug_in=None):
    args = process_args(args=args)

    # Either read input files, or use the debug_in which should contain config/status in array of strings
    status_file = None
    if debug_in:
        config_file = "__debug__"
        cfg_arr = debug_in["config"]
        sts_arr = debug_in["status"]
    else:
        config_file = ".relay-cfg"
        if args.config_file:
            config_file = args.config_file

        status_file = ".relay-sts"
        if args.status_file:
            status_file = args.status_file

        cfg_arr, sts_arr = read_input_files(config_file, status_file)

    # Process the input information
    control = Control()
    config, status = parse_input_info(cfg_arr, sts_arr, control)
    if config:
        config.filename = config_file
    else:
        print("Parse issue with Config file {} please check and try again".
              format(config_file))
        return relay_exit_codes.EXIT_CODE_ERROR_WITH_CONFIG_FILE, None

    validation_res, text = config.validate()
    app_exit_code = display_validation(validation_res, text, config_file)
    if app_exit_code != relay_exit_codes.EXIT_CODE_OK:
        return app_exit_code, None

    if status:
        status.filename = status_file
    else:
        print("Proceeding with no status file (will create at end)")
        # create status structure for each socket
        status = Status(status_file)

    # process the override comandline options
    new_overrides = process_arg_overrides(args)

    # Parse commandline options for validity
    validation_res, text = validate_args(new_overrides, config)
    if validation_res == relay_exit_codes.EXIT_CODE_CMDLINE_ERROR_UNRECOGNISED_SOCKET:
        print("Unrecognised socket {} in commandline".format(text))
        return validation_res, None

    # now take the info read from the config and status files and process the info
    set_location_coords(config.app.coords)
    ret_code = relay_process(control, config, status, new_overrides)
    if ret_code:
        return ret_code, None

    # re-write the status file
    status.write_file()
    #    if status_file:
    #        #dir_path = os.path.dirname(os.path.realpath(__file__))
    #        full_path = status_file
    #        #full_path = dir_path + '/' + status_file
    #        status.write_file (full_path)

    # configure & start thread to monitor board inputs, only do this
    # if the front panel is present
    if config.app.front_panel_present:
        thread = threading.Thread(target=update_board_inputs,
                                  args=(control, config, status))
        thread.start()

    # Now see if we want to run the app continously
    if config.app:
        if config.app.update_timer != App.APP_SINGLE_RUN_TIMER:
            # Now see if we want to run up the web server and or the socket
            if config.app.socket_active:
                # Start the socket used for controlling the app
                pass
            if config.app.webserver_active:
                # Start the webserver used for controlling the app
                #thread = threading.Thread(target=websrv_01.run, kwargs={'port': config.app.webserver_port,'debug': True})
                webserver_set_config_status(control, config, status,
                                            relay_process)
                thread = threading.Thread(target=web_svr.run,
                                          kwargs={
                                              'host': '0.0.0.0',
                                              'port': config.app.webserver_port
                                          })
                thread.start()
                pass

            # schedule a timer to kick the logic processing
            update_time = config.app.update_timer
            if args.super_time:
                update_time = config.app.update_timer / args.super_time
            control.schedule_run(update_time)
            # configure & start thread
            thread = threading.Thread(target=main__run_from_scheduler,
                                      args=(control, config, status))
            thread.start()

    if args.super_time:
        st_args = [control, args.super_time]
        st_thread = threading.Thread(target=supertime_change_time,
                                     args=st_args)
        st_thread.start()


#    #For debugging the image drawing
#    # Prep the filename of the image generated
#    multi_day = "/home/marc/temp/mja02.png"
#
#    # generate the image
#    start_date = time_now() - timedelta(days = 100)
#    end_date = time_now() + timedelta(days = 100)
#    from print_utils import print_days_image
#    print_days_image(multi_day, start_date, end_date, config, "SnugLHS", day_height=2, strobe=7)

    return relay_exit_codes.EXIT_CODE_OK, control
Esempio n. 6
0
 def say(self, message):
     statement = "%s said: %s" % (self, message)
     if self.statusQueue:
         self.statusQueue.put(Status(self.name, message))
     else:
         print(statement)
Esempio n. 7
0
    def __init__(self, master, camera, uart):
        """Create a main application with the root thread, camera, and
        UART instances."""

        # Member Data
        #######################################################
        self.tracker = CentroidTracker()
        self.controller = Controller()
        self.test = "alnilam"
        self.status = Status()
        self.threshold = 5
        self.camera = camera
        self.UART = uart

        # GUI Status Data
        #######################################################
        self.exposing = False
        self.calibrating = False
        self.calibrated = False
        self.running = False

        # Calibration Data
        #######################################################
        self.calibration = Calibration()

        # Primary GUI Objects
        #######################################################
        # master root frame
        self.master = master

        # self.img - cv2 binary image without any markup
        # self.gui_img - PIL colored image with markup
        self.img, self.gui_img = initial_img_load(self.tracker)

        # Holds image frame
        self.panel = Label(master, image=self.gui_img)
        self.panel.pack(side=LEFT)

        # Contains all control and output widgets right of image panel
        self.frame = Frame(master)
        self.frame.pack(side=RIGHT, expand=TRUE, fill=BOTH)

        # data that contains calibration and guiding status data
        self.status_txt = StringVar()
        self.status_txt.set(self.tracker.status)

        # GUI object containing status data
        self.text = Label(self.frame, textvariable=self.status_txt)
        self.text.config(height=10,
                         width=32,
                         justify="left",
                         bg="grey25",
                         fg="white")
        self.text.pack()

        # Secondary GUI Objects (widgets)
        #######################################################
        # load Astrothoughts Logo
        self.logo_img = load_logo()
        self.logo = Label(self.frame, image=self.logo_img)
        self.logo.pack(side=BOTTOM, anchor=S)

        # Binary threshold slider
        self.slider = Scale(self.frame,
                            from_=0,
                            to=200,
                            orient=HORIZONTAL,
                            length=225)
        self.slider.config(sliderlength=15,
                           label="Binary Threshold",
                           bg="grey25",
                           fg="white")
        self.slider.set(5)
        self.slider.pack()

        # Loop button
        self.expose_img = PhotoImage(file="figures/expose.png")
        self.expose_btn = Button(self.frame,
                                 image=self.expose_img,
                                 command=self.expose_button_cb)
        self.expose_btn.config(height=51, width=51, bg="white")
        self.expose_btn.pack(side="left", anchor=NW)
        self.expose_ttp = CreateToolTip(
            self.expose_btn, "Begin looping exposures from tracking camera")

        # Run button
        self.run_img = PhotoImage(file="figures/run_gs.png")
        self.run_btn = Button(self.frame,
                              image=self.run_img,
                              command=self.run_button_cb)
        self.run_btn.config(height=51, width=51, bg="white")
        self.run_btn.pack(side="left", anchor=NW)
        self.run_ttp = CreateToolTip(self.run_btn, "Start autoguiding program")

        # Stop button
        self.stop_img = PhotoImage(file="figures/stop_gs.png")
        self.stop_btn = Button(self.frame,
                               image=self.stop_img,
                               command=self.stop_button_cb)
        self.stop_btn.config(height=51, width=51, bg="white")
        self.stop_btn.pack(side="left", anchor=NW)
        self.stop_ttp = CreateToolTip(self.stop_btn,
                                      "Stop looping and guiding")

        # Calibration button
        self.cal_img = PhotoImage(file="figures/cal_gs.png")
        self.cal_btn = Button(self.frame,
                              image=self.cal_img,
                              command=self.cal_button_cb)
        self.cal_btn.config(height=51, width=51, bg="white")
        self.cal_btn.pack(side="left", anchor=NW)
        self.cal_ttp = CreateToolTip(self.cal_btn,
                                     "Begin calibration sequence")
Esempio n. 8
0
    def test_str(self):
        # Testing __str__
        s = Status(Status.INIT)
        s = Status.WAIT

        assert str(s) == 'W', 'should be W'
Esempio n. 9
0
    def __init__(self):
        """
        This method is constructor.
        """
        System()
        Gtk.Window.__init__(self, title="Mosaicode")
        # self.set_default_size(800,600)
        self.resize(
            System.properties.width,
            System.properties.height)
        self.main_control = MainControl(self)
        self.connect("check-resize", self.__resize)

        # GUI components
        self.menu = Menu(self)
        self.toolbar = Toolbar(self)
        self.search = SearchBar(self)
        self.block_notebook = BlockNotebook(self)
        self.block_properties = BlockProperties(self)
        self.work_area = WorkArea(self)
        self.status = Status(self)
        System.set_log(self.status)

        # vbox main
        # -----------------------------------------------------
        # | Menu
        # -----------------------------------------------------
        # | Toolbar
        # -----------------------------------------------------
        # | V Paned bottom
        # -----------------------------------------------------

        # First Vertical Box
        vbox_main = Gtk.VBox()
        self.add(vbox_main)
        vbox_main.pack_start(self.menu, False, True, 0)
        vbox_main.pack_start(self.toolbar, False, False, 0)
        self.vpaned_bottom = Gtk.Paned.new(Gtk.Orientation.VERTICAL)
        vbox_main.add(self.vpaned_bottom)

        # vpaned_bottom
        # -----------------------------------------------------
        # | hpaned_work_area
        # =====================================================
        # | status
        # -----------------------------------------------------

        self.hpaned_work_area = Gtk.HPaned()
        self.hpaned_work_area.connect("accept-position", self.__resize)
        self.hpaned_work_area.set_position(System.properties.hpaned_work_area)

        self.vpaned_bottom.add1(self.hpaned_work_area)
        self.vpaned_bottom.add2(self.__create_frame(self.status))
        self.vpaned_bottom.set_position(System.properties.vpaned_bottom)
        self.vpaned_bottom.set_size_request(50, 50)

        # hpaned_work_area
        # -----------------------------------------------------
        # | vbox_left      ||   work_area
        # -----------------------------------------------------
        vbox_left = Gtk.VBox(False, 0)
        self.hpaned_work_area.add1(vbox_left)
        self.hpaned_work_area.add2(self.work_area)

        # vbox_left
        # -----------------------------------------------------
        # |search
        # -----------------------------------------------------
        # |vpaned_left
        # -----------------------------------------------------

        vbox_left.pack_start(self.search, False, False, 0)
        self.vpaned_left = Gtk.VPaned()
        vbox_left.pack_start(self.vpaned_left, True, True, 0)

        # vpaned_left
        # -----------------------------------------------------
        # |blocks_tree_view
        # =====================================================
        # | block_properties
        # -----------------------------------------------------

        self.vpaned_left.add1(self.__create_frame(self.block_notebook))
        self.vpaned_left.add2(self.__create_frame(self.block_properties))
        self.vpaned_left.set_position(System.properties.vpaned_left)

        self.connect("delete-event", self.main_control.exit)
        self.connect("key-press-event", self.__on_key_press)

        for example in System.list_of_examples:
            self.menu.add_example(example)
        self.menu.update_recent_file()
 def __valid_username(self, username: str):
     if username not in self.users:
         return Status(499, "User not found")
     return Status(200, "success")
Esempio n. 11
0
'''Stater of game'''
from colorama import init
from status import Status

init()


STATUS = Status()
STATUS.make_game()
Esempio n. 12
0
    def __init__(self):
        s2idirectory.load()
        Gtk.Window.__init__(self, title="Harpia")
        #self.set_default_size(800,600)
        self.set_property("height_request", 500)
        self.maximize()
        self.set_size_request(900, 500)  #Controla o tamanho minimo
        self.main_control = MainControl(self)
        self.connect("check-resize", self.__resize)

        #GUI components
        self.menu = Menu(self)
        self.toolbar = Toolbar(self)
        self.search = SearchBar(self)
        self.blocks_tree_view = BlocksTreeView(self)
        self.block_properties = BlockProperties(self)
        self.work_area = WorkArea(self)
        self.status = Status(self)
        s2idirectory.Log = self.status

        # vbox main
        # -----------------------------------------------------
        # | Menu
        # -----------------------------------------------------
        # | Toolbar
        # -----------------------------------------------------
        # | V Paned bottom
        # -----------------------------------------------------

        # First Vertical Box
        vbox_main = Gtk.VBox()
        self.add(vbox_main)
        vbox_main.pack_start(self.menu, False, True, 0)
        vbox_main.pack_start(self.toolbar, False, False, 0)
        self.vpaned_bottom = Gtk.Paned.new(Gtk.Orientation.VERTICAL)
        vbox_main.add(self.vpaned_bottom)

        # vpaned_bottom
        # -----------------------------------------------------
        # | hpaned_work_area
        # =====================================================
        # | status
        # -----------------------------------------------------

        hpaned_work_area = Gtk.HPaned()
        self.vpaned_bottom.add1(hpaned_work_area)
        self.vpaned_bottom.add2(self.__create_frame(self.status))
        self.vpaned_bottom.set_position(420)
        self.vpaned_bottom.set_size_request(50, 50)

        # hpaned_work_area
        # -----------------------------------------------------
        # | vbox_left      ||   work_area
        # -----------------------------------------------------
        vbox_left = Gtk.VBox(False, 0)
        hpaned_work_area.add1(vbox_left)
        hpaned_work_area.add2(self.work_area)

        # vbox_left
        # -----------------------------------------------------
        # |search
        # -----------------------------------------------------
        # |vpaned_left
        # -----------------------------------------------------

        vbox_left.pack_start(self.search, False, False, 0)
        self.vpaned_left = Gtk.VPaned()
        vbox_left.pack_start(self.vpaned_left, True, True, 0)

        # vpaned_left
        # -----------------------------------------------------
        # |blocks_tree_view
        # =====================================================
        # | block_properties
        # -----------------------------------------------------

        self.vpaned_left.add1(self.__create_frame(self.blocks_tree_view))
        self.vpaned_left.add2(self.__create_frame(self.block_properties))
        self.vpaned_left.set_position(300)
        #self.vpaned_left.set_size_request(50,50)
        #self.vpaned_left.set_property("min-position",150)

        self.connect("delete-event", self.quit)

        # Load Examples
        list_of_examples = glob(os.environ['HARPIA_DATA_DIR'] + "examples/*")
        list_of_examples.sort()

        for example in list_of_examples:
            self.menu.add_example(example)

        self.menu.add_recent_file("/home/flavio/Desktop/harpiaTest.hrp")
        self.menu.add_recent_file("/home/flavio/Desktop/harpiaTest2.hrp")
Esempio n. 13
0
from status import Status

etat = Status("http://pf4.ddns.net/api/etat_bots.json")

print(etat.get_status("fire dragon#8794"))
Esempio n. 14
0
 def __init__(self, title=None, status=None):
     self.title = title if title else ""
     self.status = status if status else Status()
Esempio n. 15
0
def main():
    try:
        parser = argparse.ArgumentParser(description='Parser')
        parser.add_argument('--rowfile', help='row file')
        parser.add_argument('--colfile', help='column file', default=None)
        parser.add_argument('--outfile', help='output file')
        parser.add_argument('--pearson',
                            dest='spearman',
                            help='use pearson correlation',
                            action='store_false')
        parser.add_argument('--pvalue',
                            help='p-value threshold',
                            type=float,
                            default=None)
        parser.add_argument('--rho',
                            help='correlation (rho) threshold',
                            type=float,
                            default=None)
        parser.add_argument('--loglevel', help='set log level', default='info')
        parser.add_argument('--logfile', help='set log file', default=None)
        args = parser.parse_args()

        level = args.loglevel.upper()
        try:
            level = getattr(log, level)
        except AttributeError:
            level = log.INFO

        if args.logfile is not None:
            try:
                os.makedirs(os.path.dirname(args.logfile))
            except OSError:
                pass

        log.getLogger().handlers = []
        log.basicConfig(
            level=level,
            filename=args.logfile,
            format='%(asctime)s.%(msecs)d %(levelname)s: %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')

        log.info('row file is %s', args.rowfile)
        log.info('column file is %s', args.colfile)
        log.info('output file is %s', args.outfile)
        log.info('spearman is %s', args.spearman)
        log.info('p-value threshold is %s', args.pvalue)
        log.info('rho threshold is %s', args.rho)
        log.info('log level is %s (%d)', args.loglevel, level)
        log.info('log file is %s', args.logfile)

        status = Status(name='correlator').start()
        correlate(args.outfile,
                  args.rowfile,
                  args.colfile,
                  spearman=args.spearman,
                  pvalue_threshold=args.pvalue,
                  rho_threshold=args.rho)
        status.stop()

        return 0
    except KeyboardInterrupt:
        return 1
    except Exception, e:
        sys.stderr.write(repr(e) + '\n')
        sys.stderr.write('for help use --help\n')
        return 2
Esempio n. 16
0
 def __init__(self):
     self.status = Status()
     self.choices = {"1": self.show_ip, "2": self.show_page, "3": self.quit}
Esempio n. 17
0
def correlate(outfile,
              row_filename,
              col_filename=None,
              spearman=True,
              pvalue_threshold=None,
              rho_threshold=None):

    row_row_names, row_col_names, row_data = parse(row_filename)

    if col_filename is None:
        col_filename = row_filename

    symmetric = row_filename == col_filename

    if not symmetric:
        col_row_names, col_col_names, col_data = parse(col_filename)

        col_names = set(row_col_names).intersection(col_col_names)

        row_data = align(col_names, row_col_names, row_data)
        col_data = align(col_names, col_col_names, col_data)

        col_row_names, col_data = prune(col_row_names, col_data)
        ncols = len(col_row_names)

    row_row_names, row_data = prune(row_row_names, row_data)
    nrows = len(row_row_names)

    if symmetric:
        col_row_names, col_data, ncols = row_row_names, row_data, nrows

    if nrows == 0 or ncols == 0:
        return

    if spearman:
        status = Status('ranking for spearman correlation').start()
        row_data = np.array([rankdata(r) for r in row_data])
        col_data = row_data if symmetric else np.array(
            [rankdata(c) for c in col_data])
        status.stop()

    if symmetric:

        def complete(r):
            return r * (r - 1) / 2 + r * (nrows - r)
    else:

        def complete(r):
            return r * ncols

    status = Status('writing ' + outfile).n(
        complete(nrows)).units('correlations').start()

    try:
        os.makedirs(os.path.dirname(outfile))
    except:
        pass

    with open(outfile, 'wt') as fid:
        for r in xrange(nrows):
            for c in xrange(r + 1 if symmetric else 0, ncols):
                (rho, pvalue) = pearsonr(row_data[r], col_data[c])
                if (rho_threshold is None or math.fabs(rho) > rho_threshold
                    ) and (pvalue_threshold is None
                           or pvalue < pvalue_threshold):
                    fid.write(
                        '%s\t%s\t%0.3e\t%0.3e\n' %
                        (row_row_names[r], col_row_names[c], rho, pvalue))
            status.log(complete(r))

    status.stop()
Esempio n. 18
0
 def __init__(self, status = Status(), header = Header(), body = ''): #Body()):
     self.status = status
     self.header = header
     self.body = body
Esempio n. 19
0
    def __init__(self, clientName, password='', run=True, **jsonConfigKeysToOverride):

        self.clientName = clientName
        self.password = password
        self.isrunning = run
        self.localTimestamp = time()
        self.localDateTime = datetime.fromtimestamp(self.localTimestamp)

        logMessage = f'\n\n{self.localDateTime}\nSession created with "{self.clientName}" credentials and run = {run}'
        log.event_log_append(logMessage)
        log.raw_log_append(logMessage)

        """
        with open(paths.clientConfig, 'r') as f:
            jsonClientConfig = json.load(f)
        self.clientData = jsonClientConfig[client_name] 
        """

        with open(paths.sessionConfig, 'r') as f:
            jsonSessionConfig = json.load(f)
        for key in jsonConfigKeysToOverride:
            jsonSessionConfig[key] = jsonConfigKeysToOverride[key]

        self.marketsBuffer = jsonSessionConfig["sessionData"]["marketsBuffer"]
        markets_buffer_format_check(self.marketsBuffer)
        self.marketsBuffer = remove_inactive_markets_from_buffer(self.marketsBuffer)
        self.marketsBuffer = marketsBufferAmountsSplitting(self.marketsBuffer)

        # RESTRICTIONS TO BE IMPLEMENTE IN STATUS, NOT HERE!!!!!!

        # statuses = [] # [ID, runningOrClosed, crashingInfo, *args]

        wait = DEFAULT_WAIT
        if self.isrunning:
            self.sessionID = ID("session")
            logMessage = f'Session has started with session ID: {self.sessionID.partialID}.\n'
            log.event_log_append(logMessage)
            log.raw_log_append(logMessage)
        while self.isrunning:
            log.event_log_append('\nCurrent marketsBuffer = ', self.marketsBuffer)
            try:
                newStatus = Status(self.clientName, self.password, self.marketsBuffer[0])
                wait = DEFAULT_WAIT
            except IDOverflowError:
                self.statusIDReset = ID("status", getNew=False, reset=True)
                self.isrunning = False
                logMessage = f'\nSession terminated for statusID overflow.\n'
                log.event_log_append(logMessage)
                log.raw_log_append(logMessage)
                break
            except Exception as err:
                if wait < MAX_WAIT:
                    wait *= WAIT_MULTIPLIER_0
                logMessage = f'\nStatus crashed with error:\n    {err.__repr__()}\n'
                log.event_log_append(logMessage)
                log.raw_log_append(logMessage)
                log.error_log_append(err.__repr__(), self.sessionID.partialID, ID("status", getNew=False, reset=False).partialID)

            #if newStatus.getMarketData() is different from marketData, update sessionConfig.json
            try: self.lastMarket = newStatus.getMarketData()
            except: self.lastMarket = self.marketsBuffer[0]
            if len(self.marketsBuffer) > 1:
                self.marketsBuffer = self.marketsBuffer[1:]
                self.marketsBuffer.append(self.lastMarket)
            sleep(wait)
Esempio n. 20
0
    def __init__(self):
        """
        This method is constructor.
        """
        System()
        Gtk.Window.__init__(self, title="Mosaicode")
        self.resize(System.get_preferences().width,
                    System.get_preferences().height)
        self.main_control = MainControl(self)

        # GUI components
        self.menu = Menu(self)
        self.toolbar = Toolbar(self)
        self.search = SearchBar(self)
        self.block_notebook = BlockNotebook(self)
        self.property_box = PropertyBox(self)
        self.work_area = WorkArea(self)
        self.status = Status(self)
        self.diagram_menu = DiagramMenu()
        self.menu.add_help()

        System.set_log(self.status)

        # vbox main
        # -----------------------------------------------------
        # | Menu
        # -----------------------------------------------------
        # | Toolbar
        # -----------------------------------------------------
        # | V Paned bottom
        # -----------------------------------------------------

        # First Vertical Box
        vbox_main = Gtk.VBox()
        self.add(vbox_main)
        vbox_main.pack_start(self.menu, False, True, 0)
        vbox_main.pack_start(self.toolbar, False, False, 0)
        self.vpaned_bottom = Gtk.Paned.new(Gtk.Orientation.VERTICAL)
        vbox_main.add(self.vpaned_bottom)

        # vpaned_bottom
        # -----------------------------------------------------
        # | hpaned_work_area
        # =====================================================
        # | status
        # -----------------------------------------------------

        self.hpaned_work_area = Gtk.HPaned()
        self.hpaned_work_area.connect("accept-position", self.__resize)
        self.hpaned_work_area.set_position(
            System.get_preferences().hpaned_work_area)

        self.vpaned_bottom.add1(self.hpaned_work_area)
        self.vpaned_bottom.add2(self.__create_frame(self.status))
        self.vpaned_bottom.set_position(System.get_preferences().vpaned_bottom)
        self.vpaned_bottom.set_size_request(50, 50)

        # hpaned_work_area
        # -----------------------------------------------------
        # | vbox_left      ||   work_area
        # -----------------------------------------------------
        vbox_left = Gtk.VBox(False, 0)
        self.hpaned_work_area.add1(vbox_left)
        self.hpaned_work_area.add2(self.work_area)

        # vbox_left
        # -----------------------------------------------------
        # |search
        # -----------------------------------------------------
        # |vpaned_left
        # -----------------------------------------------------

        vbox_left.pack_start(self.search, False, False, 0)
        self.vpaned_left = Gtk.VPaned()
        vbox_left.pack_start(self.vpaned_left, True, True, 0)

        # vpaned_left
        # -----------------------------------------------------
        # |blocks_tree_view
        # =====================================================
        # |property_box
        # -----------------------------------------------------

        self.vpaned_left.add1(self.__create_frame(self.block_notebook))
        self.vpaned_left.add2(self.__create_frame(self.property_box))
        self.vpaned_left.set_position(System.get_preferences().vpaned_left)

        self.connect("key-press-event", self.__on_key_press)
        self.connect("check-resize", self.__resize)

        self.main_control.init()
Esempio n. 21
0
    async def reply(self, request):
        '''
        Once receive more than 2f + 1 commit message, append the commit 
        certificate and cannot change anymore. In addition, if there is 
        no bubbles ahead, commit the given slots and update the last_commit_slot.
        input:
            request: commit message from commit:
                preprepare_msg = {
                    'index': self._index,
                    'n': self._n,
                    'proposal': {
                        this_slot: json_data
                    }
                    'type': 'commit'
                }
        '''

        json_data = await request.json()
        # self._log.info(" %d: on reply", self._index)
        # print("\t--->node "+str(self._index)+": on reply ")

        if json_data['view'] < self._follow_view.get_view():
            # when receive message with view < follow_view, do nothing
            return web.Response()

        self._log.info(" %d: receive commit msg from %d", self._index,
                       json_data['index'])

        for slot in json_data['proposal']:
            if not self._legal_slot(slot):
                self._log.error("%d: message %s not in valid slot",
                                self._index, json_data)
                continue

            if slot not in self._status_by_slot:
                self._status_by_slot[slot] = Status(self._f)
            status = self._status_by_slot[slot]

            view = View(json_data['view'], self._node_cnt)

            status._update_sequence(json_data['type'], view,
                                    json_data['proposal'][slot],
                                    json_data['index'])

            # Commit only when no commit certificate and got more than 2f + 1
            if not status.commit_certificate and status._check_majority(
                    json_data['type']):
                status.commit_certificate = Status.Certificate(
                    view, json_data['proposal'][slot])

                self._log.debug("Add commit certifiacte to slot %d", int(slot))

                # Reply only once and only when no bubble ahead
                if self._last_commit_slot == int(
                        slot) - 1 and not status.is_committed:

                    status.is_committed = True
                    self._last_commit_slot += 1
                    if not self._is_leader:
                        self._next_propose_slot += 1

                    #    When commit messages fill the next checkpoint, propose a new checkpoint.
                    if (self._last_commit_slot +
                            1) % self._checkpoint_interval == 0:
                        self._log.info(
                            "%d: Propose checkpoint with last slot: %d. "
                            "In addition, current checkpoint's next_slot is: %d",
                            self._index, self._last_commit_slot,
                            self._ckpt.next_slot)
                        await self._ckpt.propose_vote(
                            self.get_commit_decisions())

                    if (self._last_commit_slot + 1) % self._dump_interval == 0:
                        await self.dump_to_file()

                    reply_msg = {
                        'index': self._index,
                        'view': json_data['view'],
                        'proposal': json_data['proposal'][slot],
                        'type': MessageType.REPLY
                    }
                    try:
                        await self._session.post(
                            json_data['proposal'][slot]['client_url'],
                            json=reply_msg)
                    except:
                        self._log.error(
                            "Send message failed to %s",
                            json_data['proposal'][slot]['client_url'])
                        pass
                    else:
                        self._log.info(
                            "%d reply to %s successfully!!", self._index,
                            json_data['proposal'][slot]['client_url'])

        return web.Response()
Esempio n. 22
0
 def update(self):
     z = self.vehicle.z
     self.vehicle.front_estimated_status = Status(*z[:3])
     self.vehicle.estimated_status = Status(*z[3:6])
     self.vehicle.front_estimated_diff = Status(*z[6:9])
Esempio n. 23
0
import json

with open("config.json") as file:
    json_data = json.load(file)


def job():
    status.get_groups_handler()
    status.format_link()

    status.run()

    send.send_string(status.display_result())


status = Status(json_data["url"], json_data["groups"]["groups_num"])
status.get_groups_handler()
status.format_link()

status.run()
status.display_result()

send = Send(json_data["serial"]["interface"], json_data["serial"]["baud_rate"])

schedule.every(1).seconds.do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

send.close()
Esempio n. 24
0
#!/usr/bin/env python2.6

import datetime, json, sys, time, web
from threading import Thread
from status import Status

## "local" imports
import checks

## we'll factor this stuff out later

urls = ("/status.(json|xml)", "status", "/status", "status", "/checkin(.*)",
        "checkin", "/healthcheck", "healthcheck", "/(.*)", "default")

app = web.application(urls, globals())
global_status = Status()


class checkin:
    ## currently we only support HTTP and TCP health checks,
    ## and we always pass web.input().get("path") to the healthcheck.
    ## there's probably a better way to do this.
    HEALTH_CHECKS = {
        "tcp": checks.TcpHealthCheck,
        "http": checks.HttpHealthCheck
    }

    def GET(self, *args):
        data = web.input(host=None, port=None, healthCheck=None)
        if data.host is None or data.port is None:
            return json.dumps({
Esempio n. 25
0
def main():
    import argparse
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--save_dir', type = str, help='where is the model saved', default="GPO5/mix20_120")
    parser.add_argument('--best_model', type = int, help="the index of the best model (-1 for unknown)", default = -1)
    parser.add_argument('--status_file', type = str, help="which file keeps a record of the status", default = "status.pkl")
    parser.add_argument('--result_file', type = str, help="this file keeps the performance of models on testing files", default = "result.pkl")
    parser.add_argument('--dump_dir', type = str, help="where to save (state, Pi, num_step) for SL", default = "parameters/")
    parser.add_argument('--dump_file', type = str, help="what is the filename to save (state, Pi, num_step) for SL", default="sl.pkl")
    parser.add_argument('--train_path', type = str, help='where are training files', default="satProb/mix20_train32/")
    parser.add_argument('--test_path', type = str, help='where are test files', default="satProb/mix20_test200/")

    parser.add_argument('--max_clause', type = int, help="what is the max_clause", default=120)
    parser.add_argument('--max_var', type = int, help="what is the max_var", default=20)
    parser.add_argument('--sl_buffer_size', type = int, help="max size of sl buffer", default = 1000000)
    parser.add_argument('--nbatch', type = int, help="what is the batch size to use", default = 32)
    parser.add_argument('--nstack', type = int, help="how many layers of states to use", default = 1)
    parser.add_argument('--nrepeat', type = int, help="how many times to repeat a SAT problem", default= 100)
    parser.add_argument('--n_start', type = int, help="which file index to start with (for running)", default = 0)
    parser.add_argument('--n_train_files', type = int, help="total number of training files", default = 0) # calculated later 
    parser.add_argument('--n_test_files', type = int, help="total number of testing files", default = 0) # calculated later

    parser.add_argument('--l2_coeff', type = float, help="the coefficient for l2 regularization", default = 0.0001)
    parser.add_argument('--sl_num_steps', type = int, help="how many times to do supervised training", default = 64000)
    parser.add_argument('--sl_nbatch', type = int, help="what is the batch size for supervised training", default = 32)
    parser.add_argument('--sl_ncheckpoint', type = int, help="how often to checkpoint a supervised trained model", default =32000)
    parser.add_argument('--n_cycles', type = int, help="how many cycles of self_play -> super_train -> model_ev do we want to run", default = 2)
    parser.add_argument('--show_only', type = str, help="if only show the result", default="No")
    parser.add_argument('--which_cycle', type = int, help="which cycle are we in now", default = 0)

    args = parser.parse_args()
    args.n_train_files = len([f for f in os.listdir(args.train_path) if os.path.isfile(os.path.join(args.train_path, f))]) # total number of training files
    args.n_test_files  = len([f for f in os.listdir(args.test_path)  if os.path.isfile(os.path.join(args.test_path,  f))]) # total number of testing files
    args.dump_dir = args.save_dir # all files related to this project are saved in save_dir, so dump_dir is useless
    os.makedirs(args.save_dir, exist_ok = True)

    # start the status_track for these operations
    status_track = Status()
    if os.path.isfile(os.path.join(args.save_dir, args.status_file)):
        status_track.start_with(os.path.join(args.save_dir, args.status_file))
    else: # otherwise the initial values in Status object fits with the default values here;
        status_track.init_with(args.best_model, args.n_start, [], 0, os.path.join(args.save_dir, args.status_file), args)
    status_track.show_itself()

    # following code evaluates the performance of models on testing files
    result_track = Status()
    if os.path.isfile(os.path.join(args.save_dir, args.result_file)):
        result_track.start_with(os.path.join(args.save_dir, args.result_file))
    else: # otherwise initilize values in Status object with the "total model number" --> "length_hist field" of status_track
        result_track.init_with(-1, 0, [], 0, os.path.join(args.save_dir, args.result_file))

    if args.show_only == "Yes":
       status_track.show_itself()
       status_track.print_all_models_performance()
       result_track.show_itself()
       result_track.print_all_models_performance()
       return

    # build the model for all three functions
    built_model = build_model(args, scope = "mcts")

    # run a specific file that has bugs
#    ev_ss(args, built_model, status_track, 0)
#    return
#    model_ev(args, built_model, status_track)
#    status_track.show_itself()
#    return
#    result_track.set_same_length_hist(status_track)
#    model_ev(args, built_model, result_track, ev_testing = True)
#    result_track.show_itself()
#    return

    # run args.n_cycles number of iteration (self_play -> super_train -> model_ev)
    for i in range(args.n_cycles):
        args.which_cycle = i
        self_play(args, built_model, status_track)
        status_track.show_itself()
        super_train(args, built_model, status_track)
        status_track.show_itself()
        model_ev(args, built_model, status_track)
        result_track.set_same_length_hist(status_track)
        model_ev(args, built_model, result_track, ev_testing = True)
        status_track.show_itself()

    # print the performance of all models we have so far:
    status_track.print_all_models_performance()
    result_track.print_all_models_performance()
    return
Esempio n. 26
0
 def status(self, status):
     self._status = Status(status)
Esempio n. 27
0
# Python module imports.
import wx
from wx.lib import buttons, scrolledpanel

# relax module imports.
from data_store import Relax_data_store; ds = Relax_data_store()
from graphics import IMAGE_PATH, fetch_icon
from gui.fonts import font
from gui.icons import relax_icons
from gui.interpreter import Interpreter; interpreter = Interpreter()
from gui.misc import add_border, bitmap_setup
from gui.string_conv import float_to_gui, str_to_gui
from lib.check_types import is_float
from lib.errors import RelaxImplementError
from status import Status; status = Status()


# The wx ID for the special accelerator table that allows the ESC button to close relax wizards.
ESC_ID = wx.NewId()



class Wiz_page(wx.Panel):
    """The wizard pages to be placed inside the wizard.

    To inherit from this class, you must minimally supply the add_contents() method.  This method should build the specific GUI elements.  The following methods are also designed to be overwritten:

        - add_artwork(), this builds the left hand artwork section of the page.
        - add_contents(), this builds the right hand section of the page.
        - on_display(), this is executed when the page is displayed.
Esempio n. 28
0
	def execute(self):
		Db().reset()
		Status().execute()
Esempio n. 29
0
"""Script for CPMG relaxation dispersion curve fitting using Dr. Flemming Hansen's data from http://dx.doi.org/10.1021/jp074793o.

To run:

$ ../../../../../relax --tee relax_disp.log relax_disp.py
"""

# Python module imports.
from os import sep

# relax module imports.
from auto_analyses.relax_disp import Relax_disp
from data_store import Relax_data_store
ds = Relax_data_store()
from status import Status
status = Status()

# The dispersion models.
MODELS = ['R2eff', 'LM63 3-site']

# The grid search size (the number of increments per dimension).
GRID_INC = 11

# The number of Monte Carlo simulations to be used for error analysis at the end of the analysis.
MC_NUM = 50

# Create the data pipe.
pipe_name = 'base pipe'
pipe_bundle = 'relax_disp'
pipe.create(pipe_name=pipe_name, bundle=pipe_bundle, pipe_type='relax_disp')
Esempio n. 30
0
 def get_user_status(self):
     response = requests.get(url=self.url, params=self.params).json()
     return Status(response)