Пример #1
0
 def ImportFromCvs(self,event,type):
     msg = "Screen solutions and reservoir information will be deleted!\n\n"\
                        "Importing from cvs (comma separated) text file.\n"\
                        "Lines starting with '#' will be ignored.\n"\
                        "Lines starting with '>' will be treated as headings.\n"
     if type == "formulations":
         msg += "The field 'SolutionNr' references the number of the solution in the original screen.\n"\
                "The 'Position' field specifies the well position in the new screen."
     d = wx.MessageBox(msg, "Confirm", wx.YES_NO, self)
     if d == wx.YES:
         dir = self.controller.userData.GetValue("LastDir")
         dlg = wx.FileDialog(
             self, message="Choose cvs file", defaultDir=dir, 
             defaultFile="", style=wx.OPEN | wx.CHANGE_DIR
             )
         # Show the dialog and retrieve the user response. If it is the OK response, 
         # process the data.
         if dlg.ShowModal() == wx.ID_OK:
             self.controller.userData.SetValue("LastDir", os.getcwd())
             # This returns a Python list of files that were selected.
             path = dlg.GetPath()
             if os.access(path, os.F_OK):
                         from util.converter import Converter
                         converter = Converter(path, self.data)
                         if type == "formulations":
                             converter.convert()
                         elif type == "stocks":
                             converter.convertStocks()
                         elif type == "screen":
                             converter.convertSimplexScreen()
                         self.data.UpdateEventListeners(["reagents","screen"],self)
                         self.data.InitReservoirsFromScreen()
                         self.xtal_panel.tray.RefreshWells()
                         self.screen_panel.tray.RefreshWells()
                         self.data.UpdateEventListeners(["front"],self)
Пример #2
0
 def Run(self):
     results.write("*************\nTesting Converter ... \n")
     results.write("New Screen from scratch ... ")
     name = "Hampton Crystal Screen - Test Conversion"
     noRows = 4
     noCols = 6
     noDrops = 1
     newScreen = {"ScreenName": name, "NoRows": noRows, \
                 "NoCols":noCols, "NoDrops":noDrops}
     contlr = controller.Controller(None)
     data = contlr.NewTray(None,(None,newScreen))
     from util.converter import Converter
     converter = Converter(files + "/hampton_crystal_screen2_25-48.csv", data)
     results.write("New screen before import:\n")
     results.write(data.GetSummary())
     converter.convert()
     results.write("Screen after import:\n")
     results.write(data.GetSummary())
     newFile = os.path.abspath(files + "/CrystalScreenConverted.exp")
     data.Save(newFile)
     # testing import for stock solution only
     results.write("Importing stock solutions only...\n")
     converter = Converter(files + "/simplex_Stocks.csv", data)
     converter.convertStocks()
     results.write("Screen after import:\n")
     results.write(data.GetSummary())
     newFile = os.path.abspath(files + "/CrystalScreenStocksConverted.exp")
     data.Save(newFile)
     # testing for screen solutions from simplex output
     results.write("Importing simplex screen solutions only...\n")
     converter = Converter(files + "/simplex_screen.csv", data)
     converter.convertSimplexScreen()
     results.write("Screen after import:\n")
     results.write(data.GetSummary())
     newFile = os.path.abspath(files + "/CrystalScreenSimplexConverted.exp")
     data.Save(newFile)
     # removing unused reagents
     results.write("Removing unused reagents...\n")
     data.RemoveUnusedReagents()
     results.write(data.GetSummary())
     data.Close()
     self.datafile = newFile
     #data = contlr.GetTrayData(None,newFile)
     frame = self.StartGui()
Пример #3
0
 def __init__(self, reactor):
     super(RobotManager, self).__init__(reactor)
     
     self._converter = Converter(self._loader)
     self._reqSender = None
     
     # Add all custom converters to the Converter
     for converter in self._CUSTOM_CONVERTERS:
         # Get correct path/name of the converter
         convList = converter.rsplit('.', 1)
         module = convList[0]
         className = convList[1]
 
         # Load the converter
         mod = __import__(module, fromlist=[className])
         self._converter.addCustomConverter(getattr(mod, className))
     
     self.__cleaner = LoopingCall(self.__clean)
     self.__cleaner.start(self._ROBOT_TIMEOUT/2)
