Example #1
0
 def is_requested(self, digest, code):
   logging.debug("Seeing block code=%s, digest=%s" %
       (Container.code_name(code), base64.b64encode(digest)))
   if self.block_handler.is_requested(
       self.sequence_id, self.container_idx, digest, code):
     return True
   logging.debug("Seeing block of code %s" % Container.code_name(code))
   return code == Container.CODE_HEADER
Example #2
0
 def loaded(self, digest, code, data):
   if self.block_handler.is_requested(
       self.sequence_id, self.container_idx, digest, code):
     self.block_handler.loaded(sequence_id, digest, code, data)
   if code == Container.CODE_HEADER:
     index = Container.decode_piggyback_container_index(digest)
     self.headers[index] = data
Example #3
0
def InitOptionsWindow (Window):
	"""Open main options window"""

	Container.CloseContainerWindow ()

	# Return to Game
	Button = Window.GetControl (11)
	Button.SetText (10308)
	Button.OnPress (Window.Close)
	Button.MakeEscape()

	# Quit Game
	Button = Window.GetControl (10)
	Button.SetText (13731)
	Button.OnPress (OpenQuitMsgWindow)

	# Load Game
	Button = Window.GetControl (5)
	Button.SetText (13729)
	Button.OnPress (LoadGamePress)

	# Save Game
	Button = Window.GetControl (6)
	Button.SetText (13730)
	Button.OnPress (OpenSaveMsgWindow)

	# Video Options
	Button = Window.GetControl (7)
	Button.SetText (17162)
	Button.OnPress (OpenVideoOptionsWindow)

	# Audio Options
	Button = Window.GetControl (8)
	Button.SetText (17164)
	Button.OnPress (OpenAudioOptionsWindow)

	# Gameplay Options
	Button = Window.GetControl (9)
	Button.SetText (17165)
	Button.OnPress (OpenGameplayOptionsWindow)

	# game version, e.g. v1.1.0000
	VersionLabel = Window.GetControl (0x1000000b)
	VersionLabel.SetText (GemRB.Version)

	if GameCheck.IsIWD2():
		# Keyboard shortcuts
		KeyboardButton = Window.GetControl (13)
		KeyboardButton.SetText (33468)
		KeyboardButton.OnPress (OpenHotkeyOptionsWindow)

		# Movies
		MoviesButton = Window.GetControl (14)
		MoviesButton.SetText (15415)
		MoviesButton.OnPress (OpenMovieWindow)

	return
Example #4
0
  def add_aside_block(self, digest, code, data):
    logging.debug("BlockSequencer adding aside block %s:%s:%d" %
        (base64.b64encode(digest), Container.code_name(code), len(data)))
    key = str(self.aside_block_last + 1)
    self.aside_block_last += 1
    self.aside_block_db[key] = digest

    self.aside_block_num += 1
    self.aside_block_size += len(data)
Example #5
0
    def CheckItem(self, path):
        """ Check if the model is valide
		"""

        item = self.ItemDico[path]
        file_path = "".join([path, '.py'])

        ### try to find pyc files
        if not os.path.exists(file_path):
            file_path = "".join([path, '.pyc'])

        if os.path.exists(file_path):

            ### Check the class
            info = Container.CheckClass(file_path)

            ### there is error during the chek of class?
            if isinstance(info, tuple):

                ### if module are missing, we propose to install him with pip
                if ModuleNotFoundError in info:
                    package = info[1].name
                    if install_and_import(package):
                        wx.CallAfter(self.UpdateAll)

                ### else there is an error in the code of the model...
                else:

                    ### recompile if no error
                    info = recompile(path_to_module(file_path))

                    ### there is error during recompilation?
                    if isinstance(info, (Exception, str)):
                        ### Until it has parent, we redifine icon to inform user
                        while (item):
                            ### change image
                            self.SetItemImage(item, self.not_importedidx,
                                              wx.TreeItemIcon_Normal)
                            ### next parent item
                            item = self.GetItemParent(item)
                    else:
                        ### change image
                        self.SetItemImage(item, self.pythonfileidx,
                                          wx.TreeItemIcon_Normal)

                        #### Until it has parent, we redifine icon to inform user
                        while (item):
                            #### change image
                            self.SetItemImage(
                                item, self.fldropenidx if self.IsExpanded(item)
                                else self.fldridx, wx.TreeItemIcon_Normal)
                            #### next parent item
                            item = self.GetItemParent(item)
        else:
            sys.stdout.write("File %s is not checked!")
Example #6
0
 def __init__(self, backup, code, level=0):
   StreamAdapter.OStreamAdapter.__init__(self, backup.get_block_size())
   self.backup = backup
   self.code = code
   self.level = level
   # The packer of a packer is a packer itself :)
   self.code_packer = Container.compute_packer_code(code)
   self.digests = []
   self.rec_ostream = None
   self.num_new_blocks = 0
   self.size_new_blocks = 0
Example #7
0
    def add_block(self, digest, code, data):
        self.block_manager.add_block(digest, code, data)

        if self.block_container_db.has_key(digest):
            return False

        logging.debug(
            "Storage manager adding new block %s:%s:%d"
            % (base64.b64encode(digest), Container.code_name(code), len(data))
        )
        self.block_sequencer.add_block(digest, code, data)
        return True
Example #8
0
    def __init__(self, imageDirectory, imageName, blockDimension,
                 outputDirectory):
        """
        Constructor to initialize the algorithm's parameters
        :return: None
        """

        print(imageName)
        print("Step 1 of 4: Object and variable initialization")

        # image parameter
        self.imageOutputDirectory = outputDirectory
        self.imagePath = imageName
        self.imageData = Image.open(imageDirectory + imageName)
        self.imageWidth, self.imageHeight = self.imageData.size  # height = vertikal, width = horizontal

        if self.imageData.mode != 'L':  # L means grayscale
            self.isThisRGBImage = True
            self.imageData = self.imageData.convert('RGB')
            self.imageGrayscale = self.imageData.convert(
                'L'
            )  # creates a grayscale version of current image to be used later

        else:
            self.isThisRGBImage = False
            self.imageData = self.imageData.convert('L')

        self.blockDimension = blockDimension
        self.Max_Count = 15

        # container initialization to later contains several data
        self.featuresContainerKeypoints = Container.Container()
        self.featuresContainerDescriptors = Container.Container()
        self.blockPairContainer = Container.Container()
        self.matched_coordinate = Container.Container()
        self.offsetDictionary = {}
        FLANN_INDEX_KDTREE = 1
        index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
        search_params = dict(checks=50)  # or pass empty dictionary
        self.flann = cv2.FlannBasedMatcher(index_params, search_params)
Example #9
0
 def __init__(self, _modelRunTitle, run_codes, _db):
     # add run title.
     self.modelRunTitle = self._addTitle(_modelRunTitle)
     # add run codes.
     self.run_codes = run_codes
     # container to pass info around.
     self.cont = Container.Container()
     self.cont.set('modelRunTitle', self._addTitle(_modelRunTitle))
     self.cont.set('run_codes', run_codes)
     self.cont.set('path', 'C:/Nonroad/%s/' % (_modelRunTitle))
     self.cont.set('db', _db)
     self.cont.set('qr', qr.QueryRecorder(self.cont.get('path')))
     # create Batch runner.
     self.batch = Batch.Batch(self.cont)
Example #10
0
 def PreWarmContainers(self):
     """Warm containers before incoming activation to mimic it happening at the actual time """
     if self.eviction_policy != "HIST":
         return
     to_warm = [
         kind for kind, prewarm in self.histPrewarm.items()
         if prewarm != 0 and prewarm +
         self.last_seen[kind] >= self.wall_time
     ]
     for kind in to_warm:
         c = Container(self.rep[kind])
         at = self.histPrewarm[kind] + self.last_seen[kind]
         at = min(at, self.wall_time)
         self.AddToPool(c=c, prewarm=True, at_time=at)
Example #11
0
def InitOptionsWindow(Window):
    """Open main options window (peacock tail)"""

    GemRB.GamePause(1, 1)
    TrySavingConfiguration()

    Container.CloseContainerWindow()

    def ConfigOptButton(button, strref, action):
        button.SetText(strref)
        button.SetEvent(IE_GUI_BUTTON_ON_PRESS, action)

    # Return to Game
    ConfigOptButton(Window.GetControl(0), 28638, lambda: Window.Close())

    # Quit Game
    ConfigOptButton(Window.GetControl(1), 2595, OpenQuitMsgWindow)

    # Load Game
    # german pst has two spaces that need to be squished
    LoadButton = Window.GetControl(2)
    LoadGameString = GemRB.GetString(2592)
    NewString = " ".join(LoadGameString.split())
    LoadButton.SetText(NewString)
    LoadButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, OpenLoadMsgWindow)

    # Save Game
    ConfigOptButton(Window.GetControl(3), 20639, GUISAVE.OpenSaveWindow)

    # Video Options
    ConfigOptButton(Window.GetControl(4), 28781, OpenVideoOptionsWindow)

    # Audio Options
    ConfigOptButton(Window.GetControl(5), 29720, OpenAudioOptionsWindow)

    # Gameplay Options
    ConfigOptButton(Window.GetControl(6), 29722, OpenGameplayOptionsWindow)

    # Keyboard Mappings
    ConfigOptButton(Window.GetControl(7), 29723, OpenKeyboardMappingsWindow)

    # Movies
    ConfigOptButton(Window.GetControl(9), 38156, OpenMoviesWindow)

    # game version, e.g. v1.1.0000
    Label = Window.GetControl(0x10000007)
    Label.SetText(GemRB.Version)

    return
Example #12
0
def DialogStarted():
    global ContinueWindow

    Container.CloseContainerWindow()

    # opening control size to maximum, enabling dialog window
    CommonWindow.SetGameGUIHidden(False)
    GemRB.GameSetScreenFlags(GS_DIALOG, OP_OR)

    # disable the 1-6 hotkeys, so they'll work for choosing answers
    GUICommonWindows.UpdatePortraitWindow()

    MessageWindow.UpdateControlStatus()

    ContinueWindow = OpenDialogButton(9)
    def undo_redo_helper(self):
        for i in self.container.unit_operations:
            type(i).counter = 1
        self.container = None
        for i in dock_widget_lst:
            i.hide()
            del i
        lst.clear()
        self.container = Container(self.textBrowser, self.graphicsView)

        compound_selected.clear()
        self.scene = self.container.graphics.get_scene()
        self.graphicsView.setScene(self.scene)
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.keyPressEvent=self.delete_call
Example #14
0
    def Get(self):
        result = []

        allnumbers = self.GetShuffledNumbers()

        for i in range(0, 30, 6):
            posY = 540-(10*i)
            block = []
            for j in range(i, i+6):
                posX = 0+(60 * (j % 6))
                newContainer = Container(allnumbers[j], posX, posY)
                block.append(newContainer)
            result.append(block)

        return result
