def make_move(state, action, game:BlackHole):
    newstate = state + action
    # fort = np.random.rand() < 0.5

    # if game.is_in_dang_region(newstate):
    #     return state, True
    # if game.is_out_of_bounds(newstate):
    #     return state,False
    # if fort:
    #     newstate += game.gradient[tuple(newstate.astype(int))].astype(int)
    if game.is_in_dang_region(newstate):
        return state, True
    if game.is_out_of_bounds(newstate):
        return state,False
    return newstate, False
Ejemplo n.º 2
0
def Play(screen):
    #Color of the screen
    screen.fill((0, 0, 20))

    #Creates the spaceship
    ship = Ship()
    #Creates the blackholes
    hole1 = BlackHole(200, 200, 100)
    hole2 = BlackHole(800, 200, 150)

    while (True):
        #Checks for events
        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                exit()
        #Gets the pressed key
        pressedKey = pygame.key.get_pressed()

        #Checks if the pressed key is W
        if pressedKey[pygame.K_w]:
            #Calls the MoveFront function
            ship.MoveFront()
        if pressedKey[pygame.K_s]:
            #Calls the MoveBack function
            ship.MoveBack()
        if pressedKey[pygame.K_d]:
            ship.RotateRight()
        if pressedKey[pygame.K_a]:
            ship.RotateLeft()

        #Cleans the screen
        screen.fill((0, 0, 20))
        #Calls the render function
        """Needs to pass the screen as argument or else the system doesn't
        know where to print"""
        hole1.Render(screen)
        hole2.Render(screen)
        ship.Render(screen)
        #Constant update
        """If we don't use this function the system will only render when we
        press keys, but with this function we will do all the movement"""
        hole1.attraction(ship)
        hole2.attraction(ship)
        ship.Update(hole1)
        ship.Update(hole2)
        #ship.UpdateRot()

        pygame.display.flip()
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
                # elif os.path.isdir(file_path): shutil.rmtree(file_path)
        except Exception as e:
            print(e)

def measure_perf(expert_traj, model, agent_trajs):
    logging.debug('Mean D for expert_traj: ' +str(np.mean(model.comp_Dw_part(expert_traj[0]))))
    logging.debug('Mean D for agent_traj: ' + str(np.mean(model.comp_Dw_part(agent_trajs[0]))))

if __name__ == '__main__':
    expert_traj = []
    model = SGDRegressor_occupancy(N, 4, 0)
    game = BlackHole(1,2)

    for i, t in enumerate(os.listdir('trajectories')):
        raw_traj = np.loadtxt('trajectories/' + t, dtype=int, delimiter=',')
        if np.atleast_2d(raw_traj).shape[0] > 2:
            onehot_traj = normalize_states(raw_traj, N)
            expert_traj.append(onehot_traj)

    expert_traj = np.array(expert_traj)
    # eOM = occ_measure(expert_traj)
    eOM = occupancy_measure_approx_vector(expert_traj)
    show_om(eOM)

    delete_imgs('images/')
    logging.basicConfig(filename='images/black_hole.log', level=logging.DEBUG)
Ejemplo n.º 4
0
def extractData(location, family):

    #db = DBWriter()
    #conn = db.connect()
    path = location
    files = os.listdir(path)
    directorySize = len(files)
    errorFile = open(BASE_PATH + "_" + family + "_metric_errors.txt", "w")
    print "!" * 150
    print "NOW EXTRACTING DATA FROM " + path
    print str(directorySize) + " APPS FOUND"
    print "!" * 150

    i = 1
    for f in files:

        sourceCodePaths = []
        layoutFilePaths = []
        decFolderPath = path + f

        filename = f + ".apk"
        #PRINTING HEADER
        print "*" * 50
        print "EXTRACTING DATA FROM FILE " + str(i) + " OF " + str(
            directorySize)
        print "*" * 50
        i += 1

        try:
            manifestDataExt = mde.ManifestDataExtractor(decFolderPath)
            if manifestDataExt.validateManifest():
                #get app name and package name from manifest
                appLabel, packageName = parseManifest(manifestDataExt,
                                                      decFolderPath)
                #get path for each source code file that we will consider
                smaliPath = decFolderPath + '/smali'

                dirPaths = getSourceCodeDirectoryPaths(smaliPath, packageName)

                ######  dir is malware family

                market = family

                package = f

                print "Market " + market
                date = getDate(market, f + ".apk")
                date = str(date.date())
                print "Date " + date

                if TRUSTED_MODE:

                    trusted = getOtherMetricTrusted(f)
                    appFQName = trusted['title']
                    package = trusted['package']
                    downloads = trusted['downloads']
                    version = trusted['version']
                    creator = trusted['creator']
                    superDev = 0
                    price = trusted['price']
                    offerT = 0
                    size = trusted['size']
                    rating = trusted['rating']
                    reviews = trusted['reviews']

                else:

                    appFQName = packageName
                    package = appLabel
                    downloads = ""
                    version = ""
                    creator = ""
                    superDev = 0
                    price = ""
                    offerT = 0
                    size = str(getAppSize(origin + market, filename))

                    rating = 0
                    reviews = 0

