How to use existingConnection method in fMBT

Best Python code snippet using fMBT_python

genome.py

Source:genome.py Github

copy

Full Screen

1import random2from NEAT.NEAT_implementation.Genotype.connection import Connection3from NEAT.NEAT_implementation.Genotype.node import Node4class Genome:5 def __init__(self):6 self.connections = []7 self.nodes = []8 self.nodeIds = set()9 self.innovationNumbers = set()10 self.fitness = None11 self.adjustedFitness = None12 self.species = None13 def addConnectionMutation(self):14 possibleInputs = [n.id for n in self.nodes if n.type != 'output']15 possibleOutputs = [n.id for n in self.nodes if n.type != 'input' and n.type != 'bias']16 if len(possibleOutputs) is not 0 and len(possibleInputs) is not 0:17 inputNodeId = random.choice(possibleInputs)18 outputNodeId = random.choice(possibleOutputs)19 if self.checkValidConnection(inputNodeId, outputNodeId):20 self.addConnection(inputNodeId, outputNodeId)21 def addNodeMutation(self):22 newNode = self.addNode('hidden')23 existingConnection = self.getRandomConnection()24 self.addConnection(existingConnection.inputNodeId, newNode.id, weight=1)25 self.addConnection(newNode.id, existingConnection.outputNodeId, weight=existingConnection.weight)26 existingConnection.active = False27 def countExcessGenes(self, other):28 excessGeneCounter = 029 innovationNumberMaximum = max(other.innovationNumbers)30 for connection in self.connections:31 if connection.innovationNumber > innovationNumberMaximum:32 excessGeneCounter += 133 nodeIdMaximum = max([node.id for node in other.nodes])34 for node in self.nodes:35 if node.id > nodeIdMaximum:36 excessGeneCounter += 137 return excessGeneCounter38 def countDisjointGenes(self, other):39 disjointgeneCounter = 040 innovationNumberMaximum = max(other.innovationNumbers)41 for connection in self.connections:42 if connection.innovationNumber <= innovationNumberMaximum:43 if other.getConnection(connection.innovationNumber) is None:44 disjointgeneCounter += 145 nodeIdMaximum = max([node.id for node in other.nodes])46 for node in self.nodes:47 if node.id <= nodeIdMaximum:48 if other.getNode(node.id) is None:49 disjointgeneCounter += 150 return disjointgeneCounter51 def getConnection(self, innovationNumber):52 for connection in self.connections:53 if connection.innovationNumber == innovationNumber:54 return connection55 return None56 def getNode(self, nodeId):57 for node in self.nodes:58 if node.id == nodeId:59 return node60 return None61 def getAverageWeightDifference(self, other):62 weightDifference = 0.063 weightNumber = 0.064 for connection in self.connections:65 matchingConnection = other.getConnection(connection.innovationNumber)66 if matchingConnection is not None:67 weightDifference += float(connection.weight) - float(matchingConnection.weight)68 weightNumber += 169 if weightNumber == 0.0:70 weightNumber = 1.071 return weightDifference / weightNumber72 def getNodeInputIds(self, nodeId):73 nodeInputIds = []74 for connection in self.connections:75 if (connection.outputNodeId == nodeId) and connection.active:76 nodeInputIds.append(connection.inputNodeId)77 return nodeInputIds78 def addConnection(self, inputNodeId, outputNodeId, active=True, weight=None):79 newConnection = Connection(inputNodeId, outputNodeId, active)80 if weight is not None:81 newConnection.setWeight(float(weight))82 self.connections.append(newConnection)83 self.nodeIds.add(inputNodeId)84 self.nodeIds.add(outputNodeId)85 self.innovationNumbers.add(newConnection.innovationNumber)86 def addNode(self, nodeType):87 nodeId = len(self.nodes)88 node = Node(nodeId, nodeType)89 self.nodes.append(node)90 return node91 def addConnectionCopy(self, copy):92 newConnection = Connection(copy.inputNodeId, copy.outputNodeId, copy.active)93 newConnection.setWeight(float(copy.weight))94 newConnection.setInnovationNumber(copy.innovationNumber)95 self.connections.append(newConnection)96 self.nodeIds.add(copy.inputNodeId)97 self.nodeIds.add(copy.outputNodeId)98 self.innovationNumbers.add(newConnection.innovationNumber)99 def addNodeCopy(self, copy):100 self.nodes.append(Node(copy.id, copy.type))101 def getInputConnections(self, nodeId):102 connections = []103 for connection in self.connections:104 if (connection.outputNodeId == nodeId) and connection.active:105 connections.append(connection)106 return connections107 def getRandomNodeId(self):108 return random.choice(list(self.nodeIds))109 def getRandomConnection(self):110 return random.choice(self.connections)111 def getOutputConnections(self, nodeId):112 connections = []113 for connection in self.connections:114 if (connection.inputNodeId == nodeId) and connection.active:115 connections.append(connection)116 return connections117 def checkCyclicity(self, inputNodeId, outputNodeId):118 if inputNodeId == outputNodeId:119 return True120 visited = {outputNodeId}121 while True:122 counter = 0123 for connection in self.connections:124 if connection.inputNodeId in visited and connection.outputNodeId not in visited:125 if connection.outputNodeId == inputNodeId:126 return True127 else:128 visited.add(connection.outputNodeId)129 counter += 1130 if counter == 0:131 return False132 def checkValidConnection(self, inputNodeId, outputNodeId):133 isThereCycle = self.checkCyclicity(inputNodeId, outputNodeId)134 exists = self.checkExistence(inputNodeId, outputNodeId)135 return (not isThereCycle) and (not exists)136 def checkExistence(self, inputNodeId, outputNodeId):137 for connection in self.connections:138 if (connection.inputNodeId == inputNodeId) and (connection.outputNodeId == outputNodeId):139 return True140 elif (connection.inputNodeId == outputNodeId) and (connection.outputNodeId == inputNodeId):141 return True142 return False143 def getOutputNodes(self, node, nodes):144 outputNodeIds = [connection.outputNodeId for connection in self.connections if (connection.inputNodeId == node.id) and connection.active]145 return [outputNode for outputNode in nodes if outputNode.id in outputNodeIds]146 def orderNodesByValue(self, nodeValues):147 nodes = [nodeValue.referenceNode for nodeValue in nodeValues]148 visited = set()149 ordered = []150 for node in nodes:151 if node not in visited:152 self.innerOrdering(node, nodes, ordered, visited)153 orderedNodeValues = []154 for node in ordered:155 for nodeValue in nodeValues:156 if nodeValue.referenceNode == node:157 orderedNodeValues.append(nodeValue)158 break159 return orderedNodeValues160 def innerOrdering(self, node, nodes, ordered, visited):161 visited.add(node)162 for outputNode in self.getOutputNodes(node, nodes):163 if outputNode not in visited:164 self.innerOrdering(outputNode, nodes, ordered, visited)...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