Example #15
0
 def load_block(self, digest):
   """
   Actually perform loading of the block.
   """
   logging.debug("BM Loading block " + base64.b64encode(digest) +
       " " + Container.code_name(self.get_block_code(digest)))
   if self.block_epoch.has_key(digest):
     # Block exists in the temporary cache.
     self._update_block_epoch(digest)
     return self.tmp_blocks[digest]
   if self.cached_blocks.has_key(digest):
     #
     # Blocks that sit in self.cached_blocks are never unloaded
     #
     return self.cached_blocks[digest]
   raise Exception("Block is unknown.")
Example #16
0
    def cache_miss(self, d: LambdaData):
        c = Container(d)
        if not self.checkfree(c):  #due to space constraints
            #print("Eviction needed ", d.mem_size, self.mem_used)
            evicted = self.Eviction(
                d)  #Is a list. also terminates the containers?

        added = self.AddToPool(c)
        if not added:
            # print("Could not add even after evicting. FATAL ERROR")
            # print("actual in-use memory", sum([k.metadata.mem_size for k in self.ContainerPool]))
            # print("pool size", len(self.ContainerPool))
            return None

        heapq.heapify(self.ContainerPool)
        return c
Example #17
0
def DialogStarted ():
	global ContinueWindow

	# try to force-close anything which is open
	GUICommonWindows.CloseTopWindow()
	Container.CloseContainerWindow()

	# opening control size to maximum, enabling dialog window
	CommonWindow.SetGameGUIHidden(False)
	GemRB.GameSetScreenFlags(GS_DIALOG, OP_OR)

	# disable the 1-6 hotkeys, so they'll work for choosing answers
	if GemRB.GetView ("PORTWIN"):
		GUICommonWindows.UpdatePortraitWindow ()

	ContinueWindow = OpenDialogButton(9)
Example #18
0
    def OnInit(self):

        import gettext

        #builtins.__dict__['PYDEVS_SIM_STRATEGY_DICT'] = {'original':'SimStrategy1', 'bag-based':'SimStrategy2', 'direct-coupling':'SimStrategy3'}
        #builtins.__dict__['PYPDEVS_SIM_STRATEGY_DICT'] = {'original':'SimStrategy4', 'distributed':'SimStrategy5', 'parallel':'SimStrategy6'}

        builtins.__dict__['NB_HISTORY_UNDO'] = 5
        builtins.__dict__['ICON_PATH'] = 'icons'
        builtins.__dict__['ICON_PATH_16_16'] = os.path.join(ICON_PATH, '16x16')
        builtins.__dict__['_'] = gettext.gettext

        diagram = Container.Diagram()

        self.frame = DetachedFrame(None, -1, "Test", diagram)
        self.frame.Show()
        return True
Example #19
0
    def ErrorManager(self, msg):
        """ An error is occurred.
		"""

        ### try to find the file which have the error from traceback
        devs_error = False
        try:
            typ, val, tb = msg.date if wx.VERSION_STRING < '2.9' else msg
            trace = traceback.format_exception(typ, val, tb)

            mainW = wx.GetApp().GetTopWindow()
            ### paths in traceback
            paths = [
                a for a in trace if a.split(',')[0].strip().startswith('File')
            ]

            ### find if DOMAIN_PATH is in the first file path of the trace
            path = paths[-1]
            devs_error = DOMAIN_PATH in path or HOME_PATH not in path

        except Exception as info:
            sys.stdout.write(_("Error in ErrorManager: %s" % info))

        ### if error come from devs python file
        if devs_error:

            try:
                ### simulate event button for the code editor
                event = wx.PyCommandEvent(wx.EVT_BUTTON.typeId,
                                          self._btn1.GetId())
            except:
                pass
            else:
                ### Error dialog
                if not Container.MsgBoxError(
                        event, self.parent,
                        msg.date if wx.VERSION_STRING < '2.9' else msg):
                    ### if user dont want correct the error, we destroy the simulation windows
                    self.PrepareDestroyWin()
                    self.Destroy()
                else:
                    ### if user want to correct error through an editor, we stop simulation process for trying again after the error is corrected.
                    self.OnStop(event)
        else:
            print(msg)
            raise MyBad(msg)
Example #20
0
def DialogStarted ():
	global ContinueWindow

	GUICommonWindows.CloseTopWindow()
	Container.CloseContainerWindow()

	# opening control size to maximum, enabling dialog window
	CommonWindow.SetGameGUIHidden(False)
	GemRB.GameSetScreenFlags(GS_DIALOG, OP_OR)
	
	# disable the 1-6 hotkeys, so they'll work for choosing answers
	GUICommonWindows.UpdatePortraitWindow ()

	MWin = GemRB.GetView("MSGWIN")
	CloseButton= MWin.GetControl (0)
	CloseButton.SetText ("")
	CloseButton.SetDisabled(True)
	CloseButton.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR)
Example #21
0
    def __init__(self,
                 name,
                 id,
                 mass,
                 sideLength,
                 length,
                 _from,
                 start_points,
                 end_points,
                 health=100):
        self.name = name
        self.id = id
        self.mass = mass
        self.sideLength = sideLength
        self.length = length
        self.start_points = start_points
        self.end_points = end_points
        self.parents = []
        self.health = health
        self.bacteriaClusters = []
        self.immuneCellClusters = []
        self._from = _from
        self._sideLengthBoxes = round(0.5 + (float(sideLength) /
                                             parameters.organ_grid_resolution))
        self._lengthBoxes = round(0.5 + (float(length) /
                                         parameters.organ_grid_resolution))
        self._grid = np.empty(
            (self._sideLengthBoxes, self._sideLengthBoxes, self._lengthBoxes),
            dtype=Container)
        for i in range(self._sideLengthBoxes):
            for j in range(self._sideLengthBoxes):
                for k in range(self._lengthBoxes):
                    self._grid[i][j][k] = Container()
        xs = np.random.uniform(0, self._sideLengthBoxes, 2)
        ys = np.random.uniform(0, self._sideLengthBoxes, 2)
        zs = np.random.uniform(0, self._lengthBoxes, 2)
        self._grid_entrance = Point(int(xs[0]), int(ys[0]), int(zs[0]))

        self._grid_exit = Point(int(xs[1]), int(ys[1]), int(zs[1]))
        self.volume = sideLength**2 * length
        self.residualVolume = 0
        self._flowEvent = []
        self.bacteriaCountHistory = []
        self.flowHistory = []
Example #22
0
    def OnMotion(self, evt):
        """ Motion engine over item.
		"""
        item, flags = self.HitTest(evt.GetPosition())

        if (flags & wx.TREE_HITTEST_ONITEMLABEL) and not evt.LeftIsDown():

            path = self.GetItemData(item)

            if os.path.isdir(path):
                model_list = self.GetModelList(path)
                domain_list = self.GetDomainList(path)

                tip = '\n'.join(model_list) if model_list != [] else ""
                tip += '\n'
                tip += '\n'.join(domain_list) if domain_list != [] else ""

            ### is last item
            else:
                module = BlockFactory.GetModule(path)
                info = Container.CheckClass(path)

                if isinstance(info, tuple):
                    doc = str(info)
                elif isinstance(module, tuple):
                    doc = str(module)
                else:
                    doc = inspect.getdoc(module)

                tip = doc if doc is not None else _(
                    "No documentation for selected model.")

            ### add maccabe metric info
            if item in self.MetricDico:
                mcc = self.MetricDico[item]['mcc']
                tip = ''.join([tip, '\n', 'macCabe metric: %d' % mcc])

            self.SetToolTip(tip)

        else:
            self.SetToolTip(None)

        ### else the drag and drop dont run
        evt.Skip()
Example #23
0
    def OnMotion(self, evt):
        """ Motion engine over item.
		"""
        item, flags = self.HitTest(evt.GetPosition())

        if (flags & wx.TREE_HITTEST_ONITEMLABEL) and not evt.LeftIsDown():

            path = self.GetItemPyData(item)

            if os.path.isdir(path):
                model_list = self.GetModelList(path)
                domain_list = self.GetDomainList(path)

                tip = '\n'.join(model_list) if model_list != [] else ""
                tip += '\n'
                tip += '\n'.join(domain_list) if domain_list != [] else ""

            ### is last item
            else:
                module = BlockFactory.GetModule(path)
                info = Container.CheckClass(path)

                if isinstance(info, tuple):
                    doc = str(info)
                elif isinstance(module, tuple):
                    doc = str(module)
                else:
                    doc = inspect.getdoc(module)

                tip = doc if doc is not None else _(
                    "No documentation for selected model.")

            try:
                txt = tip.decode('utf-8', 'ignore')
            except UnicodeEncodeError:
                sys.stdout.write("Unicode Error!\n")
            else:
                self.SetToolTip(wx.ToolTip(txt))

        else:
            self.SetToolTip(None)

        ### else the drag and drop dont run
        evt.Skip()
Example #24
0
    def CheckItem(self, path):
        """ Check if the model is valide
		"""

        item = self.ItemDico[path]
        file_path = "".join([path, '.py'])

        ### Check the class
        info = Container.CheckClass(file_path)

        ### there is error during the chek of class ?
        if isinstance(info, tuple):
            ### recompile if no error
            info = recompile(path_to_module(file_path))

            ### there is error during recompilation ?
            if isinstance(info, (Exception, str)):
                ### Until it has parent, we redifine icon to inform user
                while (item):
                    ### change image
                    self.SetItemImage(item, self.not_importedidx,
                                      wx.TreeItemIcon_Normal)
                    ### next parent item
                    item = self.GetItemParent(item)
            else:
                ### change image
                self.SetItemImage(item, self.pythonfileidx,
                                  wx.TreeItemIcon_Normal)

                #### Until it has parent, we redifine icon to inform user
                while (item):
                    if self.IsExpanded(item):
                        #### change image
                        self.SetItemImage(item, self.fldropenidx,
                                          wx.TreeItemIcon_Normal)
                    else:
                        self.SetItemImage(item, self.fldridx,
                                          wx.TreeItemIcon_Normal)

                    #### next parent item
                    item = self.GetItemParent(item)
Example #25
0
    def run(self, argv):

        broker = self.communicator()
        adapter = broker.createObjectAdapter("PlayerAdapter")
        adapter2 = broker.createObjectAdapter("ContainerAdapter")

        containerRobots = Container.Container()

        # Factorias para controladores de robot
        factorias_robot_identity = ["RobotFactory1", "RobotFactory2", "RobotFactory3"]
        factorias_robot = []

        for factorias_identity in factorias_robot_identity:
            factory_proxy = broker.stringToProxy(factorias_identity)
            factorias_robot.append(drobots.RobotFactoryPrx.checkedCast(factory_proxy))

        # Factoria para controlador de detector
        detector_proxy = broker.stringToProxy("RobotFactory4")
        factoria_detector = drobots.DetectorFactoryPrx.checkedCast(detector_proxy)

        sirviente = Player(adapter, factorias_robot, factoria_detector, containerRobots)
        adapter2.add(containerRobots, broker.stringToIdentity("Robots"))

        proxyPlayer = adapter.add(sirviente, broker.stringToIdentity("Player"))
        proxyDirecto = adapter.createDirectProxy(proxyPlayer.ice_getIdentity())
        player = drobots.PlayerPrx.uncheckedCast(proxyDirecto)

        adapter.activate()
        adapter2.activate()

        proxyGame = broker.propertyToProxy("Game")
        game = drobots.GamePrx.checkedCast(proxyGame)

        idrandom = random.randint(0, 9999)
        game.login(player, str(idrandom))
        print("Partida comenzada.")

        self.shutdownOnInterrupt()
        self.communicator().waitForShutdown()