Пример #4
0
def test_distribute_coins_in_binary_tree(root, res):
    from solution.distribute_coins_in_binary_tree import Solution

    assert Solution().distribute_coins(Converter.list_to_tree(root)) == res
Пример #5
0
class RobotManager(_InterfaceManager):
    """ Manager which handles the management of robots and converters.
    """
    class _Robot(object):
        """ Class which represents a robot before he actually connects.
        """
        def __init__(self, key):
            self.key = key
            self.timestamp = datetime.now()
            self.conn = None
    
    def __init__(self, reactor):
        super(RobotManager, self).__init__(reactor)
        
        self._converter = Converter(self._loader)
        self._reqSender = None
        
        # Add all custom converters to the Converter
        for converter in self._CUSTOM_CONVERTERS:
            # Get correct path/name of the converter
            convList = converter.rsplit('.', 1)
            module = convList[0]
            className = convList[1]
    
            # Load the converter
            mod = __import__(module, fromlist=[className])
            self._converter.addCustomConverter(getattr(mod, className))
        
        self.__cleaner = LoopingCall(self.__clean)
        self.__cleaner.start(self._ROBOT_TIMEOUT/2)
    
    @property
    def converter(self):
        """ ROS Message <-> JSON Message Converter. """
        return self._converter
    
    def registerRequestSender(self, sender):
        """ Register the RequestSender.
            
            @param sender:      RequestSender which should be registered.
            @type  sender:      core.interfaces.IRequestSender
        """
        if self._reqSender:
            raise InternalError('There is already a RequestSender registered.')
        
        verifyObject(IRequestSender, sender)
        
        self._reqSender = sender
    
    @_UserManagerBase.verifyUser
    def addRobot(self, userID, robot):
        """ # TODO: Add description
        """
        robotID = robot.robotID
        robots = self._users[userID].robots
        
        if robotID in robots:
            raise InternalError('There already exists a robot with the robot '
                                'ID "{0}".'.format(robotID))
        
        robots[robotID] = RobotManager._Robot(robot.key)
    
    @_UserManagerBase.verifyUser
    def removeRobot(self, userID, tag):
        """ # TODO: Add description
        """
        robots = self._users[userID].robots
        
        if tag not in robots:
            raise InternalError('Tried to remove a robot which does not '
                                'exist.')
        
        if robots[tag].conn:
            raise InternalError('Connection to robot is not closed yet.')
        
        del robots[tag]
    
    @_UserManagerBase.verifyUser
    def robotConnected(self, userID, robotID, key, conn):
        """ # TODO: Add description
                (Called by client.protocol.RobotWebSocketProtocol
                 during initialization/verification of the connection)
        """
        robots = self._users[userID].robots
        
        if robotID not in robots:
            raise AuthenticationError('There is no connection expected from '
                                      'a robot with robotID '
                                      '"{0}".'.format(robotID))
        
        robot = robots[robotID]
        
        if robot.conn:
            raise AuthenticationError('There is already a robot with the same '
                                      'robotID registered.')
        
        if not key == robot.key:
            raise AuthenticationError('The key is not correct.')
        
        robot.timestamp = None
        robot.conn = conn
    
    @_UserManagerBase.verifyUser
    def robotClosed(self, userID, robotID):
        """ # TODO: Add description
                (Called by client.protocol.RobotWebSocketProtocol
                 in onClose)
        """
        robots = self._users[userID].robots
        
        if robotID in robots and robots[robotID]:
            robot = robots[robotID]
            robot.timestamp = datetime.now()
            robot.conn = None
    
    def sendRequest(self, request):
        """ Send a request received from the robot to the master manager for
            processing.
                (Called by client.handler.*)
            
            @param request:     Request which should be sent to the master
                                manager.
            @type  request:     { 'user' : str, 'type' : str, 'args' : tuple }
        """
        self._reqSender.processRequest(request)
    
    @_UserManagerBase.verifyUser
    def receivedFromClient(self, userID, robotID, iTag, msgType, msgID, msg):
        """ Received a message from a client and should now be processed.
                (Called by client.handler.DataMessageHandler)
            
            @param userID:      User ID of the converter owner.
            @type  userID:      str
            
            @param robotID:     Robot ID of the robot for which this converter
                                works.
            @type  robotID:     str
            
            @param iTag:        Tag of the converter to which this message
                                should sent.
            @type  iTag:        str
            
            @param msgType:     Message type of the received message.
            @type  msgType:     str
            
            @param msgID:       Identifier which is used to match request /
                                response message.
            @type  msgID:       str
            
            @param msg:         JSON compatible message which should be sent to
                                the client/robot.
            @type  msg:         dict
        """
        # TODO: robotID at the moment not used...
        self._getInterface(userID, iTag).receive(msgType, msgID, msg)
    
    @_UserManagerBase.verifyUser
    def sendToClient(self, userID, robotID, msg):
        """ Send a message to a client.
                (Called by core.monitor._ConverterMonitor)
            
            @param userID:      User ID of the converter owner.
            @type  userID:      str
            
            @param robotID:     Robot ID of the robot for which this converter
                                works.
            @type  robotID:     str
            
            @param msg:         JSON compatible message which should be sent to
                                the client/robot.
            @type  msg:         dict
        """
        try:
            self._users[userID].robots[robotID].conn.sendMessage(
                {'data' : msg, 'type' : clientTypes.DATA_MESSAGE})
        except KeyError:
            log.msg('Message could not be sent: The robot "{0}" is no longer '
                    'connected.'.format(robotID))
        except AttributeError:
            raise InternalError('Tried to send a message to an unverified '
                                'robot.')
    
    def shutdown(self):
        self.__cleaner.stop()
        
        for user in self._users.itervalues():
            user.robots = {}
        
        super(RobotManager, self).shutdown()
        
        self._reqSender = None
    
    def __clean(self):
        """ Internally used method to remove unclaimed robot connections.
        """
        limit = datetime.now() - timedelta(seconds=self._ROBOT_TIMEOUT)
        
        for userID, user in self._users.iteritems():
            for robotID in [
                robotID for robotID, robot in user.robots.iteritems()
                    if robot.timestamp and robot.timestamp < limit]:
                self._reqSender.processRequest({'user' : userID,
                                                'type' : req.DESTROY_ROBOT,
                                                'args' : (robotID,) })
    
    addInterface = _UserManagerBase.verifyUser(
        _InterfaceManager.addInterface)
    removeInterface = _UserManagerBase.verifyUser(
        _InterfaceManager.removeInterface)
    _getInterface = _UserManagerBase.verifyUser(
        _InterfaceManager._getInterface)