1import random2import string3from django.contrib.auth.decorators import login_required4from django.shortcuts import render, get_object_or_404, redirect5from django.http import HttpResponse, JsonResponse, HttpResponseForbidden, HttpResponseRedirect, HttpResponseBadRequest6from .models import Connection, Token7from django.views.decorators.csrf import csrf_exempt8from django.views.decorators.http import require_POST9from django.contrib.auth import login, authenticate, logout10from django.contrib.auth.models import User11from django.core.exceptions import PermissionDenied12from django.urls import reverse13# import the logging library14import logging15# Get an instance of a logger16logger = logging.getLogger(__name__)17def index(request):18 return render(request, 'index.html')19def login_form(request):20 return render(request, 'login.html', {'incorrect_login': False})21def register_form(request):22 return render(request, 'register.html', {'incorrect_login': False})23def do_logout(request):24 logout(request)25 return HttpResponseRedirect(reverse('index'))26def incorrect_login_form(request):27 return render(request, 'login.html', {'incorrect_login': True})28def incorrect_register_form(request):29 return render(request, 'register.html', {'incorrect_login': True})30def do_login(request):31 if 'username' in request.POST and 'password' in request.POST:32 username = request.POST['username']33 password = request.POST['password']34 user = authenticate(request, username=username, password=password)35 if user is not None:36 login(request, user)37 createToken(user)38 return HttpResponseRedirect(reverse('main_friends'))39 else:40 return HttpResponseRedirect(reverse('incorrect_login_form'))41 else:42 return HttpResponseBadRequest("request must contain username and password")43def do_register(request):44 if 'username' in request.POST and 'password' in request.POST and 'email' in request.POST:45 username = request.POST['username']46 password = request.POST['password']47 email = request.POST['email']48 user = User.objects.create_user(username, email, password)49 logger.info("created user")50 logger.info(user)51 user = authenticate(request, username=username, password=password)52 if user is not None:53 login(request, user)54 createToken(user)55 return HttpResponseRedirect(reverse('main_friends'))56 else:57 return HttpResponseRedirect(reverse('incorrect_register_form'))58 else:59 return HttpResponseBadRequest("request must contain username and password")60@login_required61def main_friends(request):62 return render(request, 'main_friends.html')63@login_required64def main_upload(request):65 return render(request, 'main_upload.html', {'token': fetchToken(request.user)})66@login_required67def main_photos(request):68 return render(request, 'main_photos.html', {'token': fetchToken(request.user)})69@login_required70def get_friends(request):71 users = User.objects.all()72 usersParsed = []73 for user in users:74 connection = Connection.objects.filter(follower=request.user).filter(following=user.id)75 if connection:76 usersParsed.append({'username': user.username, 'id': user.id, 'follows': True})77 else:78 usersParsed.append({'username': user.username, 'id': user.id, 'follows': False})79 return JsonResponse({'users': list(usersParsed)})80@login_required81@csrf_exempt82def follow(request):83 if 'id' not in request.POST:84 raise PermissionDenied85 following = User.objects.get(id=request.POST['id'])86 existingConnection = Connection.objects.filter(follower=request.user).filter(following=following)87 if existingConnection.count() == 0:88 Connection.objects.create(follower=request.user, following=following)89 else:90 existingConnection.delete()91 return HttpResponse()92@csrf_exempt93def get_followings_request(request):94 logger.info("before")95 if 'HTTP_AUTHENTICATION' not in request.META:96 raise PermissionDenied97 logger.info("after")98 user = fetchUser(request.META['HTTP_AUTHENTICATION'])99 connections = Connection.objects.filter(follower=user)100 followingsParsed = []101 for connection in connections:102 followingsParsed.append({'id': connection.following.id, 'username': connection.following.username})103 return JsonResponse({ 'userId': user.id, 'friends': list(followingsParsed) })104def createToken(user):105 alreadyExistingToken = Token.objects.filter(user=user)106 alreadyExistingToken.delete()107 tokenString = str(user.id) + '-' + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(50))108 Token.objects.create(user=user, token=tokenString)109def fetchToken(user):110 return Token.objects.filter(user=user).first().token111def fetchUser(token):...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful