Best Python code snippet using fMBT_python
fmbtchromiumos.py
Source:fmbtchromiumos.py  
...109             ("mkdir -p %s; tar x -C %s" % (destDir, destDir),),110             package.read())111    def agentExec(self, pythonCode):112        self._agent.exec_in(self._agent_ns, pythonCode)113    def agentEval(self, pythonExpression):114        return self._agent.eval_in(self._agent_ns, pythonExpression)115    def open(self):116        myDir = os.path.dirname(os.path.abspath(117            inspect.getfile(inspect.currentframe())))118        self.sendFilesInTar(myDir,119                            ("fmbtx11_conn.py",120                             "fmbtpng.py",121                             "fmbtuinput.py"),122                            "/tmp/fmbtchromiumos")123        if os.access(os.path.join(myDir, "pythonshare", "__init__.py"), os.R_OK):124            pythonshareDir = myDir125        elif os.access(os.path.join(myDir, "..", "pythonshare", "pythonshare",126                                    "__init__.py"), os.R_OK):127            pythonshareDir = os.path.join(myDir, "..", "pythonshare")128        self.sendFilesInTar(pythonshareDir,129                            ("pythonshare/__init__.py",130                             "pythonshare/server.py",131                             "pythonshare/client.py",132                             "pythonshare/messages.py"),133                            "/tmp/fmbtchromiumos")134        if os.name != "nt":135            pythonshareServer = distutils.spawn.find_executable("pythonshare-server")136        else:137            pythonshareServer = os.path.join(138                os.path.dirname(__file__), "..", "Scripts", "pythonshare-server")139        if not pythonshareServer or not os.access(pythonshareServer, os.R_OK):140            raise FMBTChromiumOsError("cannot find pythonshare-server executable")141        self.sendFilesInTar(os.path.dirname(pythonshareServer),142                            ("pythonshare-server",),143                            "/tmp/fmbtchromiumos")144        agentCmd = (self._loginCommand +145                    " sudo DISPLAY=:0 XAUTHORITY=/home/chronos/.Xauthority" +146                    " LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64:/usr/lib:/usr/lib64" +147                    " python /tmp/fmbtchromiumos/pythonshare-server -p stdin")148        self._agent = pythonshare.connection("shell://" + agentCmd)149        self._agent_ns = "fmbtchromiumos-agent"150        try:151            self.agentExec("import fmbtx11_conn")152        except pythonshare.PythonShareError, e:153            raise FMBTChromiumOsError(154                "Cannot connect to pythonshare-server on device (%s): %s" %155                (e, agentCmd))156        self.agentExec("x = fmbtx11_conn.Display()")157    def recvScreenshot(self, filename):158        img = self.agentEval("x.recvScreenshot()")159        if img.startswith("FMBTRAWX11"):160            try:161                header, zdata = img.split('\n', 1)162                width, height, depth, bpp = [int(n) for n in header.split()[1:]]163                data = zlib.decompress(zdata)164            except Exception, e:165                raise FMBTChromiumOsError("Corrupted screenshot data: %s" % (e,))166            if len(data) != width * height * 4:167                raise FMBTChromiumOsError("Image data size mismatch.")168            fmbtgti.eye4graphics.bgrx2rgb(data, width, height)169            # TODO: use libimagemagick directly to save data to png?170            ppm_header = "P6\n%d %d\n%d\n" % (width, height, 255)171            f = file(filename + ".ppm", "wb").write(ppm_header + data[:width*height*3])172            _run([fmbt_config.imagemagick_convert, filename + ".ppm", filename])173            os.remove("%s.ppm" % (filename,))174        else:175            file(filename, "wb").write(img)176        return True177    def sendType(self, text):178        return self.agentEval('x.sendType(%s)' % (repr(text),))179    def sendPress(self, keyCode, modifiers=None):180        if modifiers != None:181            raise NotImplementedError182        return self.agentEval("x.sendPress(%s)" % (repr(keyCode),))183    def sendKeyDown(self, keyCode, modifiers=None):184        if modifiers != None:185            raise NotImplementedError186        return self.agentEval("x.sendKeyDown(%s)" % (repr(keyCode),))187    def sendKeyUp(self, keyCode, modifiers=None):188        if modifiers != None:189            raise NotImplementedError190        return self.agentEval("x.sendKeyUp(%s)" % (repr(keyCode),))191    def sendTap(self, x, y, button=None):192        if button == None:193            # TODO: synthesize touch display event, if available194            command = "x.sendTap(%s, %s)" % (x, y)195        else:196            command = "x.sendTap(%s, %s, %s)" % (x, y, button)197        return self.agentEval(command)198    def sendTouchDown(self, x, y, button=None):199        if button == None:200            # TODO: synthesize touch display event, if available201            command = "x.sendTouchDown(%s, %s)" % (x, y)202        else:203            command = "x.sendTouchDown(%s, %s, %s)" % (x, y, button)204        return self.agentEval(command)205    def sendTouchMove(self, x, y, button=None):206        if button == None:207            # TODO: synthesize touch display event, if available208            command = "x.sendTouchMove(%s, %s)" % (x, y)209        else:210            command = "x.sendTouchMove(%s, %s)" % (x, y)211        return self.agentEval(command)212    def sendTouchUp(self, x, y, button=None):213        if button == None:214            # TODO: synthesize touch display event, if available215            command = "x.sendTouchUp(%s, %s)" % (x, y)216        else:217            command = "x.sendMouseUp(%s, %s, %s)" % (x, y, button)218        return self.agentEval(command)219    def shellSOE(self, shellCommand, username, asyncStatus, asyncOut, asyncError, usePty):220        _, (s, o, e) = self.agentEval(221            "fmbtx11_conn.shellSOE(%s, %s, %s, %s, %s, %s)" % (222                repr(shellCommand), repr(username), repr(asyncStatus),223                repr(asyncOut), repr(asyncError), repr(usePty)))224        return s, o, e...plotter.py
Source:plotter.py  
1from mpl_toolkits.mplot3d import Axes3D2import matplotlib.pyplot as plt3from matplotlib import cm4from matplotlib.ticker import LinearLocator, FormatStrFormatter5import numpy as np67from pso import Swarm8from functions import *910class Plotter(object):1112	# def __init__(self, arg):13		14	def plotPso(agentPozByEpoch,agentEvalsByEpoch,particleRange):15		# preconditions16		assert (isinstance(particleRange,tuple))17		# variables18		(minRange,maxRange) = particleRange19		# instantiate figure20		fig = plt.figure()21		ax = fig.gca(projection = '3d')22		plt.ion()23		# compute the plot surface (evaluation of func over the whole domain)24		Xgrid = np.arange(minRange,maxRange,0.01)25		Ygrid = np.arange(minRange,maxRange,0.01)26		Xgrid, Ygrid = np.meshgrid(Xgrid,Ygrid)27		Zvalue = applyToMeshgrid(Rossenbrock,Xgrid,Ygrid)28		# Plot the surface.29		surf = ax.plot_surface(Xgrid,Ygrid,Zvalue,cmap=cm.coolwarm,linewidth=0, antialiased=False)30		# Add a color bar which maps values to colors.31		fig.colorbar(surf, shrink=0.5, aspect=5)32		# for all the epochs, scatter plot particles positions and their evaluation33		for epoch in range(0,len(agentPozByEpoch)):34			agentPozX = [ agentPozByEpoch[epoch][nrAgent][0] for nrAgent in range(0,len(agentPozByEpoch[epoch])) ]35			agentPozY = [ agentPozByEpoch[epoch][nrAgent][1] for nrAgent in range(0,len(agentPozByEpoch[epoch])) ]36			# Scatter plot the particles37			agentEval = agentEvalsByEpoch[epoch]38			ax.scatter(agentPozX,agentPozY,agentEval, marker = '+')39		# return the figure with the plot40			plt.show()41			plt.pause(2)4243		return fig 4445	def plotParticles(agentPozByEpoch,agentEvalsByEpoch,particleRange):46		# preconditions47		assert (isinstance(particleRange,tuple))48		# variables49		(minRange,maxRange) = particleRange50		# instantiate figure51		fig = plt.figure()52		ax = fig.gca(projection = '3d')53		# for all the epochs, scatter plot particles positions and their evaluation54		for epoch in range(0,len(agentPozByEpoch)):55			agentPozX = [ agentPozByEpoch[epoch][nrAgent][0] for nrAgent in range(0,len(agentPozByEpoch[epoch])) ]56			agentPozY = [ agentPozByEpoch[epoch][nrAgent][1] for nrAgent in range(0,len(agentPozByEpoch[epoch])) ]57			ax.scatter(agentPozX,agentPozY,epoch, marker = '*')5859		plt.show()60		plt.pause(100)61	6263646566swarm = Swarm(20)67gb, Xs, Ys = swarm.pso((-3,3),Rossenbrock)68fig = Plotter.plotPso(Xs,Ys,(-3,3))69# Plotter.plotParticles(Xs,Ys,(-3,3))
...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