Example #26
0
    def OnItemDocumentation(self, evt):
        """ Display the item's documentation on miniFrame.
		"""

        item = self.GetSelection()
        path = self.GetItemPyData(item)
        name = self.GetItemText(item)

        module = BlockFactory.GetModule(path)
        info = Container.CheckClass(path)

        if isinstance(info, tuple):
            doc = str(info)
        elif isinstance(module, tuple):
            doc = str(module)
        else:
            doc = inspect.getdoc(module)

        ### Add maccabe complexity measure
        doc += "".join(
            [_("\n\n MacCabe Complexity: %d") % self.MetricDico[item]['mcc']])

        if doc:
            dlg = wx.lib.dialogs.ScrolledMessageDialog(
                self,
                doc,
                _("%s Documentation") % name,
                style=wx.OK | wx.ICON_EXCLAMATION | wx.DEFAULT_DIALOG_STYLE
                | wx.RESIZE_BORDER)
            dlg.CenterOnParent(wx.BOTH)
            dlg.ShowModal()
        else:
            wx.MessageBox(
                _("No documentation! \n Please define the documentation of the model %s in the header of its python file."
                  ) % name,
                _("%s Documentation") % name, wx.OK | wx.ICON_INFORMATION)
Example #27
0
File: main.py Project: OrmesKD/PyP
import sys
import Screen
import Container
from shape import *

#Set up the initial test shapes hard coded at the moment
Shapes = Container.Generate()

#Calculate the heat graph to be displayed in the GUI
heatMap = Container.calculateHeat(Shapes)

#Calculate the possible nodes for containers
Container.findContainer(heatMap)

#Draw the screen with the calculations found from the Container problem
Screen.draw(Shapes,heatMap)
    def run(self, bridge, url, run_as_service=False):
        logger = logging.getLogger(self.id)
        import xbmc

        xbmc.bridge = bridge
        import Container
        xbmc.Container = Container.Container(self)
        xbmc.LANGUAGE = kodi_utils.get_config(kodi_utils.LANGUAGE_CONFIG)
        if not xbmc.LANGUAGE:
            xbmc.LANGUAGE = 'English'
        if type(url) is not str:
            raise Exception('Kodi plugin only accepts one string argument')

        if url.startswith('http') or url.startswith('https'):
            bridge.play(url, type_='video')
            return
        orig = sys.path

        sys.path.append(os.path.join(bundle_dir, 'scripts'))
        sys.path.append(os.path.join(bundle_dir, 'scripts', 'kodi'))

        import xbmcplugin, xbmcaddon, copy

        for r in self.requires:
            if not os.path.exists(os.path.join(ADDONS_DIR, r)):
                logger.error('Addon {} is missing module {}'.format(
                    self.id, r))
                return None

            tree = ET.parse(os.path.join(ADDONS_DIR, r, 'addon.xml'))
            for e2 in tree.iter('extension'):
                if e2.attrib['point'] == 'xbmc.python.module':
                    sys.path.insert(
                        0, os.path.join(ADDONS_DIR, r, e2.attrib['library']))
                    xbmcaddon.Addon(r,
                                    copy.deepcopy(kodi_utils.get_settings(r)))

        sys.path.insert(0, self.dir)
        if '/' in self.module:
            sys.path.insert(
                0, os.path.join(*([self.dir] + self.module.split('/')[:-1])))
        print sys.path

        if run_as_service and self.service:
            try:
                if 'setproctitle' in sys.modules:
                    setproctitle.setproctitle(
                        'python TVMLServer ({} service)'.format(self.id))
                runpy.run_module(self.service.split('/')[-1][:-3],
                                 run_name='__main__')
            except:
                logger.exception('Failed in addon {} service'.format(self.id))
            return None

        try:
            if '?' in url:
                sys.argv = [
                    url.split('?')[0], '1', '?{}'.format(url.split('?')[1])
                ]
            else:
                sys.argv = [url, '1', '']

            if not sys.argv[0]:
                sys.argv[0] = 'plugin://{}/'.format(self.id)

            if not sys.argv[0].startswith(
                    'file://') and not sys.argv[0].startswith('plugin://'):
                sys.argv[0] = 'plugin://{}{}'.format(self.id, sys.argv[0])
        # sys.argv = [script, '1', url]
            logger.debug('Calling plugin {} with {}'.format(
                self.name, sys.argv))
            import xbmcplugin, xbmcaddon
            xbmcaddon.Addon(self.id,
                            copy.deepcopy(kodi_utils.get_settings(self.id)))
            import imp

            # some patches for internal python funcs
            import urllib

            quote_plus_orig = urllib.quote_plus

            def quote_plus_patch(s, safe=''):
                if type(s) == unicode:
                    s = s.encode('utf-8')
                return quote_plus_orig(s, safe)

            urllib.quote_plus = quote_plus_patch

            import sqlite3

            sqlite3_connect_orig = sqlite3.connect

            def sqlite3_connect_patch(*args, **kwargs):
                logger.debug('sqlite3 connect patch')
                database = args[0]
                dirname = os.path.dirname(database)
                if not os.path.exists(dirname):
                    logger.debug(
                        'creating non-existent directory {}'.format(dirname))
                    os.makedirs(dirname)
                if not os.path.exists(database):
                    open(database, 'a').close()
                for tries in range(10):
                    try:
                        return sqlite3_connect_orig(*args, **kwargs)
                    except:
                        time.sleep(1)
                        logger.exception('Failed to open DB')
                raise Exception('Failed to open DB file {}'.format(database))

            sqlite3.connect = sqlite3_connect_patch

            dbapi2_connect_orig = sqlite3.dbapi2.connect

            def dbapi2_connect_patch(*args, **kwargs):
                logger.debug('sqlite3.dbapi2 connect patch')
                database = args[0]
                dirname = os.path.dirname(database)
                if not os.path.exists(dirname):
                    logger.debug(
                        'creating non-existent directory {}'.format(dirname))
                    os.makedirs(dirname)
                if not os.path.exists(database):
                    open(database, 'a').close()
                for tries in range(10):
                    try:
                        return dbapi2_connect_orig(*args, **kwargs)
                    except:
                        time.sleep(1)
                        logger.exception('Failed to open DB')
                logger.exception('Failed to open DB file {}'.format(database))
                raise Exception('Failed to open DB file {}'.format(database))

            sqlite3.dbapi2.connect = dbapi2_connect_patch

            xbmcplugin.items = []
            runpy.run_module(self.module.split('/')[-1], run_name='__main__')
            #imp.load_module(self.module, fp, self.dir, ('.py', 'rb', imp.PY_SOURCE))
        except SystemExit:
            pass
        except:
            logger.exception('Failure in plugin run')
        sqlite3.connect = sqlite3_connect_orig
        sqlite3.dbapi2.connect = dbapi2_connect_orig
        urllib.quote_plus = quote_plus_orig
        sys.path = orig
        # sys.argv = old_sys_argv
        items = xbmcplugin.items
        if xbmcplugin.resolved:
            listitem = xbmcplugin.resolved
            image = listitem.thumbnailImage if listitem.thumbnailImage != 'DefaultFolder.png' else ''
            if listitem.getProperty('poster'):
                image = listitem.getProperty('poster')
            imdb = listitem.getProperty('imdb')
            if not imdb:
                imdb = listitem.getProperty('imdb_id')
            if not imdb:
                imdb = listitem.getProperty('imdbnumber')
            if not imdb:
                imdb = listitem.getProperty('code')
            global resolved
            resolved = listitem
            bridge.play(listitem.path,
                        title=listitem.getProperty('title'),
                        description=listitem.getProperty('plot'),
                        image=image,
                        imdb=imdb,
                        season=str(listitem.getProperty('season'))
                        if listitem.getProperty('season') else None,
                        episode=str(listitem.getProperty('episode'))
                        if listitem.getProperty('episode') else None)
            xbmcplugin.resolved = None
        logger.debug('Plugin {} ended with: {}'.format(self.name, items))

        # some cleanup
        for id in xbmcaddon.ADDON_CACHE:
            kodi_utils.set_settings(id, xbmcaddon.ADDON_CACHE[id].settings)
        if hasattr(bridge, 'progress'):
            logger.debug('Closing left over progress')
            bridge.closeprogress()
        ans = []
        items = xbmcplugin.items
        from Plugin import Item

        if len(items) == 1 and hasattr(items[0], 'path'):
            return items
        for item in items:
            # url, title, subtitle=None, icon=None, details=None, menuurl='', info={})
            i = Item(
                url=item['url'],
                title=kodi_utils.tag_conversion(item['listitem'].label),
                subtitle=item['listitem'].getProperty('subtitle'),
                icon=item['listitem'].thumbnailImage if
                item['listitem'].thumbnailImage != 'DefaultFolder.png' else '',
                details=item['listitem'].getProperty('details'),
                info=item['listitem'].infos,
                context=item['listitem'].context)
            try:
                if type(i.context) is list:  # needs to be dict
                    i.context = {x[0]: x[1] for x in i.context}
            except:
                pass
            infos = item['listitem'].infos
            if 'poster' in infos:
                i.icon = infos['poster']
            if 'plot' in infos:
                i.details = infos['plot']
            if 'year' in infos:
                i.year = infos['year']
            if 'trailer' in infos:
                i.context['Watch trailer'] = 'RunPlugin({})'.format(
                    infos['trailer'])
            # icon path fix
            if i.icon and i.icon.startswith(ADDONS_DIR):
                i.icon = i.icon.replace(ADDONS_DIR, '/addons')
            if i.icon:
                i.icon = i.icon.replace('\\', '/')
            ans.append(i)
        return ans
    def __init__(self, imageDirectory, imageName, blockDimension,
                 outputDirectory):
        """
        Constructor to initialize the algorithm's parameters
        :param imageDirectory: direktori file citra
        :param imageName: nama file citra
        :param blockDimension: ukuran blok dimensi (ex:32, 64, 128)
        :param outputDirectory: direktori untuk hasil deteksi
        :return: None
        """

        print imageName
        print "Step 1 of 4: Object and variable initialization",

        # image parameter
        self.imageOutputDirectory = outputDirectory
        self.imagePath = imageName
        self.imageData = Image.open(imageDirectory + imageName)
        self.imageWidth, self.imageHeight = self.imageData.size  # height = vertikal, width = horizontal

        if self.imageData.mode != 'L':  # L means grayscale
            self.isThisRGBImage = True
            self.imageData = self.imageData.convert('RGB')
            RGBImagePixels = self.imageData.load()
            self.imageGrayscale = self.imageData.convert(
                'L'
            )  # creates a grayscale version of current image to be used later
            GrayscaleImagePixels = self.imageGrayscale.load()

            for yCoordinate in range(0, self.imageHeight):
                for xCoordinate in range(0, self.imageWidth):
                    redPixelValue, greenPixelValue, bluePixelValue = RGBImagePixels[
                        xCoordinate, yCoordinate]
                    GrayscaleImagePixels[xCoordinate, yCoordinate] = int(
                        0.299 * redPixelValue) + int(
                            0.587 * greenPixelValue) + int(
                                0.114 * bluePixelValue)
        else:
            self.isThisRGBImage = False
            self.imageData = self.imageData.convert('L')

        # algorithm's parameters from the first paper
        self.N = self.imageWidth * self.imageHeight
        self.blockDimension = blockDimension
        self.b = self.blockDimension * self.blockDimension
        self.Nb = (self.imageWidth - self.blockDimension +
                   1) * (self.imageHeight - self.blockDimension + 1)
        self.Nn = 2  # amount of neighboring block to be evaluated
        self.Nf = 188  # minimum treshold of the offset's frequency
        self.Nd = 50  # minimum treshold of the offset's magnitude

        # algorithm's parameters from the second paper
        self.P = (1.80, 1.80, 1.80, 0.0125, 0.0125, 0.0125, 0.0125)
        self.t1 = 2.80
        self.t2 = 0.02

        print self.Nb, self.isThisRGBImage

        # container initialization to later contains several data
        self.featuresContainer = Container.Container()
        self.blockPairContainer = Container.Container()
        self.offsetDictionary = {}
