Esempio n. 1
0
 def __init__(self, extension, filetype, token):
     self.extension = extension
     self.token = token
     self.color = Colors()
     self.drive = dropbox.Dropbox(self.token)
     self.shareds = []
     self.filetype = filetype
Esempio n. 2
0
    def loadDescription(self, startPara, nrPara):
        readme = QFile(self.readmePath)
        if not readme.open(QFile.ReadOnly):
            Colors.debug("- MenuContentItem.loadDescription: Could not load:", self.readmePath)
            return ""

        in_str = QTextStream(readme)
        # Skip a certain number of paragraphs.
        while startPara:
            if not in_str.readLine():
                startPara -= 1

        # Read in the number of wanted paragraphs.
        result = ""
        line = in_str.readLine()
        while True:
            result += line + " "
            line = in_str.readLine()
            if not line:
                nrPara -= 1
                line = "<br><br>" + in_str.readLine()

            if nrPara == 0 or in_str.atEnd():
                break

        return Colors.contentColor + result
Esempio n. 3
0
	def __init__(self, graphData):
		
		VdxRecord.__init__(self)
		self.graphData = graphData
		self.colors = Colors()
		# self.graphData = self.GraphDataImpl()
		"""
		up to the first 7 elements work, from then on the VDX cannot be imported!
		e.g., 
		# self.edgeData = self.graphData.getEdgeData()[:6] # works
		# self.edgeData = self.graphData.getEdgeData()[:7] # does NOT work
		"""
		# self.edgeData = self.graphData.getEdgeData()
		self.edgeData = self.graphData.getEdgeData()

		if len(self.edgeData) == 0:
			self.addEmptyGraphNode()
			return

		self.layout = Layout (self.edgeData, **self.layout_args)
		if self.verbose:
			print self.layout
	
		self.addNodes();
		
		self.addEdges();
Esempio n. 4
0
    def getResource(self, name):
        ba = self.helpEngine.fileData(QtCore.QUrl(name))

        if ba.isEmpty():
            Colors.debug(" - WARNING: Could not get", name)

        return ba
Esempio n. 5
0
    def createContent(self):
        # Create the items.
        self.heading = HeadingItem(self.name, self.scene(), self)
        para1 = self.loadDescription(0, 1)
        if not para1:
            para1 = Colors.contentColor + "Could not load description. Ensure that the documentation for Qt is built."
        bgcolor = Colors.sceneBg1.darker(200)
        bgcolor.setAlpha(100)
        self.description1 = DemoTextItem(para1, Colors.contentFont(),
                                         Colors.heading, 500, self.scene(),
                                         self, DemoTextItem.STATIC_TEXT)
        self.description2 = DemoTextItem(self.loadDescription(1, 2),
                                         Colors.contentFont(), Colors.heading,
                                         250, self.scene(), self,
                                         DemoTextItem.STATIC_TEXT)

        # Place the items on screen.
        self.heading.setPos(0, 3)
        self.description1.setPos(
            0,
            self.heading.pos().y() + self.heading.boundingRect().height() + 10)
        self.description2.setPos(
            0,
            self.description1.pos().y() +
            self.description1.boundingRect().height() + 15)
Esempio n. 6
0
    def add(self, name):
        if name not in cfgStore.store:
            cfgStore.store[name] = {}
            cfgStore.store[name] = self.loadConfigFromFile(name)

            default = self.loadConfigFromFile(name, True)
            for d in default:
                if d not in cfgStore.store[name]:
                    cfgStore.store[name][d] = default[d]

            if name not in ['System', 'Project', 'Camera', 'Flir', 'Capture']:
                if 'frameIn' not in cfgStore.store[name]:
                    # store the dict and then insert the new vars at the top of the list
                    temp = cfgStore.store[name]
                    cfgStore.store[name] = {}
                    self.insertConfigVariable(
                        name, 1, "Text", "frameIn", "default", "",
                        "Frame source", "", "default~Mask~Color~Noise~FillGap")
                    self.insertConfigVariable(name, 1, "Number", "channel",
                                              "0", "", "Source channel", "")
                    for t in temp:
                        cfgStore.store[name][t] = temp[t]

            if name in ['System']:
                if 'colors' not in cfgStore.store[name]:
                    cfgStore.store[name]['colors'] = Colors().list
                if 'cindex' not in cfgStore.store[name]:
                    cfgStore.store[name]['cindex'] = Colors().index

            self.saveConfigToFile(name)
            # after save to file - only change in memory
            # add the port here just in case we are serving multiple vision applications
            if name == 'Project':
                cfgStore.store[name]['visionServer'] = cfgStore.store[name][
                    'visionServer'] + ':' + os.environ['PORT']
Esempio n. 7
0
    def setupSceneItems(self):
        if Colors.showFps:
            self.fpsLabel = DemoTextItem("FPS: --", Colors.buttonFont(),
                    QtCore.Qt.white, -1, self.scene, None,
                    DemoTextItem.DYNAMIC_TEXT)
            self.fpsLabel.setZValue(1000)
            self.fpsLabel.setPos(Colors.stageStartX,
                    600 - QtGui.QFontMetricsF(Colors.buttonFont()).height() - 5)

        self.mainSceneRoot = QtGui.QGraphicsWidget()
        self.scene.addItem(self.mainSceneRoot)

        self.companyLogo = ImageItem(
                QtGui.QImage(':/images/trolltech-logo.png'), 1000, 1000,
                self.scene, None, True, 0.5)
        self.qtLogo = ImageItem(
                QtGui.QImage(':/images/qtlogo_small.png'), 1000, 1000,
                self.scene, None, True, 0.5)
        self.companyLogo.setZValue(100)
        self.qtLogo.setZValue(100)
        self.pausedLabel = DemoTextItem("PAUSED", Colors.buttonFont(),
                QtCore.Qt.white, -1, self.scene, None)
        self.pausedLabel.setZValue(100)
        fm = QtGui.QFontMetricsF(Colors.buttonFont())
        self.pausedLabel.setPos(Colors.stageWidth - fm.width("PAUSED"),
                590 - fm.height())
        self.pausedLabel.setRecursiveVisible(False)
    def loadDescription(self, startPara, nrPara):
        readme = QFile(self.readmePath)
        if not readme.open(QFile.ReadOnly):
            Colors.debug("- MenuContentItem.loadDescription: Could not load:",
                         self.readmePath)
            return ""

        in_str = QTextStream(readme)
        # Skip a certain number of paragraphs.
        while startPara:
            if not in_str.readLine():
                startPara -= 1

        # Read in the number of wanted paragraphs.
        result = ''
        line = in_str.readLine()
        while True:
            result += line + " "
            line = in_str.readLine()
            if not line:
                nrPara -= 1
                line = "<br><br>" + in_str.readLine()

            if nrPara == 0 or in_str.atEnd():
                break

        return Colors.contentColor + result
