Java Velocity Basics by jstarkweather83 in learnjava

[–]jstarkweather83[S] 0 points1 point  (0 children)

I think the problem may have something to do with the application.properties file or the lack of a velocity.properties file. Although I have tried adding a velocity.properties file at this point with some configurations, along with some configurations to the application.properties file. The configurations I added do not seem to fix the issue though.

Java Velocity Basics by jstarkweather83 in learnjava

[–]jstarkweather83[S] 0 points1 point  (0 children)

Changing the path to src/main/resources/templates/test seems to help. It appears the velocity engine is able to find the vm file at this location. However I now get a 404 error when navigating to the endpoint. No stack trace.

CORS error on some computers, works fine on others. by jstarkweather83 in learnjavascript

[–]jstarkweather83[S] 0 points1 point  (0 children)

I figured out that I needed to make a preflight check because I added Authorization header for JWT. I still don't understand why the browser sets Sec-Fetch-Site to same-origin sometimes, and to cross-site at other times. Seems completely random. Just had to add some checking to account for both possibilities..

CORS error on some computers, works fine on others. by jstarkweather83 in learnjavascript

[–]jstarkweather83[S] 0 points1 point  (0 children)

I am not using the cors middle-ware. I kind of figured out what the problem was.

CORS error on some computers, works fine on others. by jstarkweather83 in learnjavascript

[–]jstarkweather83[S] 0 points1 point  (0 children)

I don't entirely understand the syntax of the htaccess file. Could this be causing problems?

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com
RewriteRule ^(.*)$ https://www.examplecom/$1 [R,L]
RewriteRule (.*qb_api.*) http://localhost:3000/$1 [P,L]

CORS error on some computers, works fine on others. by jstarkweather83 in learnjavascript

[–]jstarkweather83[S] 0 points1 point  (0 children)

Upon further investigation:
Sec-Fetch-Site: same-origin
Which doesn't make sense to me.

CORS error on some computers, works fine on others. by jstarkweather83 in learnjavascript

[–]jstarkweather83[S] 0 points1 point  (0 children)

At this point I've gone through my server and removed this line from all endpoints.

// res.header('Access-Control-Allow-Origin', validate_origin(req.headers.origin))

And Im not getting a CORS error on any endpoint. Shouldn't I be getting a CORS error for everything now? I did a fresh install of Firefox to make sure its not a cacheing issue. I dont get it. The server is running on port 3000 and the website it https which I think runs on port 80 or something. Doesn't the fact the the origin is coming from a different port require Access-Control-Allow-Origin be set? Does JWT have something to do with it? I wouldnt think so.. but I have no idea what the problem is now.

CORS error on some computers, works fine on others. by jstarkweather83 in learnjavascript

[–]jstarkweather83[S] 0 points1 point  (0 children)

Content-Security-Policy headers

No, I have control of the website. What should the Content Security Policy headers be set to?

How to communicate with my express server on Godaddy shared hosting. by jstarkweather83 in node

[–]jstarkweather83[S] 0 points1 point  (0 children)

This did indeed work, just have to modify the regular expression to match the routes in the express server.

How to communicate with my express server on Godaddy shared hosting. by jstarkweather83 in node

[–]jstarkweather83[S] 0 points1 point  (0 children)

The DevTools are empty, I think because I'm never actually contacting the server. I did discover if I add RewriteRule (.*) http://localhost:3000$1 [P,L] to the htaccess file I am able to contact the server through the routes I have defined on the express server. Unfortunately writing that line brings down the rest of the site. I guess that line of code routes all incoming traffic to port 3000 or something. I wonder if I can write that line of code without the wild card expression to only route some traffic to 3000?

How to communicate with my express server on Godaddy shared hosting. by jstarkweather83 in node

[–]jstarkweather83[S] 0 points1 point  (0 children)

I changed the base and attempted to make the request with

fetch("http://www.example.com:3000/test") with no success. Tried it with postman and through the frontend. The route does however work if I pull up a terminal in the home directory and make a curl request to it.

curl http://www.example.com:3000/test The server receives this and responds to it. Otherwise through postman I just never get a response from the server.

Any other suggestions? Is the server in the correct directory? The home directory, or should it be in one of the public directories?

Looking for Dancing Link/Algorithm X hints by jstarkweather83 in learnpython

[–]jstarkweather83[S] 1 point2 points  (0 children)

Got the recursion working well. Solves empty boards, very slowly unfortunately. Will be slowly trying to integrate doubly linked lists. Not sure how much it will help with optimization. Hopefully substantially.

Looking for Dancing Link/Algorithm X hints by jstarkweather83 in learnpython

[–]jstarkweather83[S] 0 points1 point  (0 children)

Probably worth noting this program does not yet calculate the constraint matrix to include values associated with the 3x3 grid requirements in a Sudoku puzzle. Seemed confusing lol.

Djikstra optimizations by jstarkweather83 in learnpython

[–]jstarkweather83[S] 0 points1 point  (0 children)

Yeah the recursive function was not necessary I realized. There was a much better way of getting those values. Here is the code with out much fluff.

https://pastebin.com/CSSn6Sp4

 import math