Пример #6
0
def update_tags(infiles, args, logger, killer):
    """Updates the tags of infiles.
    Returns the number of successful updates and the time taken.
    """

    converter = Converter(threads=args["threads"])

    start_time = time.time()

    num_files = len(infiles)
    size_files = fileops.total_size(infiles)
    update_progress = True

    while converter.num_converted() < num_files:
        # Check current processes
        if converter.check_processes() > 0:
            print("Logging errors...")
            converter.log_errors(logger)
            # update_progress = True

        if converter.can_add_process() and len(infiles) > 0:
            inf = infiles.pop()

            outf = fileops.convert_path(inf, args["indir"], args["outdir"])
            outf = os.path.splitext(outf)[0] + (os.extsep + args["outext"])
            converter.add_update_process(inf, outf, pretend=args["pretend"])
            update_progress = True

        # Update the progress
        if update_progress:
            time_left = time_remaining(
                converter.size_conv,
                size_files - converter.size_conv,
                time.time() - start_time,
            )
            display_progress(converter.num_converted(), num_files, time_left)
            update_progress = False
        # Sleep only if really waiting
        elif not args["pretend"]:
            time.sleep(0.05)

        if killer.kill_now:
            converter.kill_all()
            print("Exiting...")
            exit(1)

    return converter.completed, time.time() - start_time
Пример #7
0
 def test_challenge(self):
     hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
     expected_base64 = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
     self.assertEquals(Converter.convert_hex_to_base64(hex), expected_base64)