Esempio n. 9
0
    def createImage(self, transform):
        scaledRect = transform.mapRect(QRect(0, 0, 25, 25))
        image = QImage(scaledRect.width(), scaledRect.height(),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(0)
        painter = QPainter(image)
        painter.scale(transform.m11(), transform.m22())
        painter.setRenderHints(QPainter.TextAntialiasing | QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
        painter.setPen(Qt.NoPen)

        if Colors.useEightBitPalette:
            painter.setBrush(QColor(102, 175, 54))
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255))
            painter.drawText(10, 15, self.letter)
        else:
            brush = QLinearGradient(0, 0, 0, 25)
            brush.setSpread(QLinearGradient.PadSpread)
            brush.setColorAt(0.0, QColor(102, 175, 54, 200))
            brush.setColorAt(1.0, QColor(102, 175, 54, 60))
            painter.setBrush(brush)
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255, 255))
            painter.drawText(10, 15, self.letter)

        return image
Esempio n. 10
0
    def showDocInAssistant(self, name):
        url = self.resolveDocUrl(name)
        Colors.debug("Sending URL to Assistant:", url)

        # Start assistant if it's not already running.
        if self.assistantProcess.state() != QProcess.Running:
            app = QLibraryInfo.location(
                QLibraryInfo.BinariesPath) + QDir.separator()

            if sys.platform == 'darwin':
                app += 'Assistant.app/Contents/MacOS/Assistant'
            else:
                app += 'assistant'

            args = ['-enableRemoteControl']
            self.assistantProcess.start(app, args)
            if not self.assistantProcess.waitForStarted():
                QMessageBox.critical(None, "PyQt Demo",
                                     "Could not start %s." % app)
                return

        # Send command through remote control even if the process was just
        # started to activate assistant and bring it to the front.
        cmd_str = QTextStream(self.assistantProcess)
        cmd_str << 'SetSource ' << url << '\n'
Esempio n. 11
0
    def getResource(self, name):
        ba = self.helpEngine.fileData(QtCore.QUrl(name))

        if ba.isEmpty():
            Colors.debug(" - WARNING: Could not get", name)

        return ba
Esempio n. 12
0
 def __init__(self, project='Untitled', source='.', ignored_paths=None, color=False,
              filter_obj=None, verbose=False, outfile=None, quiet=False):
     """
     Constructor.
     :type project: str
     :param project: str
     :param ignored_paths: bool
     :param source: str
     :param color: bool
     :param filter_obj: lib.Filter()
     :param verbose: bool
     :param outfile: str
     :param quiet: bool
     """
     self.project = project
     self.source = source
     self.color = False
     if color:
         self.color = Colors()
     self.filter = filter_obj
     self.verbose = verbose
     self.outfile = outfile
     self.fp = None
     self.html = ''
     self.quiet = quiet
     if ignored_paths:
         paths = ignored_paths.split(':')
         for path in paths:
             self.filter.ignored_paths.append(re.compile(path, self.filter.REGEX_FLAGS))
     self.html = open('resources/output_template.html', 'r').read()
     self.fp = open(self.outfile, 'w')
     self.html = self.html.replace('###DIRECTORY###', self.source)
     self.html = self.html.replace('###PROJECT###', self.project)
Esempio n. 13
0
    def createImage(self, matrix):
        scaledRect = matrix.mapRect(QtCore.QRect(0, 0, 25, 25))
        image = QtGui.QImage(scaledRect.width(), scaledRect.height(),
                             QtGui.QImage.Format_ARGB32_Premultiplied)
        image.fill(0)
        painter = QtGui.QPainter(image)
        painter.scale(matrix.m11(), matrix.m22())
        painter.setRenderHints(QtGui.QPainter.TextAntialiasing
                               | QtGui.QPainter.Antialiasing
                               | QtGui.QPainter.SmoothPixmapTransform)
        painter.setPen(QtCore.Qt.NoPen)

        if Colors.useEightBitPalette:
            painter.setBrush(QtGui.QColor(102, 175, 54))
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QtGui.QColor(255, 255, 255))
            painter.drawText(10, 15, self.letter)
        else:
            brush = QtGui.QLinearGradient(0, 0, 0, 25)
            brush.setSpread(QtGui.QLinearGradient.PadSpread)
            brush.setColorAt(0.0, QtGui.QColor(102, 175, 54, 200))
            brush.setColorAt(1.0, QtGui.QColor(102, 175, 54, 60))
            painter.setBrush(brush)
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QtGui.QColor(255, 255, 255, 255))
            painter.drawText(10, 15, self.letter)

        return image
    def setupSceneItems(self):
        if Colors.showFps:
            self.fpsLabel = DemoTextItem("FPS: --", Colors.buttonFont(),
                                         QtCore.Qt.white, -1, self.scene, None,
                                         DemoTextItem.DYNAMIC_TEXT)
            self.fpsLabel.setZValue(1000)
            self.fpsLabel.setPos(
                Colors.stageStartX,
                600 - QtGui.QFontMetricsF(Colors.buttonFont()).height() - 5)

        self.mainSceneRoot = QtGui.QGraphicsWidget()
        self.scene.addItem(self.mainSceneRoot)

        self.companyLogo = ImageItem(
            QtGui.QImage(':/images/trolltech-logo.png'), 1000, 1000,
            self.scene, None, True, 0.5)
        self.qtLogo = ImageItem(QtGui.QImage(':/images/qtlogo_small.png'),
                                1000, 1000, self.scene, None, True, 0.5)
        self.companyLogo.setZValue(100)
        self.qtLogo.setZValue(100)
        self.pausedLabel = DemoTextItem("PAUSED", Colors.buttonFont(),
                                        QtCore.Qt.white, -1, self.scene, None)
        self.pausedLabel.setZValue(100)
        fm = QtGui.QFontMetricsF(Colors.buttonFont())
        self.pausedLabel.setPos(Colors.stageWidth - fm.width("PAUSED"),
                                590 - fm.height())
        self.pausedLabel.setRecursiveVisible(False)