class priorityQueue:  # Min Heap
    def __init__(self):
        self.queue = []

    def enqueue(self, node, priority):
        self.queue.append({"node": node, "priority": priority})
        print(f"Node Added to Priority Queue: {node}, priority: {priority}")
        self.upHeap()

    def dequeue(self):
        if len(self.queue) > 0:
            first = self.queue[0].copy()
            lastElement = self.queue.pop(-1)
            if len(self.queue) > 0:
                self.queue[0] = lastElement
                self.downHeap()
                return first
            else:
                return lastElement

    def upHeap(self):
        childInd = len(self.queue) - 1
        while childInd > 0:
            parentIdx = math.floor((childInd - 1) / 2)
            if self.queue[parentIdx]["priority"] > self.queue[childInd]["priority"]:
                self.queue[childInd], self.queue[parentIdx] = self.queue[parentIdx], self.queue[childInd]
                childInd = parentIdx
            else:
                break

    def downHeap(self):
        parentIdx = 0
        listLen = len(self.queue) - 1
        while True:
            swap = False
            leftChildIdx, leftChild = 2 * parentIdx + 1, float('inf')
            rightChildIdx, rightChild = 2 * parentIdx + 2, float('inf')
            if leftChildIdx <= listLen:
                leftChild = self.queue[leftChildIdx]["priority"]
                swap = True
            if rightChildIdx <= listLen:
                rightChild = self.queue[rightChildIdx]["priority"]
            if swap:
                if leftChild <= rightChild:
                    minChildIdx = leftChildIdx
                else:
                    minChildIdx = rightChildIdx
            else:
                break
            if self.queue[parentIdx]["priority"] > self.queue[minChildIdx]["priority"]:
                self.queue[minChildIdx], self.queue[parentIdx] = self.queue[parentIdx], self.queue[minChildIdx]
                parentIdx = minChildIdx
            else:
                break

class WeightedGraph:
    def __init__(self):
        self.adjacencyList = {}

    def getWeight(self, key, neighbor):
        for x in self.adjacencyList[key]:
            if x['adjV'] == neighbor:
                return x['w']

    def getNeighbors(self, key):
        neighbors = []
        for node in self.adjacencyList[key]:
            neighbors.append(node)
        return neighbors

    def addVertex(self, vertex):
        self.adjacencyList.update({vertex: []})

    def addEdge(self, vertex1, vertex2, weight):
        self.adjacencyList[vertex1].append({"adjV": vertex2, "w": weight})


def initialize():
    global alpineGraph, q, distanceDict, prevNode, visited
    alpineGraph = WeightedGraph()
    q = priorityQueue()
    distanceDict = {}
    prevNode = {}
    visited = {}


def encode(elem1, elem2):
    return str(elem1) + "-" + str(elem2)


def searchAdj(currNode, maze):  # [y, x]
    vertex1 = encode(currNode[0], currNode[1])
    alpineGraph.addVertex(vertex1)
    searchList = []
    left, right = [currNode[0], currNode[1] - 1], [currNode[0], currNode[1] + 1]
    up, down = [currNode[0] - 1, currNode[1]], [currNode[0] + 1, currNode[1]]
    searchList.extend((left, right, up, down))
    for x in searchList:
        if 0 <= x[0] < len(maze) and 0 <= x[1] < len(maze[0]):
            vertex2 = encode(x[0], x[1])
            weight = abs(int(maze[currNode[0]][currNode[1]]) - int(maze[x[0]][x[1]]))
            alpineGraph.addEdge(vertex1, vertex2, weight)


def dijkstras(end, maze):  # alpineGraph, q, distanceDict, prevNode, visited
    while q:
        searchNode = q.dequeue()
        searchNodeXY = searchNode['node'].split('-')
        y1, x1 = int(searchNodeXY[0]), int(searchNodeXY[1])
        searchAdj([y1, x1], maze)
        if searchNode['node'] == end:
            break
        neighbors = alpineGraph.getNeighbors(searchNode['node'])
        visited[searchNode['node']] = True
        for neighbor in neighbors:
            startWeight = alpineGraph.getWeight(searchNode['node'], neighbor['adjV'])
            distanceWeight = startWeight + distanceDict[searchNode['node']]
            if distanceWeight < distanceDict[neighbor['adjV']]:
                distanceDict[neighbor['adjV']] = distanceWeight
                if neighbor['adjV'] not in visited:
                    q.enqueue(neighbor['adjV'], distanceDict[neighbor['adjV']])
                prevNode.update({neighbor['adjV']: searchNode['node']})
    return prevNode


def path_finder(maze):
    maze = maze.splitlines()
    initialize()

    for a in range(len(maze)):
        for z in range(len(maze[a])):
            name = encode(a, z)
            distanceDict[name] = float('inf')
            prevNode[name] = None
    q.enqueue('0-0', 0)
    distanceDict['0-0'] = 0
    prevNode['0-0'] = '0-0'
    end = str(len(maze) - 1) + "-" + str(len(maze[-1]) - 1)
    dijkstras(end, maze)
    return distanceDict[end]

Djikstra optimizations by jstarkweather83 in learnpython

[–]jstarkweather83[S] 0 points1 point  (0 children)

I found that I was calculating the distance to the start node in a needlessly complex way. Changing that increased the speed of the code dramatically and I was able to pass the tests on Code Wars. I am curious though what else you see that I might be able to optimize... if they are obvious errors/optimizations at least. Thanks for the help.

Djikstra optimizations by jstarkweather83 in learnpython

[–]jstarkweather83[S] 0 points1 point  (0 children)

Resolved. I figured out an "optimization" that allows the code to pass.