#revs = getReviews(appFQName)
#db.saveApkFile(package, appFQName, appFQName, '', date, market, downloads, version, creator, superDev, price, offerT, size, rating, reviews)

#navigate using fully qualified packageName
                for codeDir in dirPaths:
                    for root, dirs, files in os.walk(codeDir):
                        for file in files:
                            if file not in ignoreFiles:
                                sourceCodePaths.append(os.path.join(
                                    root, file))

                #calculate size metrics
                print "========  Size Metrics =========\n"
                sizeMetrics = SizeMetrics.SizeMetrics(sourceCodePaths)
                sizeMetrics.extractData()
                numInstructions = sizeMetrics.getNumInstructions()
                numMethods = sizeMetrics.getNumMethods()
                numClasses = sizeMetrics.getNumClasses()
                methodsPerClass = sizeMetrics.getMethodsPerClass()
                instrPerMethod = sizeMetrics.getInstructionsPerMethod()
                cyclomatic = sizeMetrics.getCyclomatic()
                wmc = sizeMetrics.getWMC()
                print "\n"
                #db.saveSizeMetric(numInstructions, numMethods, numClasses, methodsPerClass, instrPerMethod, cyclomatic, wmc)

                print "========  Chidamber and Kemerer Metrics =========\n"
                #calculate CK metrics
                ckMetrics = CKMetrics.CKMetrics(sourceCodePaths, packageName)

                ckMetrics.extractData()
                noc = ckMetrics.getNOC()
                dit = ckMetrics.getDIT()
                lcom = ckMetrics.getLCOM()
                cbo = ckMetrics.getCBO()
                ppiv = ckMetrics.getPPIV()
                apd = ckMetrics.getAPD()
                print "\n"

                #db.saveCKMetric(noc, dit, lcom, cbo, ppiv, apd)

                print "========  MVC Metrics =========\n"
                #calculate MVC metrics
                mvcMetrics = MVCMetrics.MVCMetrics(sourceCodePaths,
                                                   layoutFilePaths)
                mvcMetrics.extractData()
                mvc = mvcMetrics.getSepVCScore()
                avgNumViewsInXML = mvcMetrics.getAvgNumViewsInXML()

                maxNumViewsInXML = mvcMetrics.getMaxNumViewsInXML()
                numViewsInXml = mvcMetrics.getNumViewsInXml()
                numViewsInController = mvcMetrics.getNumViewsInController()
                numViewsNotInController = mvcMetrics.getNumViewsNotInController(
                )
                viewsNotInControllerPerc = mvcMetrics.getSepVCScore()
                potBadToken = mvcMetrics.getPotentialBadTokenExceptions()
                numFragments = mvcMetrics.getNumFragments()
                print "\n"

                #db.saveMVCMetric(numViewsInController, numViewsNotInController, numViewsInXml, maxNumViewsInXML, viewsNotInControllerPerc, potBadToken, numFragments)

                #calculate other metrics

                print "========  Unchecked bundles Metrics =========\n"
                otherMetrics = OtherMetrics.OtherMetrics(
                    sourceCodePaths, layoutFilePaths)
                otherMetrics.extractData()

                numBundles = otherMetrics.getNumBundles()
                checkedBundles = otherMetrics.getNumCheckedBundles()
                uncheckedBundles = otherMetrics.getNumUncheckedBundles()
                objMap = len(otherMetrics.getObjectMap())

                print "\n"

                #db.saveOtherMetric(numBundles, checkedBundles, uncheckedBundles, objMap)

                #bad smell methods
                #                 bsmc = BadSmellMethodCalls.BadSmellMethodCalls(sourceCodePaths,layoutFilePaths)
                #                 bsmc.extractData()
                #                 show = bsmc.getNumShowCalls()
                #                 dismiss = bsmc.getNumDismissCalls()
                #                 setContentView = bsmc.getNumSetContentViewCalls()
                #                 createScaledBitmap = bsmc.getNumCreateScaledBitmapCalls()
                #                 onKeyDown = bsmc.getNumOnKeyDownCalls()
                #                 isPlaying = bsmc.getNumIsPlayingCalls()
                #                 unregisterReceiver = bsmc.getNumUnregisterRecieverCalls()
                #                 onBackPressed = bsmc.getNumOnBackPressedCalls()
                #                 showDialog = bsmc.getNumShowDialogCalls()
                #                 create = bsmc.getNumCreateCalls()

                print "========  unchecked Bad Smells Metrics =========\n"
                #unchecked bad smell methods
                cbsmc = UncheckedBadSmellMethodCalls.UncheckedBadSmellMethodCalls(
                    sourceCodePaths, layoutFilePaths)
                cbsmc.extractData()

                cshow = cbsmc.getNumShowCalls()
                cdismiss = cbsmc.getNumDismissCalls()
                csetContentView = cbsmc.getNumSetContentViewCalls()
                ccreateScaledBitmap = cbsmc.getNumCreateScaledBitmapCalls()
                conKeyDown = cbsmc.getNumOnKeyDownCalls()
                cisPlaying = cbsmc.getNumIsPlayingCalls()
                cunregisterReceiver = cbsmc.getNumUnregisterRecieverCalls()
                conBackPressed = cbsmc.getNumOnBackPressedCalls()
                cshowDialog = cbsmc.getNumShowDialogCalls()
                ccreate = cbsmc.getNumCreateCalls()

                print "\n"

                #db.saveUncheckedBadSmellsMetric(cshow, cdismiss, csetContentView, ccreateScaledBitmap, conKeyDown, cisPlaying, cunregisterReceiver, conBackPressed, cshowDialog, ccreate)

                print "========  Battery Life Metrics =========\n"
                #Battery Life metrics
                batteryMetrics = BatteryMetrics.BatteryMetrics(
                    sourceCodePaths, layoutFilePaths)
                batteryMetrics.extractData()

                noTimeoutWakeLocks = batteryMetrics.getNumNoTimeoutWakeLocks()
                locListeners = batteryMetrics.getNumLocationListeners()
                gpsUses = batteryMetrics.getNumGpsUses()
                domParsers = batteryMetrics.getNumDomParsers()
                saxParsers = batteryMetrics.getNumSaxParsers()
                xmlPullParsers = batteryMetrics.getNumXMLPullParsers()

                print "\n"

                #db.saveBatteryMetric(noTimeoutWakeLocks, locListeners, gpsUses, domParsers, saxParsers, xmlPullParsers)

                #network timeout metrics
                print "========  Network Timeout Metrics =========\n"
                networkTimeout = NetworkTimeout.NetworkTimeout(
                    sourceCodePaths, layoutFilePaths)
                networkTimeout.extractData()
                httpClients = networkTimeout.getNumHttpClients()
                numConTimeouts = networkTimeout.getNumConTimeouts()
                numSoTimeouts = networkTimeout.getNumSoTimeouts()
                numNoConTimeouts = networkTimeout.getNumNoConTimeout()
                numNoSoTimeouts = networkTimeout.getNumNoSoTimeout()

                print "\n"

                #db.saveNetworkMetric(httpClients, numConTimeouts, numSoTimeouts, numNoConTimeouts, numNoSoTimeouts)

                #black hole exception handling
                print "========  Black Hole Exception Handling Metrics =========\n"
                blackHole = BlackHole.BlackHole(sourceCodePaths,
                                                layoutFilePaths)
                blackHole.extractData()
                numCatchBlocks = blackHole.getNumCatchBlocks()
                numLogOnly = blackHole.getNumLogOnly()
                numNoAction = blackHole.getNumNoAction()
                #
                print "Catch Blocks " + str(numCatchBlocks)
                print "LogOnly " + str(numLogOnly)
                print "No action " + str(numNoAction)
                print "\n"

                #db.saveBlackHolekMetric(numCatchBlocks, numLogOnly, numNoAction)

                #ANR Metrics
                print "========  ANR Metrics =========\n"
                anrMetrics = ANRMetrics.ANRMetrics(sourceCodePaths,
                                                   layoutFilePaths)
                anrMetrics.extractData()

                network = anrMetrics.getNumNetworkOnMainThread()
                sqlLite = anrMetrics.getNumSQLLiteOnMainThread()
                fileIO = anrMetrics.getNumFileIOOnMainThread()
                bitmap = anrMetrics.getNumBitmapOnMainThread()

                print "\n"

                #db.saveANRkMetric(network, sqlLite, fileIO, bitmap)

                #intent launch metrics
                print "========  Intent Launch Metrics =========\n"
                intentLaunchMetrics = IntentLaunchMetrics.IntentLaunchMetrics(
                    sourceCodePaths, layoutFilePaths, packageName)
                intentLaunchMetrics.extractData()

                startActivities = intentLaunchMetrics.getNumStartActivities()
                startActivity = intentLaunchMetrics.getNumStartActivity()
                startInstrumentation = intentLaunchMetrics.getNumStartInstrumentation(
                )
                startIntentSender = intentLaunchMetrics.getNumStartIntentSender(
                )
                startService = intentLaunchMetrics.getNumStartService()
                startActionMode = intentLaunchMetrics.getNumStartActionMode()
                startActivityForResult = intentLaunchMetrics.getNumStartActivityForResult(
                )
                startActivityFromChild = intentLaunchMetrics.getNumStartActivityFromChild(
                )
                startActivityFromFragment = intentLaunchMetrics.getNumStartActivityFromFragment(
                )
                startActivityIfNeeded = intentLaunchMetrics.getNumStartActivityIfNeeded(
                )
                startIntentSenderForResult = intentLaunchMetrics.getNumStartIntentSenderForResult(
                )
                startIntentSenderFromChild = intentLaunchMetrics.getNumStartIntentSenderFromChild(
                )
                startNextMatchingActivity = intentLaunchMetrics.getNumStartNextMatchingActivity(
                )
                startSearch = intentLaunchMetrics.getNumStartSearch()

                print "\n"

                #db.saveIntentLaunchkMetric(startActivities, startActivity, startInstrumentation, startIntentSender, startService, startActionMode, startActivityForResult, startActivityFromChild, startActivityFromFragment, startActivityIfNeeded, startIntentSenderForResult, startIntentSenderFromChild, startNextMatchingActivity, startSearch)

                folder = decFolderPath

                print "========  API Information =========\n"
                yml = open(decFolderPath + '/apktool.yml')
                print(yml.read())
                yml.close()
                print "\n"

                print "Eliminazione " + decFolderPath

                for the_file in os.listdir(folder):
                    file_path = os.path.join(folder, the_file)
                    try:
                        if os.path.isfile(file_path):
                            os.unlink(file_path)
                        elif os.path.isdir(file_path):
                            shutil.rmtree(file_path)
                    except Exception, e:
                        print e