Esempio n. 15
0
 def __init__(self, editor, workdir, params, inputs, mode):
     #print "create MyQProcess........\n"
     #self.myprocess=MyQProcess(workdir, params)
     Colors.debug("WorkDir:", workdir)
     print "\ncreate MyThread......... \n"
     self.mode=mode
     self.thread=MyThread(workdir, params, editor, inputs, mode)
     print "\ncreate MyThread end ....\n"
Esempio n. 16
0
  def SetMessage(self, msg="Game"):
    self.msgSurfaceObj = self.fontObj.render(msg, False, Colors.blue())
    self.msgRectobj = self.msgSurfaceObj.get_rect()
    self.msgRectobj.topleft = (self.width + 4, 0)

    # Clear previous msg
    self.surface.fill(Colors.white(), self.msgRectobj)

    self.surface.blit(self.msgSurfaceObj, self.msgRectobj)
Esempio n. 17
0
    def __init__(self, workdir, params):
        QtCore.QProcess.__init__(self)
        Colors.debug("WorkDir:", workdir)
        #print "1:"+
        #self.startDetached(QtCore.QDir(workdir))
        self.setWorkingDirectory(QtCore.QDir(workdir))
        #.absolutePath()
	for param in params:
    	    self.addArgument(param)
Esempio n. 18
0
    def reproduce(self, other, board):
        if self is other:
            print(self.debug())
            print(str(other))
            raise Exception('⛔  the father and the mother are the same')
        if self.debugging:
            print('⚤  ' + str(self) + ' copulates with ' + str(other))
        if self.actions < 1:
            if self.debugging:
                print('☹  ' + str(self) + ' is exausted and can not repreduce')
            return False
        if other.actions < 1:
            if self.debugging:
                print('☹  ' + str(other) + ' is exausted and can not repreduce')
            return False
        if self.gender is other.gender:
            print(self.debug())
            print(str(other))
            raise Exception('⛔  Can not copulate animals with same gender')

        empty_cells = self.look_for_empty_cells(board)
        if empty_cells is None or not empty_cells:
            if self.debugging:
                print('⚠  ' + self.race.capitalize() +
                      ' has not empty location to reproduce: ' + str(self))
            return False
        cell = empty_cells[random.randint(0, len(empty_cells)-1)]

        father = self if self.gender is Genders.MALE.value else other
        mother = self if self.gender is Genders.FEMALE.value else other

        # cell division
        if random.randint(1, 100) <= self.mutation_probability:
            if self.debugging:
                print('⚛  child mutates!!!')
            color = Colors.melt(Colors, Colors.random(
                Colors), Colors.melt(Colors, father.color, mother.color))
            size = int((father.size + mother.size)/3 *
                       random.uniform(1 - self.mutation_factor, 1 + self.mutation_factor))
        else:
            color = Colors.melt(Colors, father.color, mother.color)
            size = int((father.size + mother.size)/3 *
                       random.uniform(1.1, 1.5))

        size = min(100, max(1, size))

        self.expend_action()
        other.expend_action()

        baby = self.__class__(cell.pos, father.race, color,
                              size, None, father, mother)
        cell.occupy(baby)

        if self.debug:
            print('❤  New ' + baby.race.capitalize() +
                  ' born: ' + str(cell.content))
Esempio n. 19
0
    def init(self, window):
        self.window = window

        # Create div.
        self.createTicker()
        self.createUpnDownButtons()
        self.createBackButton()

        # Create first level menu.
        rootElement = self.contentsDoc.documentElement()
        self.createRootMenu(rootElement)

        # Create second level menus.
        level2MenuNode = rootElement.firstChild()
        while not level2MenuNode.isNull():
            level2MenuElement = level2MenuNode.toElement()
            self.createSubMenu(level2MenuElement)

            # Create leaf menu and example info.
            exampleNode = level2MenuElement.firstChild()
            while not exampleNode.isNull():
                exampleElement = exampleNode.toElement()
                self.readInfoAboutExample(exampleElement)
                self.createLeafMenu(exampleElement)
                exampleNode = exampleNode.nextSibling()

            level2MenuNode = level2MenuNode.nextSibling()

        # Support QML if possible.
        try:
            from PyQt4 import QtDeclarative
        except ImportError:
            return

        self.declarativeEngine = QtDeclarative.QDeclarativeEngine(self)

        component = QtDeclarative.QDeclarativeComponent(
            self.declarativeEngine, QtCore.QUrl('qrc:/qml/qmlShell.qml'), self)
        if component.isReady():
            self.qmlRoot = component.create()

        if self.qmlRoot is not None:
            self.qmlRoot.setHeight(window.scene.sceneRect().height())
            self.qmlRoot.setWidth(window.scene.sceneRect().width())
            self.qmlRoot.setZValue(101)
            self.qmlRoot.setCursor(QtCore.Qt.ArrowCursor)
            window.scene.addItem(self.qmlRoot)

            window.viewport().setFocusPolicy(QtCore.Qt.NoFocus)
            window.setFocusPolicy(QtCore.Qt.StrongFocus)
            window.scene.setStickyFocus(True)
            window.setFocus()
        else:
            Colors.debug(
                "Error initializing QML subsystem, Declarative examples will not work"
            )