Example #30
0
    def GetDiagramCoupling(canvas):
        ''' Build the DEVSimpy diagram coupling 
		'''
        ### make connection
        connectionlist = xmldoc.getElementsByTagName('coupling')

        ### all blocks
        blocks = canvas.diagram.GetFlatBlockShapeList()

        ### make connection
        while (connectionlist != []):

            ### take the first connection object (deleted at the end of while)
            s = connectionlist[0]

            ### Get the names of blocks
            source_name = GetNodeFromUID(
                s.attributes['sourceuid'].value).attributes['name'].value
            target_name = GetNodeFromUID(
                s.attributes['sinkuid'].value).attributes['name'].value
            diagram_name = s.parentNode.attributes['name'].value

            ### Get the port id removing caracter form str if port has specified with label
            source_port_num = u''.join(
                [i for i in s.attributes['sourceport'].value if i.isdigit()])
            target_port_num = u''.join(
                [i for i in s.attributes['sinkport'].value if i.isdigit()])

            ### if no port number is specified in the XML, there is one port and its id is 1 (not 0 but it can be depending on the rule chose by the SES modeler!)
            if source_port_num == u'': source_port_num = u'1'
            if target_port_num == u'': target_port_num = u'1'

            ### find the graphic block of the source, target and diagram
            source = target = diagram = None
            for b in blocks:
                if b.label == source_name:
                    source = b
                if b.label == target_name:
                    target = b
                if b.label == diagram_name:
                    diagram = b

            ### if source or target is the diagram, we change them with the corresponding iPort or oPort
            if diagram == source:
                for s in filter(lambda a: isinstance(a, Container.iPort),
                                source.GetShapeList()):
                    if int(s.id) == int(source_port_num) - 1:
                        source = s
                        break

            if diagram == target:
                for t in filter(lambda a: isinstance(a, Container.oPort),
                                target.GetShapeList()):
                    if int(t.id) == int(target_port_num) - 1:
                        target = t
                        break

            #print "------------------------------------------------"
            #print source, target

            a, b = GetNodeLists(canvas, source, target)

            #print a,b

            if len(a) == 1: source_port_num = u'1'
            if len(b) == 1: target_port_num = u'1'
            #print source_name,int(source_port_num)-1,target_name,int(target_port_num)-1
            sourceNode, targetNode = a[int(source_port_num) -
                                       1], b[int(target_port_num) - 1]

            ### item of node must be overwritted
            sourceNode.item = source
            targetNode.item = target

            ### add the connexion to the diagram
            ci = Container.ConnectionShape()
            ci.setInput(sourceNode.item, sourceNode.index)
            ci.x[0], ci.y[0] = sourceNode.item.getPortXY(
                'output', sourceNode.index)
            ci.x[1], ci.y[1] = targetNode.item.getPortXY(
                'input', targetNode.index)
            ci.setOutput(targetNode.item, targetNode.index)
            diagram.shapes.insert(0, ci)

            #print "------------------------------------------------"

            ### delete the first selected cinnection objet
            del connectionlist[0]

        return canvas.GetDiagram()
    def __init__(self, init_string):
        c = Container.Container()
        Lx = 10.
        Ly = 10.
        Lz = 0.
        dist = Lx / 5.
        vel = dist / 5.

        if init_string == 'one':
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = Lz

            c.add_particle(0., dist, 0., 0., 0., 0.)

        elif init_string == 'two':
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = Lz

            c.add_particle(1., 5., 0., 0.4, 0., 0.)
            c.add_particle(3., 5., 0., -0.4, 0., 0.)

        elif init_string == 'eight':
            lx = 10.
            ly = 10.
            dist = lx / 5.
            vel = dist / 5.
            #c.L = Vector_3D(10., 10., 0.)
            c.Lx = 10.
            c.Ly = 10.
            c.Lz = 0.
            c.add_particle(-dist + 5, 0. + 5, 0., vel, 0., 0.)
            c.add_particle(dist + 5, 0. + 5, 0., -vel, 0., 0.)
            c.add_particle(0. + 5, dist + 5, 0., 0., -vel, 0.)
            c.add_particle(0. + 5, -dist + 5, 0., 0., vel, 0.)
            c.add_particle(dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0.,
                           -vel / sqrt(2), -vel / sqrt(2), 0.)
            c.add_particle(-dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0.,
                           vel / sqrt(2), -vel / sqrt(2), 0.)
            c.add_particle(-dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0.,
                           vel / sqrt(2), vel / sqrt(2), 0.)
            c.add_particle(dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0.,
                           -vel / sqrt(2), vel / sqrt(2), 0.)

        elif init_string == 'eight-zeros':
            lx = 10.
            ly = 10.
            dist = lx / 5.
            vel = dist / 5.
            #c.L = Vector_3D(10., 10., 0.)
            c.Lx = 10.
            c.Ly = 10.
            c.Lz = 0.
            c.add_particle(-dist + 5, 0. + 5, 0., 0., 0., 0.)
            c.add_particle(dist + 5, 0. + 5, 0., 0., 0., 0.)
            c.add_particle(0. + 5, dist + 5, 0., 0., 0., 0.)
            c.add_particle(0. + 5, -dist + 5, 0., 0., vel, 0.)
            c.add_particle(dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)
            c.add_particle(-dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)
            c.add_particle(-dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0., 0.,
                           0., 0.)
            c.add_particle(dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)

        elif init_string == 'square_lattice':
            N = 8  # Particles per row
            Lx = 8.
            Ly = sqrt(3) / 2. * Lx
            #c.Ly = c.Lx       # Extents determined by Lx input
            # TODO: set L
            #c.L = Vector_3D(30., 30., 0.)
            c.Lx = 9.
            c.Ly = 9.
            c.Lz = 0.
            d = 2.**(1 / 6.)  # Particle diameter
            x = np.linspace(d / 2, Lx - d / 2, N)
            y = np.linspace(d / 2., Lx - d / 2, N)
            for i in range(x.size):
                for j in range(y.size):
                    c.add_particle(x[i], y[j], 0., 0., 0., 0.)
                    #c.addParticle(x, y, z, vx, vy, ax, ay, mass)

        elif init_string == 'tri_lattice':
            Lx = 8.
            N = 8  # particles per row
            Ly = sqrt(3) / 2. * Lx  # Set this based on Lx
            #c.L = Vector_3D(Lx, Ly, 0.)
            c.Lx = Lx
            c.Ly = Ly
            d = 2.**(1 / 6.)  # diameter
            x = np.linspace(-c.Lx / 2 + 3. * d / 4., c.Lx / 2. - 1. * d / 4.,
                            N)  # Unstaggered
            xs = np.linspace(-c.Lx / 2 + d / 4., c.Lx / 2. - 3. * d / 4.,
                             N)  # Staggered
            y = np.linspace(-c.Ly / 2 + d / 2., c.Ly / 2 - d / 2, N)

            for i in range(N):
                for j in range(N):
                    if np.mod(i, 2) == 0:
                        #c.addParticle(x[j],y[i],0,0,0,0,1)
                        c.add_particle(x[j], y[i], 0., 0., 0., 0.)
                    else:
                        #c.addParticle(xs[j],y[i],0,0,0,0,1)
                        c.add_particle(xs[j], y[i], 0., 0., 0., 0.)

        elif init_string == 'prob3':
            N = 64
            #Lx = 8.
            #Ly = sqrt(3) / 2. * Lx
            Lx = 15.
            Ly = 15.
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = 0.

            for i in range(N):
                x = np.random.random_sample() * Lx
                y = np.random.random_sample() * Ly
                print "x: " + str(x)
                print "y: " + str(y)

                c.add_particle(x, y, 0., 0., 0., 0.)
                print c.x
                print c.y

        elif init_string == 'proj1':
            cFloor = 100
            cSled = 13
            a = 2**(1 / 6)
            Lx = 100 * a
            Ly = 20 * a
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = 0.

            # set up floor values
            xFloor = np.linspace(a / 2, Lx - a / 2, cFloor)
            yFloor = 1.

            # set up the bottom of the sled
            xSledBot = np.linspace(a, (2 * np.ceil(cSled) - 1) * a,
                                   np.ceil(cSled))
            ySledBot = 1 + a

            # set up the top of the sled
            xSledTop = np.linspace(2 * a, 2 * np.floor(cSled) * a,
                                   np.floor(cSled))
            ySledTop = 1 + a + np.sqrt(3) * a

            for i in range(cFloor):
                c.add_particle(xFloor[i], yFloor, 0., 0., 0., 0., 1.)

            for i in range(cSled):
                if i % 2:
                    c.add_particle(xSledTop[(i - 1) / 2], ySledTop, 0., 0., 0.,
                                   0.)
                else:
                    c.add_particle(xSledBot[i / 2], ySledBot, 0., 0., 0., 0.)

        self.c = c
Example #32
0
    def InsertNewDomain(self, dName, parent, L=[]):
        """ Recurrent function that insert new Domain on library panel.
		"""

        ### first only for the root
        if dName not in self.ItemDico.keys():
            label = os.path.basename(
                dName) if not dName.startswith('http') else filter(
                    lambda a: a != '', dName.split('/'))[-1]
            id = self.InsertItemBefore(parent, 0, label)
            self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal)
            self.SetItemImage(id, self.fldropenidx, wx.TreeItemIcon_Expanded)
            self.SetItemBold(id)
            self.ItemDico.update({dName: id})
            self.SetPyData(id, dName)

        ### end
        if L == []:
            return
        else:
            item = L.pop(0)

            isunicode = isinstance(item, unicode)
            isstr = isinstance(item, str)
            isdict = isinstance(item, dict)

            assert not isunicode, _("Warning unicode item !")

            ### element to insert in the list
            D = []
            ### if child is build from DEVSimPy
            if isstr:

                ### parent is retrieved from dict
                parent = self.ItemDico[dName]
                assert parent != None

                ### parent path
                parentPath = self.GetPyData(parent)
                come_from_net = parentPath.startswith('http')

                ### comma replace
                item = item.strip()

                ### suppression de l'extention su .cmd (model atomic lu à partir de __init__ donc pas d'extention)
                if item.endswith('.cmd'):
                    ### gestion de l'importation de module (.py) associé au .cmd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                    if not come_from_net:
                        path = os.path.join(parentPath, item)
                        zf = Zip(path)
                        module = zf.GetModule()
                        image_file = zf.GetImage()
                    else:
                        path = "".join([parentPath, '/', item, '.py'])
                        module = load_module_from_net(path)

                    ### check error
                    error = isinstance(module, Exception)

                    ### change icon depending on the error and the presence of image in amd
                    if error:
                        img = self.not_importedidx
                    elif image_file is not None:
                        img = self.il.Add(image_file.ConvertToBitmap())
                    else:
                        img = self.coupledidx

                    ### insert into the tree
                    id = self.InsertItemBefore(parent, 0,
                                               os.path.splitext(item)[0], img,
                                               img)
                    self.SetPyData(id, path)

                elif item.endswith('.amd'):
                    ### gestion de l'importation de module (.py) associé au .amd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                    if not come_from_net:
                        path = os.path.join(parentPath, item)
                        zf = Zip(path)
                        module = zf.GetModule()
                        image_file = zf.GetImage()
                    else:
                        path = "".join([parentPath, '/', item, '.py'])
                        module = load_module_from_net(path)

                    ### check error
                    error = isinstance(module, Exception)

                    ### change icon depending on the error and the presence of image in amd
                    if error:
                        img = self.not_importedidx
                    elif image_file is not None:
                        img = self.il.Add(image_file.ConvertToBitmap())
                    else:
                        img = self.atomicidx

                    ### insertion dans le tree
                    id = self.InsertItemBefore(parent, 0,
                                               os.path.splitext(item)[0], img,
                                               img)
                    self.SetPyData(id, path)

                else:

                    path = os.path.join(parentPath, "".join(
                        [item, '.py'])) if not come_from_net else "".join(
                            [parentPath, '/', item, '.py'])

                    info = Container.CheckClass(path)

                    error = isinstance(info, tuple)
                    img = self.not_importedidx if error else self.pythonfileidx

                    ### insertion dans le tree
                    id = self.InsertItemBefore(parent, 0, item, img, img)
                    self.SetPyData(id, path)

                ### error info back propagation
                if error:
                    while (parent):
                        self.SetItemImage(parent, self.not_importedidx,
                                          wx.TreeItemIcon_Normal)
                        ### next parent item
                        parent = self.GetItemParent(parent)

                ### insertion des donnees dans l'item et gestion du ItemDico
                self.ItemDico.update({os.path.join(
                    parentPath,
                    item,
                ): id})

            ### si le fils est un sous repertoire contenant au moins un fichier (all dans __init__.py different de [])
            elif isdict and item.values() != [[]]:

                ### nom a inserer dans l'arbe
                dName = os.path.basename(item.keys()[0])

                ### nouveau parent
                parent = self.ItemDico[os.path.dirname(
                    item.keys()[0])] if not dName.startswith(
                        'http') else self.ItemDico[item.keys()[0].replace(
                            '/' + dName, '')]

                assert (parent != None)

                ### insertion de fName sous parent
                id = self.InsertItemBefore(parent, 0, dName)
                self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal)
                self.SetItemImage(id, self.fldropenidx,
                                  wx.TreeItemIcon_Expanded)

                ### stockage du parent avec pour cle le chemin complet avec extention (pour l'import du moule dans le Dnd)
                self.ItemDico.update({item.keys()[0]: id})
                self.SetPyData(id, item.keys()[0])

                ### pour les fils du sous domain
                for elem in item.values()[0]:
                    # si elem simple (modèle couple ou atomic)
                    if isstr:
                        ### remplacement des espaces
                        elem = elem.strip()  #replace(' ','')
                        ### parent provisoir
                        p = self.ItemDico[item.keys()[0]]

                        assert (p != None)

                        come_from_net = item.keys()[0].startswith('http')
                        ### si model atomic
                        if elem.endswith('.cmd'):
                            ### gestion de l'importation de module (.py) associé au .amd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                            if not come_from_net:
                                path = os.path.join(item.keys()[0], elem)
                                zf = Zip(path)
                                module = zf.GetModule()
                                image_file = zf.GetImage()
                            else:
                                path = "".join(
                                    [item.keys()[0], '/', elem, '.py'])
                                module = load_module_from_net(path)

                            ### check error
                            error = isinstance(module, Exception)

                            ### change icon depending on the error and the presence of image in amd
                            if error:
                                img = self.not_importedidx
                            elif image_file is not None:
                                img = self.il.Add(image_file.ConvertToBitmap())
                            else:
                                img = self.coupledidx

                            ### insertion dans le tree
                            id = self.InsertItemBefore(
                                p, 0,
                                os.path.splitext(elem)[0], img, img)
                            self.SetPyData(id, path)

                        elif elem.endswith('.amd'):
                            ### gestion de l'importation de module (.py) associé au .amd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                            if not come_from_net:
                                path = os.path.join(item.keys()[0], elem)
                                zf = Zip(path)
                                module = zf.GetModule()
                                image_file = zf.GetImage()
                            else:
                                path = "".join(
                                    [item.keys()[0], '/', elem, '.py'])
                                module = load_module_from_net(path)

                            ### check error
                            error = isinstance(module, Exception)

                            ### change icon depending on the error and the presence of image in amd
                            if error:
                                img = self.not_importedidx
                            elif image_file is not None:
                                img = self.il.Add(image_file.ConvertToBitmap())
                            else:
                                img = self.atomicidx

                            ### insertion dans le tree
                            id = self.InsertItemBefore(
                                p, 0,
                                os.path.splitext(elem)[0], img, img)
                            self.SetPyData(id, path)
                        else:

                            path = os.path.join(item.keys()[0], "".join(
                                [elem, '.py'])) if not item.keys(
                                )[0].startswith('http') else "".join(
                                    [item.keys()[0], '/', elem, '.py'])
                            info = Container.CheckClass(path)

                            error = isinstance(info, tuple)
                            img = self.not_importedidx if error else self.pythonfileidx

                            ### insertion dans le tree
                            id = self.InsertItemBefore(p, 0, elem, img, img)
                            self.SetPyData(id, path)

                        ### error info back propagation
                        if error:
                            ### insert error to the doc field
                            while (p):
                                self.SetItemImage(p, self.not_importedidx,
                                                  wx.TreeItemIcon_Normal)
                                ### next parent item
                                p = self.GetItemParent(p)

                        self.ItemDico.update({
                            os.path.join(item.keys()[0],
                                         os.path.splitext(elem)[0]):
                            id
                        })

                    else:
                        ### pour faire remonter l'info dans la liste
                        D.append(elem)

                ### mise a jour avec le nom complet
                dName = item.keys()[0]

            ### for spash screen
            try:
                ### format the string depending the nature of the item
                if isdict:
                    item = " ".join([
                        os.path.basename(item.keys()[0]), 'from',
                        os.path.basename(os.path.dirname(item.keys()[0]))
                    ])
                else:
                    item = " ".join([item, 'from', os.path.basename(dName)])

                pub.sendMessage('object.added',
                                message='Loading %s domain...' % item)
            except:
                pass

            ### gestion de la recursion
            if D != []:
                return self.InsertNewDomain(dName, parent, L + D)
            else:
                return self.InsertNewDomain(dName, parent, L)