#                 db.writeAppTable(filename, appLabel, packageName, market)
#                 db.writeSizeMetricsTable(filename, numInstructions, numMethods,
#                 numClasses, methodsPerClass, instrPerMethod, cyclomatic, wmc)
#                 db.writeOOMetricsTable(filename, noc, dit, lcom, cbo, ppiv, apd)
#                 db.writeMVCMetricsTable(filename, mvc, avgNumViewsInXML,
#                 maxNumViewsInXML)
#                 db.writeOtherMetricsTable(filename, uncheckedBundles, potBadToken)
#                 db.updateNumFragments(filename,numFragments)
#                 db.writeAndroidObjectsTable(filename, objMap)
# #                 db.writeBadSmellMethodCallsTable(filename, show, dismiss,
# #                 setContentView, createScaledBitmap, onKeyDown, isPlaying, unregisterReceiver,
# #                 onBackPressed, showDialog, create)
#                 db.writeUncheckedBadSmellMethodCallsTable(filename, cshow, cdismiss,
#                 csetContentView, ccreateScaledBitmap, conKeyDown, cisPlaying, cunregisterReceiver,
#                 conBackPressed, cshowDialog, ccreate)
#                 db.writeBatteryMetrics(filename, noTimeoutWakeLocks, locListeners,
#                 gpsUses, domParsers, saxParsers, xmlPullParsers)
#                 db.writeNetworkTimeoutMetrics(filename, httpClients, numConTimeouts,
#                 numSoTimeouts, numNoConTimeouts, numNoSoTimeouts)
#                 db.writeBlackHole(filename, numCatchBlocks, numLogOnly, numNoAction)
#                 db.writeANRMetrics(filename, network, sqlLite, fileIO, bitmap,
#                 networkBg, sqlLiteBg, fileIOBg, bitmapBg)
#                 db.writeIntentLaunchMetrics(filename, startActivities, startActivity,
#                 startInstrumentation, startIntentSender, startService, startActionMode,
#                 startActivityForResult, startActivityFromChild, startActivityFromFragment,
#                 startActivityIfNeeded, startIntentSenderForResult, startIntentSenderFromChild,
#                 startNextMatchingActivity, startSearch)
            else:
                print "ERROR FOUND WITH FILE AndroidManifest.xml"