Esempio n. 20
0
    def queueMovie(self, indexName, runMode=FROM_START, lockMode=SKIP_LOCK):
        try:
            movie = self.index[indexName]
        except KeyError:
            Colors.debug("Queuing movie:", indexName, "(does not exist)")
            return

        self.prepare(movie, runMode, lockMode)
        self.playList.append(PlayListMember(movie, runMode))
        Colors.debug("Queuing movie:", indexName)
Esempio n. 21
0
    def queueMovie(self, indexName, runMode=FROM_START, lockMode=SKIP_LOCK):
        try:
            movie = self.index[indexName]
        except KeyError:
            Colors.debug("Queuing movie:", indexName, "(does not exist)")
            return

        self.prepare(movie, runMode, lockMode)
        self.playList.append(PlayListMember(movie, runMode))
        Colors.debug("Queuing movie:", indexName)
Esempio n. 22
0
 def stringify_resource(res):
     """Print a ResourceGroup instance."""
     s = ""
     s += "\tName: {}\n".format(Colors.ok_blue(Colors.bold(res.name)))
     s += "\tType: {}\n".format(res.type)
     s += "\tId: {}\n".format(res.id)
     s += "\tLocation: {}\n".format(res.location)
     s += "\tTags: {}\n".format(res.tags)
     s += Deployer.stringify_properties(res.properties)
     return s
Esempio n. 23
0
    def init(self, window):
        self.window = window

        # Create div.
        self.createTicker()
        self.createUpnDownButtons()
        self.createBackButton()

        # Create first level menu.
        rootElement = self.contentsDoc.documentElement()
        self.createRootMenu(rootElement)

        # Create second level menus.
        level2MenuNode = rootElement.firstChild()
        while not level2MenuNode.isNull():
            level2MenuElement = level2MenuNode.toElement()
            self.createSubMenu(level2MenuElement)

            # Create leaf menu and example info.
            exampleNode = level2MenuElement.firstChild()
            while not exampleNode.isNull():
                exampleElement = exampleNode.toElement()
                self.readInfoAboutExample(exampleElement)
                self.createLeafMenu(exampleElement)
                exampleNode = exampleNode.nextSibling()

            level2MenuNode = level2MenuNode.nextSibling()

        # Support QML if possible.
        try:
            from PyQt4 import QtDeclarative
        except ImportError:
            return

        self.declarativeEngine = QtDeclarative.QDeclarativeEngine(self)
        self.declarativeEngine.quit.connect(self.quitQML)

        component = QtDeclarative.QDeclarativeComponent(self.declarativeEngine,
                QtCore.QUrl('qrc:/qml/qmlShell.qml'), self)
        if component.isReady():
            self.qmlRoot = component.create()

        if self.qmlRoot is not None:
            self.qmlRoot.setHeight(window.scene.sceneRect().height())
            self.qmlRoot.setWidth(window.scene.sceneRect().width())
            self.qmlRoot.setZValue(101)
            self.qmlRoot.setCursor(QtCore.Qt.ArrowCursor)
            window.scene.addItem(self.qmlRoot)

            window.viewport().setFocusPolicy(QtCore.Qt.NoFocus)
            window.setFocusPolicy(QtCore.Qt.StrongFocus)
            window.scene.setStickyFocus(True)
            window.setFocus()
        else:
            Colors.debug("Error initializing QML subsystem, Declarative examples will not work")
Esempio n. 24
0
    def color(self) -> curses.color_pair:
        """An initialized ncurses color pair associated with the type of file
        for this Item.
        """
        if self.selected:
            return Colors.black_on_white()

        if self._path.is_dir():
            return Colors.blue_on_black()

        return Colors.default()
Esempio n. 25
0
    def __init__(self):
        colors = Colors()
        green = colors.green()
        reset = colors.reset()

        print green + """
            Simple Email Harvester
            This tools allows to scrape websites for emails
            Usage: ./email_harvester.py --url http://www.example.com --file example_emails.txt
                
                """ + reset
Esempio n. 26
0
class Banner:

    r = Colors().red(1)
    y = Colors().yellow(9)
    ny = Colors().yellow(0)
    nw = Colors().white(0)
    e = Colors().end()

    def banner(self):
        print self.ny + "  _____             _       _   _   _ " + self.e
        print self.ny + " |   __|___ ___ ___| |_ ___| |_| |_|_|" + self.e
        print self.ny + " |__   | . | .'| . |   | -_|  _|  _| |" + self.e
        print self.ny + " |_____|  _|__,|_  |_|_|___|_| |_| |_|" + self.e
        print self.ny + "       |_|     |___|          " + self.r + "v0.1.3\n" + self.e
        print self.nw + "~/#" + self.e + " Spaghetti - Web Application Security Scanner" + self.e
        print self.nw + "~/#" + self.e + " Codename - " + self.y + "MR.R0B0T" + self.e
        print self.nw + "~/#" + self.e + " Momo Outaadi (@M4ll0k)" + self.e
        print self.nw + "~/#" + self.e + " https://github.com/m4ll0k/Spaghetti\n" + self.e

    def usage(self, exit=False):
        name = os.path.basename(sys.argv[0])
        self.banner()
        print "Usage:\n"
        print "\t-u --url\tTarget URL (eg: http://example.com)"
        print "\t-s --scan\tScan Options (default=0):\n"
        print "\t\t0:\tFull Scan"
        print "\t\t1:\tBruteforce (dirs,files,..)"
        print "\t\t2:\tDisclosure (ip,emails,..)"
        print "\t\t3:\tAttacks (sql,lfi,..)"
        print "\t\t4:\tOthers (webdav,..)"
        print "\t\t5:\tVulns (shellshock,..)"
        print "\t\t6:\tFingerprint only\n"
        print "\t--crawler\tDeep crawling (slow)"
        print "\t--agent\t\tUse the specified user-agent"
        print "\t--random-agent\tUse a random user-agent"
        print "\t--redirect\tRedirect target URL, default=True"
        print "\t--timeout\tSet timeout, default=None"
        print "\t--cookie\tSet cookie, default=None"
        print "\t--proxy\t\tSet proxy, (host:port)"
        print "\t--verbose\tVerbose output"
        print "\t--version\tShow version"
        print "\t--help\t\tShow this help and exit\n"
        print "Examples:\n"
        print "\t" + name + " --url http://example.com"
        print "\t" + name + " --url http://example.com --scan [0-6]"
        print "\t" + name + " --url http://example.com --scan 1 --crawler\n"
        if exit:
            sys.exit(0)

    def version(self, exit=False):
        self.banner()
        print "~/# Spaghetti - Web Application Security Scanner (v0.1.3\n"
        if exit:
            sys.exit(0)
Esempio n. 27
0
    def resolveQmlFile(self, name):
        dir = self.resolveDir(name)

        fileName = self.info[name]['filename'].split('/')[-1]

        qmlFile = QFile(dir.path() + '/' + fileName + '.qml')
        if qmlFile.exists():
            return qmlFile.fileName()

        Colors.debug("- WARNING: Could not resolve QML file:", dir.path(),
                     fileName)
        return '__QML not found__'
Esempio n. 28
0
    def readInfoAboutExample(self, example):
        name = str(example.attribute('name'))
        if name in self.info:
            Colors.debug("__WARNING: MenuManager.readInfoAboutExample: "
                         "Demo/example with name", name, "appears twice in "
                         "the xml-file!__")

        self.info.setdefault(name, {})['filename'] = str(example.attribute('filename'))
        self.info[name]['category'] = str(example.parentNode().toElement().tagName())
        self.info[name]['dirname'] = str(example.parentNode().toElement().attribute('dirname'))
        self.info[name]['changedirectory'] = str(example.attribute('changedirectory'))
        self.info[name]['image'] = str(example.attribute('image'))
Esempio n. 29
0
    def resolveQmlFile(self, name):
        dir = self.resolveDir(name)

        fileName = self.info[name]["filename"].split("/")[-1]

        qmlFile = QFile(dir.path() + "/" + fileName + ".qml")
        if qmlFile.exists():
            return qmlFile.fileName()

        Colors.debug("- WARNING: Could not resolve QML file:", dir.path(),
                     fileName)
        return "__QML not found__"
Esempio n. 30
0
    def readInfoAboutExample(self, example):
        name = str(example.attribute('name'))
        if name in self.info:
            Colors.debug("__WARNING: MenuManager.readInfoAboutExample: "
                         "Demo/example with name", name, "appears twice in "
                         "the xml-file!__")

        self.info.setdefault(name, {})['filename'] = str(example.attribute('filename'))
        self.info[name]['category'] = str(example.parentNode().toElement().tagName())
        self.info[name]['dirname'] = str(example.parentNode().toElement().attribute('dirname'))
        self.info[name]['changedirectory'] = str(example.attribute('changedirectory'))
        self.info[name]['image'] = str(example.attribute('image'))
Esempio n. 31
0
    def readInfoAboutExample(self, example):
        name = example.getAttribute('name')
        if name in self.info:
            Colors.debug("__WARNING: MenuManager.readInfoAboutExample: "
                         "Demo/example with name", name, "appears twice in "
                         "the xml-file!__")

        self.info.setdefault(name, {})['filename'] = example.getAttribute('filename')
        self.info[name]['dirname'] = example.parentNode.getAttribute('dirname')
        self.info[name]['changedirectory'] = example.getAttribute('changedirectory')
        self.info[name]['image'] = example.getAttribute('image')
        self.info[name]['qml'] = example.getAttribute('qml')
Esempio n. 32
0
    def resolveQmlFile(self, name):
        dir = self.resolveDir(name)

        fileName = self.info[name]['filename'].split('/')[-1]

        qmlFile = QFile(dir.path() + '/' + fileName + '.qml')
        if qmlFile.exists():
            return qmlFile.fileName()

        Colors.debug("- WARNING: Could not resolve QML file:", dir.path(),
                fileName)
        return '__QML not found__'
Esempio n. 33
0
    def launchQml(self, name):
        import_path = self.resolveDataDir(name)
        qml = self.resolveQmlFile(name)

        process = QProcess(self)
        process.error.connect(self.launchError)

        env = QProcessEnvironment.systemEnvironment()
        env.insert('QML2_IMPORT_PATH', import_path)
        process.setProcessEnvironment(env)

        executable = QLibraryInfo.location(QLibraryInfo.BinariesPath) + '/qmlscene'
        Colors.debug("Launching:", executable)
        process.start(executable, [qml])
Esempio n. 34
0
    def __init__(self):
        self.clock = pygame.time.Clock()
        # Создание экземпляра класса Colors
        self.color = Colors()
        # Характеристики экрана:
        # Цвет экрана
        self.screen_color = self.color.LAVENDER
        # Ширина и высота/размер экрана
        self.screen_size = self.screen_width, self.screen_height = 1280, 720
        # Частота кадров
        self.FPS = 60

        # Характеристики Точек:
        # Радиус точки
        self.dot_radius = 6
        # Радиус обзора
        self.dot_scan_radius = 120
        # Начальный уровень энергии
        self.dot_energy = 500
        # Скорость
        self.dot_vel = random.randint(1, 3)

        # Характеристики Травинок:
        # Цвет Травинки
        self.grass_color = self.color.WHITE
        # Радиус точки
        self.grass_radius = 2
        # Энергатическая ценность
        self.grass_energy = 120