Example #33
0
class SimulationDialog(wx.Frame, wx.Panel):
    """ SimulationDialog(parent, id, title, master)

		Frame or Panel with progress bar
	"""
    def __init__(self, parent, id, title, master):
        """ Constructor
		"""

        if isinstance(parent, wx.Panel):
            wx.Panel.__init__(self, parent, id)
            self.SetBackgroundColour(wx.NullColour)
            self.panel = self

            ### panel inherit of the left splitter size
            self.panel.SetSize(parent.GetParent().GetSize())

            # status bar of main application
            self.statusbar = parent.GetTopLevelParent().statusbar
        else:
            wx.Frame.__init__(self,
                              parent,
                              id,
                              title,
                              style=wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)

            ### adapt size of frame depending on the plate-form
            if '__WXMSW__' in wx.PlatformInfo:
                self.SetSize((320, 280))
            else:
                self.SetSize((280, 160))

            # disable the roll out of the frame
            self.SetMinSize(self.GetSize())

            self.panel = wx.Panel(self, -1)

            wx.CallAfter(self.CreateBar)

            self.__set_properties()

        # local copy
        self.parent = parent
        self.master = master
        self.title = title

        ### current master for multi-simulation without simulationDialog reloading (show OnOk)
        self.current_master = None

        # simulator strategy
        self.selected_strategy = DEFAULT_SIM_STRATEGY

        ### profiling simulation with hotshot
        self.prof = False

        ### No time limit simulation (defined in the builtin dictionary from .devsimpy file)
        self.ntl = __builtin__.__dict__['NTL']

        self.verbose = False

        # definition of the thread, the timer and the counter for the simulation progress
        self.thread = None
        self.timer = wx.Timer(self, wx.NewId())
        self.count = 10.0
        self.stdioWin = None

        self.__widgets()
        self.__do_layout()
        self.__set_events()

        ### create a pubsub receiver (simple way to communicate with thread)
        Publisher.subscribe(self.ErrorManager, "error")

    def CreateBar(self):
        self.statusbar = self.CreateStatusBar(2)

    def __set_properties(self):
        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(
            wx.Bitmap(os.path.join(ICON_PATH_16_16, "simulation.png"),
                      wx.BITMAP_TYPE_ANY))
        self.SetIcon(icon)

        self.Center()

    def __widgets(self):

        self._text1 = wx.StaticText(self.panel, wx.ID_ANY, _('Final time:'))
        self._value = wx.TextCtrl(self.panel,
                                  wx.ID_ANY,
                                  str(float(self.master.FINAL_TIME)),
                                  validator=TextObjectValidator())
        self._btn1 = wx.Button(self.panel, wx.NewId(), _('Run'))
        self._btn2 = wx.Button(self.panel, wx.NewId(), _('Stop'))
        self._btn3 = wx.Button(self.panel, wx.NewId(), _('Suspend'))
        self._btn4 = wx.Button(self.panel, wx.NewId(), _('Log'))
        self._gauge = wx.Gauge(self.panel,
                               wx.ID_ANY,
                               100,
                               size=(-1, 25),
                               style=wx.GA_HORIZONTAL | wx.GA_SMOOTH)
        self._cp = CollapsiblePanel(self.panel, self)

        self._text1.Enable(not self.ntl)
        self._value.Enable(not self.ntl)

        self._btn1.SetToolTipString(_("Begin simulation process."))
        self._btn2.SetToolTipString(_("Stop the simulation process."))
        self._btn3.SetToolTipString(_("Suspend the simulation process."))
        self._btn4.SetToolTipString(
            _("Launch the log window (often depends on some plug-ins (verbose, activity, ...))."
              ))

    def __do_layout(self):

        #vbox_top = wx.BoxSizer(wx.VERTICAL)
        vbox_body = wx.BoxSizer(wx.VERTICAL)

        #panel 1
        grid1 = wx.GridSizer(1, 2)
        grid1.Add(self._text1, 0,
                  wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)
        grid1.Add(self._value, 1, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL)

        # panel2
        grid2 = wx.GridSizer(3, 2, 2, 2)
        grid2.Add(
            self._btn1, 0,
            wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND)
        grid2.Add(
            self._btn3, 0,
            wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND)
        grid2.Add(
            self._btn2, 0,
            wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND)
        grid2.Add(
            self._btn4, 0,
            wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND)

        # panel4
        #hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        #hbox1.Add(self._gauge, 1, wx.EXPAND, 9)

        ## panel5
        #hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        #hbox2.Add(self._cp, 1, wx.EXPAND, 9)

        vbox_body.Add(grid1, 0, wx.EXPAND, 9)
        vbox_body.Add(grid2, 0, wx.EXPAND, 9)
        vbox_body.Add(self._gauge, 0, wx.EXPAND, 9)
        vbox_body.Add(self._cp, 0, wx.EXPAND, 9)

        # fin panel
        #vbox_top.Add(vbox_body, 0, wx.EXPAND|wx.ALL, 9)
        self.panel.SetSizer(vbox_body)

        #		vbox_body.Fit(self)

        self._text1.SetFocus()
        self._btn1.SetDefault()
        self._btn2.Disable()
        self._btn3.Disable()

    ###
    def __set_events(self):

        ### binding event
        self.Bind(wx.EVT_BUTTON, self.OnOk, self._btn1)
        self.Bind(wx.EVT_BUTTON, self.OnStop, self._btn2)
        self.Bind(wx.EVT_BUTTON, self.OnSuspend, self._btn3)
        self.Bind(wx.EVT_BUTTON, self.OnViewLog, self._btn4)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.Bind(wx.EVT_TEXT, self.OnText, self._value)
        self.Bind(wx.EVT_CLOSE, self.OnQuit)

    ###
    def ChangeButtonLabel(self, btn, new_label):
        """ Change the label of the Log button depending on the active plug-in
		"""

        ### if activity plug-in is enabled
        if is_enable('start_activity_tracking'):
            self._btn4.SetLabel("Activity")

    ###
    def OnText(self, event):
        self._gauge.SetValue(0)

    ###
    @BuzyCursorNotification
    def OnViewLog(self, event):
        """	When View button is clicked
		"""
        # The simulation verbose event occurs
        trigger_event("START_SIM_VERBOSE", parent=self)

        # The simulation verbose event occurs
        trigger_event("VIEW_ACTIVITY_REPORT",
                      parent=self,
                      master=self.current_master)

    ###
    def OnOk(self, event):
        """ When Run button is clicked
		"""

        assert (self.master is not None)

        if self._value.GetValidator().Validate(self._value) or self.ntl:

            ### pour prendre en compte les simulations multiples sans relancer un SimulationDialog
            ### si le thread n'est pas lancé (pas pendant un suspend)
            if self.thread is not None and not self.thread.thread_suspend:
                diagram = self.master.getBlockModel()
                diagram.Clean()
                self.current_master = Container.Diagram.makeDEVSInstance(
                    diagram)
            else:
                self.current_master = self.master

            if isinstance(self.parent, wx.Panel):
                # redirection du stdout ici dans le cas du Panel (sinon dans OnSimulation)
                mainW = self.parent.GetTopLevelParent()
                sys.stdout = mainW.stdioWin

            ### test si le modele et bien charge
            if (self.current_master
                    == None) or (self.current_master.componentSet == []):
                return self.MsgBoxEmptyModel()

            ### dont erase the gauge if ntl
            if not self.ntl:
                # stockage du temps de simulation dans le master
                self.current_master.FINAL_TIME = float(self._value.GetValue())
                self._gauge.SetValue(0)
                ### if _gauge is wx.Slider
                #self._gauge.SetMax(self.current_master.FINAL_TIME)

            self.statusbar.SetBackgroundColour('')
            self.statusbar.SetStatusText("", 1)
            if self.statusbar.GetFieldsCount() > 2:
                self.statusbar.SetStatusText("", 2)

            if (self.thread is None) or (not self.timer.IsRunning()):

                trigger_event("START_BLINK",
                              parent=self,
                              master=self.current_master)
                trigger_event("START_TEST",
                              parent=self,
                              master=self.current_master)

                ### The START_ACTIVITY_TRACKING event occurs
                trigger_event("START_ACTIVITY_TRACKING",
                              parent=self,
                              master=self.current_master)

                ### The START_ACTIVITY_TRACKING event occurs
                trigger_event("START_STATE_TRAJECTORY",
                              parent=self,
                              master=self.current_master)

                ### The START_CONCURRENT_SIMULATION event occurs
                trigger_event("START_CONCURRENT_SIMULATION",
                              parent=self,
                              master=self.current_master)

                ### future call is required because the simulator is flattened during the execution of the strategy 3
                wx.FutureCall(1,
                              trigger_event,
                              'START_DIAGRAM',
                              parent=self,
                              master=self.current_master)

                ### clear all log file
                for fn in filter(lambda f: f.endswith('.devsimpy.log'),
                                 os.listdir(gettempdir())):
                    os.remove(os.path.join(gettempdir(), fn))

                self.thread = simulator_factory(self.current_master,
                                                self.selected_strategy,
                                                self.prof, self.ntl,
                                                self.verbose)
                self.thread.setName(self.title)

                ### si le modele n'a pas de couplage, ou si pas de generateur: alors pas besoin de simuler
                if self.thread.end_flag:
                    self.OnTimer(event)
                else:
                    self.timer.Start(100)

            else:
                #print self.thread.getAlgorithm().trace
                ### for back simulation
                #self.thread.s = shelve.open(self.thread.f.name+'.db',flag='r')
                #self.thread.model = self.thread.s['s'][str(float(self._gauge.GetValue()))]

                ### restart the hiding gauge
                if self.ntl:
                    self._gauge.Show()

                ### restart thread
                self.thread.resume_thread()

            self.Interact(False)

            if self.count >= 100:
                return

            # aucune possibilité d'interagir avec le modele
            #self.parent.Enable(False)

    def Interact(self, access=True):
        """ Enabling and disabling options (buttons, checkbox, ...)
		"""

        self._btn1.Enable(access)
        self._btn2.Enable(not access)
        self._btn3.Enable(not access)
        self._value.Enable(not self.ntl)
        self._cp.Enable(access)

    ###
    def OnStop(self, event):
        """ When Stop button is clicked
		"""

        self.Interact()
        self.thread.terminate()
        self.timer.Stop()
        wx.Bell()

        self._gauge.SetValue(0)
        self.statusbar.SetBackgroundColour('')
        self.statusbar.SetStatusText(_('Interrupted'), 0)
        self.statusbar.SetStatusText("", 1)
        if self.statusbar.GetFieldsCount() > 2:
            self.statusbar.SetStatusText("", 2)

    ###
    def OnSuspend(self, event):
        """ When Stop button is clicked
		"""

        self.Interact()
        self.thread.suspend()

        if self.ntl:
            self._gauge.Hide()

        if self.count == 0 or self.count >= 100 or not self.timer.IsRunning():
            return

        self.statusbar.SetStatusText(_('Suspended'), 0)

        # way to interact with the model
        #self.parent.Enable(True)
        wx.Bell()

    ###
    def OnTimer(self, event):
        """ Give the pourcentage of simulation progress
		"""

        ### if no time limit, gauge pulse
        if self.ntl:
            self._gauge.Pulse()
        else:
            if not isinstance(self.thread.model.timeLast, tuple):
                timeLast = self.thread.model.timeLast
            else:
                timeLast = self.thread.model.timeLast[0]

            self.count = (timeLast / self.thread.model.FINAL_TIME) * 100

            self._gauge.SetValue(self.count)

        ### if simulation is over
        if self.thread.end_flag:

            ### update the status of buttons
            self._btn1.Enable(True)
            self._btn2.Disable()
            self._btn3.Disable()
            self._value.Enable(not self.ntl)
            self._cp.Enable()

            ### check if gauge is full (can appear if timer is too slow)
            if self.count != 100:
                self.count = 100
                self._gauge.SetValue(self.count)

            ### update the status bar
            self.statusbar.SetBackgroundColour('')
            self.statusbar.SetStatusText(_("Completed!"), 0)
            self.statusbar.SetStatusText("%0.4f s" % (self.thread.cpu_time), 1)

            ### is no time limit add some informations in status bar
            if not self.ntl:
                if self.statusbar.GetFieldsCount() > 2:
                    self.statusbar.SetStatusText(str(100) + "%", 2)

            ### stop the timer
            self.timer.Stop()

        ### if the simulation is suspended
        elif not self.thread.thread_suspend:
            ### udpate the status bar
            self.statusbar.SetBackgroundColour('GREY')
            self.statusbar.SetStatusText(_("Processing..."), 0)
            self.statusbar.SetStatusText("%0.4f s" % (self.thread.cpu_time), 1)

            ### is no time limit, add some information in status bar
            if not self.ntl:
                if self.statusbar.GetFieldsCount() > 2:
                    self.statusbar.SetStatusText(str(self.count)[:4] + "%", 2)

            #wx.Yield()
            wx.YieldIfNeeded()

    ###
    def MsgBoxEmptyModel(self):
        """ Pop-up alert for empty model
		"""
        dial = wx.MessageDialog(
            self, _('You want to simulate an empty master model!'),
            _('Simulation Manager'), wx.OK | wx.ICON_EXCLAMATION)

        if (dial.ShowModal() == wx.ID_OK) and (isinstance(
                self.parent, wx.Frame)):
            self.DestroyWin()
        else:
            return

    def DestroyWin(self):
        """ To destroy the simulation frame
		"""

        ### clean status bar
        self.statusbar.SetBackgroundColour('')
        self.statusbar.SetFields([""] * self.statusbar.GetFieldsCount())

        ### try to hidden stdioWin
        try:
            self.parent.stdioWin.frame.Show(False)
        except:
            pass

        try:
            ## left panel enabled
            nb1 = self.parent.mainW.GetControlNotebook()
            nb1.Enable()

            ## menu enabled
            self.parent.tb.Enable()
            for i in xrange(self.parent.menuBar.GetMenuCount()):
                self.parent.menuBar.EnableTop(i, True)

            ### other tab diagram enabled
            nb2 = self.parent.GetDiagramNotebook()
            for p in xrange(nb2.GetPageCount()):
                ## pour tout les tab non selectionner
                if p != nb2.GetSelection():
                    nb2.GetPage(p).Enable()

        except Exception:
            #sys.stdout.write(_("Empty mode over\n"))
            pass

        ### destroy the frame
        self.Destroy()

    def OnQuit(self, event):
        """ When the simulation are stopping
		"""

        # if the simulation is running
        if self.timer.IsRunning():
            dial = wx.MessageDialog(
                self, _('Are you sure to stop simulation?'),
                _('Simulation Manager'),
                wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
            self.thread.suspend()

            ### if user wants to stop simulation process
            if dial.ShowModal() == wx.ID_YES:
                self.DestroyWin()
                self.thread.terminate()
            else:
                self.thread.resume_thread()

        else:
            self.DestroyWin()

    def ErrorManager(self, msg):
        """ An error is occurred.
		"""

        ### try to find the file which have the error from traceback
        devs_error = False
        try:
            typ, val, tb = msg.data
            trace = traceback.format_exception(typ, val, tb)

            mainW = wx.GetApp().GetTopWindow()
            ### paths in traceback
            paths = filter(
                lambda a: a.split(',')[0].strip().startswith('File'), trace)
            ### find if DOMAIN_PATH is in paths list (inversed because traceback begin by the end)
            for path in paths[::-1]:
                ### find if one path in trace comes from Domain or exported path list
                for d in [DOMAIN_PATH] + mainW.GetExportPathsList():

                    if d in path:
                        devs_error = True
                        break

        except Exception, info:
            print _("Error in ErrorManager: %s" % info)

        ### if error come from devs python file
        if devs_error:

            ### simulate event button for the code editor
            event = wx.PyCommandEvent(wx.EVT_BUTTON.typeId, self._btn1.GetId())

            ### Error dialog
            if not Container.MsgBoxError(event, self.parent, msg.data):
                ### if user dont want correct the error, we destroy the simulation windows
                self.DestroyWin()
            else:
                ### if user want to correct error through an editor, we stop simulation process for trying again after the error is corrected.
                self.OnStop(event)
        else:

            raise msg
Example #34
0
# First Python Project
from Container import *

container1 = Container("OCL", "Clothes")
container2 = Container("MAS", "Electronics")
container3 = Container("AML", "Foods")
container4 = Container._create_empty_container("BML")

while True:
    print("please provide a number: 12")
    response = input()
    if (int(response) % 7 == 0):
        print("it's reminder of 0")
        break
    else:
        print("not a reminder of 7.")
Example #35
0
    def InsertNewDomain(self, dName, parent, L=[]):
        """ Recurrent function that insert new Domain on library panel.
		"""

        ### first only for the root
        if dName not in list(self.ItemDico.keys()):

            label = os.path.basename(dName) if not dName.startswith(
                'http') else [a for a in dName.split('/') if a != ''][-1]
            id = self.InsertItemBefore(parent, 0, label)
            self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal)
            self.SetItemImage(id, self.fldropenidx, wx.TreeItemIcon_Expanded)
            self.SetItemBold(id)
            self.ItemDico.update({dName: id})
            self.SetPyData(id, dName)

        ### end
        if L == []:
            return
        else:
            item = L.pop(0)

            isunicode = isinstance(item, str)
            isstr = isinstance(item, str)
            isdict = isinstance(item, dict)

            ### element to insert in the list
            D = []
            ### if child is build from DEVSimPy
            if isstr:

                ### parent is retrieved from dict
                parent = self.ItemDico[dName]
                assert parent != None

                ### parent path
                parentPath = self.GetPyData(parent)
                come_from_net = parentPath.startswith('http')

                ### comma replace
                item = item.strip()

                ### suppression de l'extention su .cmd (model atomic lu à partir de __init__ donc pas d'extention)
                if item.endswith('.cmd'):
                    ### gestion de l'importation de module (.py) associé au .cmd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                    if not come_from_net:
                        path = os.path.join(parentPath, item)
                        zf = Zip(path)
                        module = zf.GetModule()
                        image_file = zf.GetImage()
                    else:
                        path = "".join([parentPath, '/', item, '.py'])
                        module = load_module_from_net(path)

                    ### check error
                    error = isinstance(module, Exception)

                    ### change icon depending on the error and the presence of image in amd
                    if error:
                        img = self.not_importedidx
                    elif image_file is not None:
                        img = self.il.Add(image_file.ConvertToBitmap())
                    else:
                        img = self.coupledidx

                    ### insert into the tree
                    id = self.InsertItemBefore(parent, 0,
                                               os.path.splitext(item)[0], img,
                                               img)
                    self.SetPyData(id, path)

                    self.MetricDico.update(
                        {id: {
                            'mcc': 0.0,
                            'parent': parent
                        }})
                    s = sum([
                        d['mcc'] for id, d in self.MetricDico.items()
                        if d['parent'] == parent
                    ])
                    self.MetricDico.update(
                        {parent: {
                            'mcc': s,
                            'parent': None
                        }})

                elif item.endswith('.amd'):
                    ### gestion de l'importation de module (.py) associé au .amd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                    if not come_from_net:
                        path = os.path.join(parentPath, item)
                        zf = Zip(path)
                        module = zf.GetModule()
                        image_file = zf.GetImage()
                    else:
                        path = "".join([parentPath, '/', item, '.py'])
                        module = load_module_from_net(path)

                    ### check error
                    error = isinstance(module, Exception)

                    ### change icon depending on the error and the presence of image in amd
                    if error:
                        img = self.not_importedidx
                    elif image_file is not None:
                        img = self.il.Add(image_file.ConvertToBitmap())
                    else:
                        img = self.atomicidx

                    mcc = GetMacCabeMetric(path)

                    ### insert in the tree
                    id = self.InsertItemBefore(parent, 0,
                                               os.path.splitext(item)[0], img,
                                               img)
                    self.SetPyData(id, path)

                    self.MetricDico.update(
                        {id: {
                            'mcc': mcc,
                            'parent': parent
                        }})
                    s = sum([
                        d['mcc'] for id, d in self.MetricDico.items()
                        if d['parent'] == parent
                    ])
                    self.MetricDico.update(
                        {parent: {
                            'mcc': s,
                            'parent': None
                        }})

                else:

                    path = os.path.join(parentPath, "".join(
                        [item, '.py'])) if not come_from_net else "".join(
                            [parentPath, '/', item, '.py'])

                    ### try for .pyc
                    ispyc = False
                    if not os.path.exists(path):
                        path = os.path.join(parentPath, "".join(
                            [item, '.pyc'])) if not come_from_net else "".join(
                                [parentPath, '/', item, '.pyc'])
                        ispyc = True

                    devs = Container.CheckClass(path)

                    #mcc = float(subprocess.check_output('python {} {}'.format('Complexity.py', path), shell = True))
                    mcc = GetMacCabeMetric(path)

                    error = isinstance(devs, tuple)
                    img = self.not_importedidx if error else self.pythoncfileidx if ispyc else self.pythonfileidx

                    ### insert in the tree
                    id = self.InsertItemBefore(parent, 0, item, img, img)
                    self.SetPyData(id, path)

                    self.MetricDico.update(
                        {id: {
                            'mcc': mcc,
                            'parent': parent
                        }})
                    s = sum([
                        d['mcc'] for id, d in self.MetricDico.items()
                        if d['parent'] == parent
                    ])
                    self.MetricDico.update(
                        {parent: {
                            'mcc': s,
                            'parent': None
                        }})

                ### error info back propagation
                if error:
                    while (parent):
                        self.SetItemImage(parent, self.not_importedidx,
                                          wx.TreeItemIcon_Normal)
                        ### next parent item
                        parent = self.GetItemParent(parent)

                ### insertion des donnees dans l'item et gestion du ItemDico
                self.ItemDico.update({os.path.join(
                    parentPath,
                    item,
                ): id})

            ### si le fils est un sous repertoire contenant au moins un fichier (all dans __init__.py different de [])
            elif isdict and list(item.values()) != [[]]:

                ### name to insert in the tree
                dName = os.path.basename(list(item.keys())[0])

                ### new parent
                parent = self.ItemDico[os.path.dirname(
                    list(item.keys())[0]
                )] if not dName.startswith('http') else self.ItemDico[list(
                    item.keys())[0].replace('/' + dName, '')]

                assert (parent != None)

                ### insert of the fName above the parent
                id = self.InsertItemBefore(parent, 0, dName)

                self.SetItemBold(id)

                self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal)
                self.SetItemImage(id, self.fldropenidx,
                                  wx.TreeItemIcon_Expanded)

                ### stockage du parent avec pour cle le chemin complet avec extention (pour l'import du moule dans le Dnd)
                self.ItemDico.update({list(item.keys())[0]: id})
                self.SetPyData(id, list(item.keys())[0])

                self.MetricDico.update({id: {'mcc': 0.0, 'parent': parent}})
                self.MetricDico.update({parent: {'mcc': 0.0, 'parent': None}})

                ### for the childrens of the sub-domain
                for elem in list(item.values())[0]:
                    # si elem simple (modèle couple ou atomic)
                    if isinstance(elem, str):
                        ### replace the spaces
                        elem = elem.strip()  #replace(' ','')

                        ### parent provisoir
                        p = self.ItemDico[list(item.keys())[0]]
                        assert (p != None)
                        come_from_net = list(item.keys())[0].startswith('http')
                        ### si model atomic
                        if elem.endswith('.cmd'):
                            ### gestion de l'importation de module (.py) associé au .amd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                            if not come_from_net:
                                path = os.path.join(list(item.keys())[0], elem)
                                zf = Zip(path)
                                module = zf.GetModule()
                                image_file = zf.GetImage()
                            else:
                                path = "".join(
                                    [list(item.keys())[0], '/', elem, '.py'])
                                module = load_module_from_net(path)

                            ### check error
                            error = isinstance(module, Exception)

                            ### change icon depending on the error and the presence of image in amd
                            if error:
                                img = self.not_importedidx
                            elif image_file is not None:
                                img = self.il.Add(image_file.ConvertToBitmap())
                            else:
                                img = self.coupledidx

                            ### insertion dans le tree
                            id = self.InsertItemBefore(
                                p, 0,
                                os.path.splitext(elem)[0], img, img)
                            self.SetPyData(id, path)

                            self.MetricDico.update(
                                {id: {
                                    'mcc': 0.0,
                                    'parent': parent
                                }})
                            s = sum([
                                d['mcc'] for id, d in self.MetricDico.items()
                                if d['parent'] == parent
                            ])
                            self.MetricDico.update(
                                {parent: {
                                    'mcc': s,
                                    'parent': None
                                }})

                        elif elem.endswith('.amd'):
                            ### gestion de l'importation de module (.py) associé au .amd si le fichier .py n'a jamais été decompresssé (pour edition par exemple)
                            if not come_from_net:
                                path = os.path.join(list(item.keys())[0], elem)
                                zf = Zip(path)
                                module = zf.GetModule()
                                image_file = zf.GetImage()
                            else:
                                path = "".join(
                                    [list(item.keys())[0], '/', elem, '.py'])
                                module = load_module_from_net(path)

                            ### check error
                            error = isinstance(module, Exception)

                            ### change icon depending on the error and the presence of image in amd
                            if error:
                                img = self.not_importedidx
                            elif image_file is not None:
                                img = self.il.Add(image_file.ConvertToBitmap())
                            else:
                                img = self.atomicidx

                            mcc = GetMacCabeMetric(path)

                            ### insert in the tree
                            id = self.InsertItemBefore(
                                p, 0,
                                os.path.splitext(elem)[0], img, img)
                            self.SetPyData(id, path)

                            self.MetricDico.update(
                                {id: {
                                    'mcc': mcc,
                                    'parent': parent
                                }})
                            s = sum([
                                d['mcc'] for id, d in self.MetricDico.items()
                                if d['parent'] == parent
                            ])
                            self.MetricDico.update(
                                {parent: {
                                    'mcc': s,
                                    'parent': None
                                }})

                        else:

                            path = os.path.join(
                                list(item.keys())[0],
                                "".join([elem, '.py'])) if not list(item.keys(
                                ))[0].startswith('http') else list(
                                    item.keys())[0] + '/' + elem + '.py'
                            ### try for .pyc file
                            ispyc = False
                            if not os.path.exists(path):
                                path = os.path.join(
                                    list(item.keys())[0], "".join([
                                        elem, '.pyc'
                                    ])) if not list(item.keys(
                                    ))[0].startswith('http') else list(
                                        item.keys())[0] + '/' + elem + '.pyc'
                                ispyc = True

                            devs = Container.CheckClass(path)

                            mcc = GetMacCabeMetric(path)

                            error = isinstance(devs, tuple)
                            img = self.not_importedidx if error else self.pythoncfileidx if ispyc else self.pythonfileidx

                            ### insert in the tree
                            id = self.InsertItemBefore(p, 0, elem, img, img)
                            self.SetPyData(id, path)
                            self.MetricDico.update(
                                {id: {
                                    'mcc': mcc,
                                    'parent': parent
                                }})

                            s = sum([
                                d['mcc'] for id, d in self.MetricDico.items()
                                if d['parent'] == parent
                            ])
                            self.MetricDico.update(
                                {parent: {
                                    'mcc': s,
                                    'parent': None
                                }})

                        ### error info back propagation
                        if error:
                            ### insert error to the doc field
                            while (p):
                                self.SetItemImage(p, self.not_importedidx,
                                                  wx.TreeItemIcon_Normal)
                                ### next parent item
                                p = self.GetItemParent(p)

                        self.ItemDico.update(
                            {os.path.join(list(item.keys())[0], elem): id})

                    else:
                        ### in order to go up the information in the list
                        D.append(elem)

                ### update with whole name
                dName = list(item.keys())[0]

            ### for spash screen
            try:
                ### format the string depending the nature of the item
                if isdict:
                    item = " ".join([
                        os.path.basename(list(item.keys())[0]), 'from',
                        os.path.basename(os.path.dirname(list(item.keys())[0]))
                    ])
                else:
                    item = " ".join([item, 'from', os.path.basename(dName)])

                pub.sendMessage('object.added',
                                message='Loading %s domain...' % item)
            except:
                pass

            ### managment of the recursion
            if D != []:
                self.InsertNewDomain(dName, parent, D)

            try:
                self.SortChildren(parent)
            except:
                pass

            return self.InsertNewDomain(dName, parent, L)