Esempio n. 35
0
 def __init__(self):
     # Класс точки наследует от встроенного класса Sprite
     super().__init__()
     # self.name = name
     # Создается экземпляр класса Config, где хранятся все настройки и цветов Colors
     self.config = Config()
     self.color = Colors()
     # Цвет Точки
     if self.config.dot_vel == 1:
         self.dot_color = self.color.BLUE
     elif self.config.dot_vel == 2:
         self.dot_color = self.color.FUCHSIA
     elif self.config.dot_vel == 3:
         self.dot_color = self.color.DARKKHAKI
     # Создаем спрайт Точки. Ширина и высота прямоугольника Точки равны диаметру Точки (два радиуса)
     self.image = pygame.Surface(
         [self.config.dot_radius * 2, self.config.dot_radius * 2])
     self.image.fill(self.color.WHITE)
     # Создаем поверхность для Точек
     self.image.set_colorkey(self.color.WHITE)
     self.rect = self.image.get_rect()
     pygame.draw.circle(self.image, self.dot_color,
                        (self.rect.x + self.config.dot_radius,
                         self.rect.y + self.config.dot_radius),
                        self.config.dot_radius)
Esempio n. 36
0
 def check_has_expected(self):
     if not self.expected:
         self.print_start()
         logging.warning(Colors.warning("No data, dumping"))
         logging.warning(self.dump_str())
         return False
     return True
Esempio n. 37
0
    def resolveExeFile(self, name):
        dir = self.resolveDir(name)

        fileName = self.info[name]['filename'].split('/')[-1]

        pyFile = QtCore.QFile(dir.path() + '/' + fileName + '.py')
        if pyFile.exists():
            return pyFile.fileName()

        pywFile = QtCore.QFile(dir.path() + '/' + fileName + '.pyw')
        if pywFile.exists():
            return pywFile.fileName()

        Colors.debug("- WARNING: Could not resolve executable:", dir.path(),
                fileName)
        return '__executable not found__'
Esempio n. 38
0
    def resolveExeFile(self, name):
        dir = self.resolveDir(name)

        fileName = self.info[name]["filename"].split("/")[-1]

        pyFile = QFile(dir.path() + "/" + fileName + ".py")
        if pyFile.exists():
            return pyFile.fileName()

        pywFile = QFile(dir.path() + "/" + fileName + ".pyw")
        if pywFile.exists():
            return pywFile.fileName()

        Colors.debug("- WARNING: Could not resolve executable:", dir.path(),
                     fileName)
        return "__executable not found__"
Esempio n. 39
0
	def __init__(self, extension, filetype, token) :
		self.extension = extension
		self.token = token
		self.color = Colors()
		self.drive = dropbox.Dropbox(self.token)
		self.shareds = []
		self.filetype = filetype
Esempio n. 40
0
    def __init__(self, caption):
        """Инициализация основных параметров."""
        self.caption = caption
        self.config = Config()
        self.color = Colors()
        # Заголовок экрана
        pygame.display.set_caption(self.caption)
        # Экран с заданным размером
        self.screen = pygame.display.set_mode(self.config.screen_size)
        # Создается группа Точек/список спрайтов
        self.dot_list = pygame.sprite.Group()
        # Создается группа Травинок/список спрайтов
        self.grass_list = pygame.sprite.Group()
        # Создается группа всех спрайтов
        self.all_sprites_list = pygame.sprite.Group()

        for i in range(10):
            # Создание Точки
            self.dot = Dot()
            # Выбор случайных координат размещения Точки
            self.dot.rect.x = random.randrange(self.config.screen_width)
            self.dot.rect.y = random.randrange(self.config.screen_height)
            # Добавить точки в список точек
            self.dot_list.add(self.dot)
            self.all_sprites_list.add(self.dot)

        for i in range(100):
            # Создание травинки
            self.grass = Grass()
            # Выбор случайных координат размещения травинки
            self.grass.rect.x = random.randrange(self.config.screen_width)
            self.grass.rect.y = random.randrange(self.config.screen_height)
            # Добавить травинку в список травинок
            self.grass_list.add(self.grass)
            self.all_sprites_list.add(self.grass)
Esempio n. 41
0
    def __init__(self, width, height, caption):
        pygame.init()
        # Размеры окна и заголовок
        self.width = width
        self.height = height
        self.size = (self.width, self.height)
        self.caption = caption
        pygame.display.set_caption(self.caption)
        # Экран с заданным размеров
        self.screen = pygame.display.set_mode(self.size)
        # Полноэкранный режим
        # self.screen = pygame.display.set_mode(self.size, pygame.FULLSCREEN)

        # Инициализация настроек
        self.config = Config()
        # Инициализация набора цветов
        self.colors = Colors()
        # Инициализация счетчика шагов
        self.step = 0
        # Инициализация списков объектов (Точки и трав)
        self.dotsList = []
        # Инициализация первой точки и добавление в список Точек
        self.firstDot = Dot()
        self.dotsList.append(self.firstDot)
        # Список координат трав
        self.grass = Grass()
        self.grassesCoords = self.grass.addGrass(self.width, self.height,
                                                 self.grass.startQuantity)

        self.font = pygame.font.SysFont(None, 16)
        self.screen_rect = self.screen.get_rect()

        pygame.mouse.set_visible(False)
Esempio n. 42
0
    def resolveExeFile(self, name):
        dir = self.resolveDir(name)

        fileName = self.info[name]['filename'].split('/')[-1]

        pyFile = QFile(dir.path() + '/' + fileName + '.py')
        if pyFile.exists():
            return pyFile.fileName()

        pywFile = QFile(dir.path() + '/' + fileName + '.pyw')
        if pywFile.exists():
            return pywFile.fileName()

        Colors.debug("- WARNING: Could not resolve executable:", dir.path(),
                     fileName)
        return '__executable not found__'
Esempio n. 43
0
  def __init__(self, row_token=None, column_token=None, 
              header_color='STRONG_YELLOW', header_background_color='BG_BLUE',
              cell_a_color='BLUE', cell_b_color='YELLOW',
              cell_a_background_color='BG_YELLOW', cell_b_background_color='BG_BLUE'):
  
    self.table        = list()
    self.header       = list()
    self.lines        = list()
    self.title        = None
    self.longest      = 0
    self.row_token    = '-'
    self.column_token = '|'

    self.c = Colors()
    self.c.set_header_color(header_color)
    self.c.set_header_background_color(header_background_color)
    self.c.set_cell_a_color(header_color)
    self.c.set_cell_b_color(header_color)
    self.c.set_cell_a_background_color(header_color)
    self.c.set_cell_b_background_color(header_color)
    self.c.set_cell_a_color(cell_a_color)
    self.c.set_cell_b_color(cell_b_color)
    self.c.set_cell_a_background_color(cell_a_background_color)
    self.c.set_cell_b_background_color(cell_b_background_color)

    self.color = False

    if row_token != None:
      self.row_token = row_token[0]

    if column_token != None:
      self.column_token = column_token[0]
Esempio n. 44
0
    def setupHoverText(self):
        if not self.buttonLabel:
            return

        textItem = DemoTextItem(self.buttonLabel, Colors.buttonFont(),
                                Colors.buttonText, -1, self)
        textItem.setZValue(self.zValue() + 2)
        textItem.setPos(16, 0)
    def loadDescription(self):
        ba = self._menu_manager.getHtml(self.name)

        exampleDoc = QtXml.QDomDocument()
        exampleDoc.setContent(ba, False)

        paragraphs = exampleDoc.elementsByTagName('p')
        if paragraphs.length() < 1:
            Colors.debug("- ExampleContent.loadDescription(): Could not load description:", self._menu_manager.info[self.name].get('docfile'))

        description = Colors.contentColor + "Could not load description. Ensure that the documentation for Qt is built."
        for p in range(paragraphs.length()):
            description = self.extractTextFromParagraph(paragraphs.item(p))
            if self.isSummary(description):
                break

        return Colors.contentColor + description
Esempio n. 46
0
    def loadDescription(self):
        ba = self._menu_manager.getHtml(self.name)

        exampleDoc = QtXml.QDomDocument()
        exampleDoc.setContent(ba, False)

        paragraphs = exampleDoc.elementsByTagName('p')
        if paragraphs.length() < 1:
            Colors.debug("- ExampleContent.loadDescription(): Could not load description:", self._menu_manager.info[self.name].get('docfile'))

        description = Colors.contentColor + "Could not load description. Ensure that the documentation for Qt is built."
        for p in range(paragraphs.length()):
            description = self.extractTextFromParagraph(paragraphs.item(p))
            if self.isSummary(description):
                break

        return Colors.contentColor + description
Esempio n. 47
0
    def setupHoverText(self):
        if not self.buttonLabel:
            return

        textItem = DemoTextItem(self.buttonLabel, Colors.buttonFont(),
                Colors.buttonText, -1, self)
        textItem.setZValue(self.zValue() + 2)
        textItem.setPos(16, 0)
Esempio n. 48
0
 def diff_str(self, zipped):
     l = []
     for s_map, s_brief, s_full in zipped:
         if s_map == s_brief:
             l.append(self.S_OK % (s_full))
         else:
             l.append(self.S_FAIL % (s_full, Colors.warning(s_map)))
     return '\n' + '\n'.join(l)
Esempio n. 49
0
 def compare(self):
     errors = 0
     for mod in self.res.keys():
         if not self.merge_mods:
             logging.info(Colors.blue("Test on mod '%s'" % mod))
         errors += self.check_one_mod(mod)
     total  = len(self.expected) * len(self.res.keys())
     return (errors, total)
Esempio n. 50
0
    def setRenderingSystem(self):
        if Colors.openGlRendering:
            from PyQt4 import QtOpenGL

            viewport = QtOpenGL.QGLWidget(QtOpenGL.QGLFormat(QtOpenGL.QGL.SampleBuffers))

            if Colors.noScreenSync:
                viewport.format().setSwapInterval(0)

            viewport.setAutoFillBackground(False)
            self.setCacheMode(QtGui.QGraphicsView.CacheNone)
            Colors.debug("- using OpenGL")
        else:
            viewport = QtGui.QWidget()
            self.setCacheMode(QtGui.QGraphicsView.CacheBackground)
            Colors.debug("- using software rendering")

        self.setViewport(viewport)
Esempio n. 51
0
  def _NeighborCount(self, square):
    """Returns the count and color of a square's neighbors.

    Args:
      square: (Square) Object

    Returns:
      neighbors: (dict) {
                          Color.white: N,  # total
                          "friends": H,
                          "enemies": J,
                          "total_neighbors": L,  # non-white neighbors
                          "influence": Team  # the team with the most influence
                                             # simply with the most squares
                                             # surrounding this one
                        }
    """
    neighbors = {"total_neighbors": 0, "friends": 0, "enemies": 0}


    if square.position == (46, 14):
      pass
    # initialize all colors to 0
    for color in Colors.all():
      neighbors[color] = 0

    neighbor_team_count = {}

    for pos in (world_rules.POSITIONS):
      try:
        neighbor_color, neighbor_team = self._NeighborColor(square, pos)
      except (OutsideWorld, NoNeighbor):
        continue

      neighbors[neighbor_color] += 1
      if neighbor_color != Colors.white:
        neighbors["total_neighbors"] += 1

        neighbor_team_count.setdefault(neighbor_team, 0)
        neighbor_team_count[neighbor_team] += 1

        if neighbor_team == square.team:
          neighbors["friends"] += 1
        else:
          neighbors["enemies"] += 1

    influence = None
    max = 0
    for team, count in neighbor_team_count.iteritems():
      if count > max:
        max = count
        influence = team


      neighbors["influence"] = influence

    return neighbors