Example #36
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 13:08:32 2019

@author: rosto
"""

import Row
import Container

r = Row.Row()
r2 = Row.Row()
c = Container.Container()
c.add_child(r)
c.add_child(r2)

print(c.to_html())
Example #37
0
    def SelectProp(self, evt):
        """
		"""

        row, col = evt.GetRow(), evt.GetCol()

        table = self.GetTable()

        typ = table.dataTypes[row][1]
        prop = self.GetCellValue(row, 0)

        if prop == 'fill' or re.findall(
                "[.]*color[.]*", prop, flags=re.IGNORECASE):
            val = self.GetCellValue(row, 1)
            dlg = wx.ColourDialog(self.parent)
            dlg.GetColourData().SetChooseFull(True)
            if dlg.ShowModal() == wx.ID_OK:
                data = dlg.GetColourData()
                val = str([RGBToHEX(data.GetColour().Get())])
                self.SetCellValue(row, 1, val)
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'font':
            val = eval(self.GetCellValue(row, 1))
            default_font = wx.Font(val[0], val[1], val[2], val[3], False,
                                   val[4])
            data = wx.FontData()
            if sys.platform == 'win32':
                data.EnableEffects(True)
            data.SetAllowSymbols(False)
            data.SetInitialFont(default_font)
            data.SetRange(10, 30)
            dlg = wx.FontDialog(self.parent, data)
            if dlg.ShowModal() == wx.ID_OK:
                data = dlg.GetFontData()
                font = data.GetChosenFont()
                color = data.GetColour()
                val = [
                    font.GetPointSize(),
                    font.GetFamily(),
                    font.GetStyle(),
                    font.GetWeight(),
                    font.GetFaceName()
                ]
                self.SetCellValue(row, 1, str(val))
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'label':

            d = LabelGUI.LabelDialog(self.parent, self.parent.model)
            d.ShowModal()

            self.SetCellValue(row, 1, str(self.parent.model.label))
            self.AcceptProp(row, col)

        elif prop == 'image_path':

            dlg = ib.ImageDialog(self, os.path.join(HOME_PATH))
            dlg.Centre()

            if dlg.ShowModal() == wx.ID_OK:
                val = os.path.normpath(dlg.GetFile())
                if val != self.GetCellValue(row, 1):
                    self.SetCellValue(row, 1, val)
                    self.canvas.UpdateShapes([self.parent.model])
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif 'filename' in str(prop).lower():
            wcd = _('Data files All files (*)|*')
            val = self.GetCellValue(row, 1)
            default_dir = os.path.dirname(val) if os.path.exists(
                os.path.dirname(val)) else HOME_PATH
            dlg = wx.FileDialog(self,
                                message=_("Select file ..."),
                                defaultDir=default_dir,
                                defaultFile="",
                                wildcard=wcd,
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                val = os.path.normpath(dlg.GetPath())
                if val != self.GetCellValue(row, 1):
                    self.SetCellValue(row, 1, val)
                    self.canvas.UpdateShapes([self.parent.model])
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'python_path':

            model = self.parent.model

            ### for .amd or .cmd
            if model.model_path != '':
                wcd = _(
                    'Atomic DEVSimPy model (*.amd)|*.amd|Coupled DEVSimPy model (*.cmd)|*.cmd|All files (*)|*'
                )
            else:
                wcd = _('Python files (*.py)|*.py|All files (*)|*')

            default_dir = os.path.dirname(model.python_path) if os.path.exists(
                os.path.dirname(model.python_path)) else DOMAIN_PATH
            dlg = wx.FileDialog(self,
                                message=_("Select file ..."),
                                defaultDir=default_dir,
                                defaultFile="",
                                wildcard=wcd,
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                new_python_path = os.path.normpath(dlg.GetPath())

                ### if the user would like to load a compressed python file, he just give the name of compressed file that contain the python file
                if zipfile.is_zipfile(new_python_path):
                    zf = zipfile.ZipFile(new_python_path, 'r')
                    new_python_path = os.path.join(
                        new_python_path,
                        filter(
                            lambda f: f.endswith('.py') and f != 'plugins.py',
                            zf.namelist())[0])
                    ### update model path
                    model.model_path = os.path.dirname(new_python_path)

                self.SetCellValue(row, 1, new_python_path)

                # behavioral args update (because depends of the new class coming from new python file)
                new_cls = Components.GetClass(new_python_path)

                if inspect.isclass(new_cls):

                    ### update attributes (behavioral ang graphic)
                    model.args = Components.GetArgs(new_cls)
                    model.SetAttributes(Attributable.GRAPHICAL_ATTR)

                    ### TODO: when ScopeGUI and DiskGUI will be amd models, delete this line)
                    ### delete xlabel and ylabel attributes if exist
                    model.RemoveAttribute('xlabel')
                    model.RemoveAttribute('ylabel')
                    ### Update of DEVSimPy model from new python behavioral file (ContainerBlock is not considered because he did not behavioral)
                    if new_cls.__name__ in ('To_Disk', 'MessagesCollector'):
                        model.__class__ = Container.DiskGUI
                    elif new_cls.__name__ == 'QuickScope':
                        model.__class__ = Container.ScopeGUI
                        model.AddAttribute("xlabel")
                        model.AddAttribute("ylabel")
                    elif True in map(lambda a: 'DomainStructure' in str(a),
                                     new_cls.__bases__):
                        model.__class__ = Container.ContainerBlock
                    else:
                        model.__class__ = Container.CodeBlock

                    ### if we change the python file from zipfile we compresse the new python file and we update the python_path value
                    if zipfile.is_zipfile(model.model_path):
                        zf = ZipManager.Zip(model.model_path)
                        zf.Update([new_python_path])
                        #model.model_path =

                    ### update flag and color if bad filename
                    if model.bad_filename_path_flag:
                        model.bad_filename_path_flag = False
                else:
                    Container.MsgBoxError(evt, self, new_cls)
                    dlg.Destroy()
                    return False
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif typ == "list":
            frame = ListEditor(self,
                               wx.ID_ANY,
                               _('List editor'),
                               values=self.GetCellValue(row, 1))
            if frame.ShowModal() == wx.ID_CANCEL:
                self.SetCellValue(row, 1, frame.GetValueAsString())
            else:
                frame.Destroy()

            self.AcceptProp(row, col)

        elif typ == 'dict':
            frame = DictionaryEditor(self,
                                     wx.ID_ANY,
                                     _('List editor'),
                                     values=self.GetCellValue(row, 1))
            if frame.ShowModal() == wx.ID_CANCEL:
                self.SetCellValue(row, 1, frame.GetValueAsString())
            else:
                frame.Destroy()

            self.AcceptProp(row, col)
        elif 'choice' in typ:
            self.AcceptProp(row, col)
        else:
            pass

        ### all properties grid update (because the python classe has been changed)
        ### here, because OnAcceptProp should be executed before
        if prop == 'python_path':

            ### Update table from new model
            table.UpdateRowBehavioralData(model)
            self.SetTable(table, False)
            self.ForceRefresh()
            self.AutoSizeColumns()

            # code updating
            if isinstance(model, Achievable):
                new_code = CodeCB(self.parent, wx.ID_ANY, model)
                #self.parent.boxH.Remove(0)
                if hasattr(self.parent, '_boxH'):
                    # DeleteWindows work better in vista
                    if wx.VERSION_STRING < '4.0':
                        self.parent._boxH.DeleteWindows()
                        self.parent._boxH.AddWindow(new_code,
                                                    1,
                                                    wx.EXPAND,
                                                    userData='code')
                    else:
                        self.parent._boxH.Clear()
                        self.parent._boxH.Add(new_code,
                                              1,
                                              wx.EXPAND,
                                              userData='code')

                    self.parent._boxH.Layout()
                else:
                    sys.stdout.write("_boxH is unknown!")