Esempio n. 52
0
    def loadDescription(self):
        contents = self._menu_manager.getHtml(self.name).data().decode('utf8')
        if contents == '':
            paragraphs = []
        else:
            exampleDoc = parseString(contents)
            paragraphs = exampleDoc.getElementsByTagName('p')

        if len(paragraphs) < 1:
            Colors.debug("- ExampleContent.loadDescription(): Could not load description:", self._menu_manager.info[self.name].get('docfile'))

        description = Colors.contentColor + "Could not load description. Ensure that the documentation for Qt is built."
        for p in paragraphs:
            description = self.extractTextFromParagraph(p)
            if self.isSummary(description):
                break

        return Colors.contentColor + description
Esempio n. 53
0
    def createContent(self):
        # Create the items.
        self.heading = HeadingItem(self.name, self)
        para1 = self.loadDescription(0, 1)
        if not para1:
            para1 = Colors.contentColor + "Could not load description. Ensure that the documentation for Qt is built."
        bgcolor = Colors.sceneBg1.darker(200)
        bgcolor.setAlpha(100)
        self.description1 = DemoTextItem(para1, Colors.contentFont(),
                Colors.heading, 500, self, DemoTextItem.STATIC_TEXT)
        self.description2 = DemoTextItem(self.loadDescription(1, 2),
                Colors.contentFont(), Colors.heading, 250, self,
                DemoTextItem.STATIC_TEXT)

        # Place the items on screen.
        self.heading.setPos(0, 3)
        self.description1.setPos(0, self.heading.pos().y() + self.heading.boundingRect().height() + 10)
        self.description2.setPos(0, self.description1.pos().y() + self.description1.boundingRect().height() + 15)
Esempio n. 54
0
 def check_same_len(self, res):
     if not self.expected:
         return
     if len(self.expected) != len(res):
         logging.error(Colors.fail("Incorrect list length"))
         logging.error("expected: %d" % (len(self.expected)))
         logging.error("got:      %d" % (len(res)))
         logging.error(str(self.expected))
         logging.error(str(res))
         raise TR_Exception("Incorrect list length")
Esempio n. 55
0
    def createImage(self, matrix):
        sx = min(matrix.m11(), matrix.m22())
        sy = max(matrix.m22(), sx)
        fm = QtGui.QFontMetrics(Colors.headingFont())

        w = fm.width(self.text) + 1
        h = fm.height()
        xShadow = 3.0
        yShadow = 3.0

        image = QtGui.QImage(int((w + xShadow) * sx), int((h + yShadow) * sy),
                QtGui.QImage.Format_ARGB32_Premultiplied)
        image.fill(QtGui.QColor(0, 0, 0, 0).rgba())
        painter = QtGui.QPainter(image)
        painter.setFont(Colors.headingFont())
        painter.scale(sx, sy)

        # Draw shadow.
        brush_shadow = QtGui.QLinearGradient(xShadow, yShadow, w, yShadow)
        brush_shadow.setSpread(QtGui.QLinearGradient.PadSpread)
        if Colors.useEightBitPalette:
            brush_shadow.setColorAt(0.0, QtGui.QColor(0, 0, 0))
        else:
            brush_shadow.setColorAt(0.0, QtGui.QColor(0, 0, 0, 100))
        pen_shadow = QtGui.QPen()
        pen_shadow.setBrush(brush_shadow)
        painter.setPen(pen_shadow)
        painter.drawText(int(xShadow), int(yShadow), int(w), int(h),
                QtCore.Qt.AlignLeft, self.text)

        # Draw text.
        brush_text = QtGui.QLinearGradient(0, 0, w, w)
        brush_text.setSpread(QtGui.QLinearGradient.PadSpread)
        brush_text.setColorAt(0.0, QtGui.QColor(255, 255, 255))
        brush_text.setColorAt(0.2, QtGui.QColor(255, 255, 255))
        brush_text.setColorAt(0.5, QtGui.QColor(190, 190, 190))
        pen_text = QtGui.QPen()
        pen_text.setBrush(brush_text)
        painter.setPen(pen_text)
        painter.drawText(0, 0, int(w), int(h), QtCore.Qt.AlignLeft, self.text)

        return image
Esempio n. 56
0
    def createContent(self):
        # Create the items.
        self.heading = HeadingItem(self.name, self)
        self.description = DemoTextItem(self.loadDescription(), Colors.contentFont(), Colors.heading, 500, self)
        imgHeight = 340 - int(self.description.boundingRect().height()) + 50
        self.screenshot = ImageItem(QImage.fromData(self._menu_manager.getImage(self.name)), 550, imgHeight, self)

        # Place the items on screen.
        self.heading.setPos(0, 3)
        self.description.setPos(0, self.heading.pos().y() + self.heading.boundingRect().height() + 10)
        self.screenshot.setPos(0, self.description.pos().y() + self.description.boundingRect().height() + 10)
 def get_companies_object_list(list_of_arguments, list_from_sql):
     for element in list_from_sql:
         element[2] = Colors.get_avg_color(element[2])
     companies_object_list = []
     dict_arguments_sql = {}
     for element in list_from_sql:
         for i in range(len(list_of_arguments)):
             dict_arguments_sql[list_of_arguments[i]] = element[i]
         company = Companies.get_object_from_dictionary(dict_arguments_sql)
         companies_object_list.append(company)
     return companies_object_list
Esempio n. 58
0
    def launchExample(self, name):
        executable = self.resolveExeFile(name)

        process = QtCore.QProcess(self)
        process.finished.connect(self.exampleFinished)
        process.error.connect(self.exampleError)

        if sys.platform == 'win32':
            # Make sure it finds the DLLs on Windows.
            curpath = os.getenv('PATH')
            newpath = 'PATH=%s;%s' % (QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath), curpath)
            process.setEnvironment([newpath])

        if self.info[name]['changedirectory'] != 'false':
            workingDirectory = self.resolveDataDir(name)
            process.setWorkingDirectory(workingDirectory)
            Colors.debug("Setting working directory:", workingDirectory)

        Colors.debug("Launching:", executable)
        process.start(sys.executable, [executable])