text:
Q: Dijkstra's algorithm in python I am trying to implement Dijkstra's algorithm in python using arrays. This is my implementation.
def extract(Q, w):
    m=0
    minimum=w[0]
    for i in range(len(w)):
        if w[i]<minimum:
            minimum=w[i]
            m=i
    return m, Q[m]

def dijkstra(G, s, t='B'):
    Q=[s]
    p={s:None}
    w=[0]
    d={}
    for i in G:
        d[i]=float('inf')
        Q.append(i)
        w.append(d[i])
    d[s]=0
    S=[]
    n=len(Q)
    while Q:
        u=extract(Q,w)[1]
        S.append(u)
        #w.remove(extract(Q, d, w)[0])
        Q.remove(u)
        for v in G[u]:
            if d[v]>=d[u]+G[u][v]:
                d[v]=d[u]+G[u][v]
                p[v]=u
    return d, p

B='B'
A='A'
D='D'
G='G'
E='E'
C='C'
F='F'
G={B:{A:5, D:1, G:2}, A:{B:5, D:3, E:12, F:5}, D:{B:1, G:1, E:1, A:3}, G:{B:2, D:1, C:2}, C:{G:2, E:1, F:16}, E:{A:12, D:1, C:1, F:2}, F:{A:5, E:2, C:16}}
print "Assuming the start vertex to be B:"
print "Shortest distances", dijkstra(G, B)[0]
print "Parents", dijkstra(G, B)[1]

I expect the answer to be:
Assuming the start vertex to be B:
Shortest distances {'A': 4, 'C': 4, 'B': 0, 'E': 2, 'D': 1, 'G': 2, 'F': 4}
Parents {'A': 'D', 'C': 'G', 'B': None, 'E': 'D', 'D': 'B', 'G': 'D', 'F': 'E'}

However, the answer that I get is this:
Assuming the start vertex to be B:
Shortest distances {'A': 4, 'C': 4, 'B': 0, 'E': 2, 'D': 1, 'G': 2, 'F': 10}
Parents {'A': 'D', 'C': 'G', 'B': None, 'E': 'D', 'D': 'B', 'G': 'D', 'F': 'A'}.

For the node F, the program gives the incorrect answer. Can someone please tell me why?

A: I needed a solution which would also return the path so I put together a simple class using ideas from multiple questions/answers about Dijkstra:
class Dijkstra:

    def __init__(self, vertices, graph):
        self.vertices = vertices  # ("A", "B", "C" ...)
        self.graph = graph  # {"A": {"B": 1}, "B": {"A": 3, "C": 5} ...}

    def find_route(self, start, end):
        unvisited = {n: float("inf") for n in self.vertices}
        unvisited[start] = 0  # set start vertex to 0
        visited = {}  # list of all visited nodes
        parents = {}  # predecessors
        while unvisited:
            min_vertex = min(unvisited, key=unvisited.get)  # get smallest distance
            for neighbour, _ in self.graph.get(min_vertex, {}).items():
                if neighbour in visited:
                    continue
                new_distance = unvisited[min_vertex] + self.graph[min_vertex].get(neighbour, float("inf"))
                if new_distance < unvisited[neighbour]:
                    unvisited[neighbour] = new_distance
                    parents[neighbour] = min_vertex
            visited[min_vertex] = unvisited[min_vertex]
            unvisited.pop(min_vertex)
            if min_vertex == end:
                break
        return parents, visited

    @staticmethod
    def generate_path(parents, start, end):
        path = [end]
        while True:
            key = parents[path[0]]
            path.insert(0, key)
            if key == start:
                break
        return path

Example graph and usage (drawing is generated using this nifty tool):

input_vertices = ("A", "B", "C", "D", "E", "F", "G")
input_graph = {
    "A": {"B": 5, "D": 3, "E": 12, "F": 5},
    "B": {"A": 5, "D": 1, "G": 2},
    "C": {"E": 1, "F": 16, "G": 2},
    "D": {"A": 3, "B": 1, "E": 1, "G": 1},
    "E": {"A": 12, "C": 1, "D": 1, "F": 2},
    "F": {"A": 5, "C": 16, "E": 2},
    "G": {"B": 2, "C": 2, "D": 1}
}
start_vertex = "B"
end_vertex= "C"
dijkstra = Dijkstra(input_vertices, input_graph)
p, v = dijkstra.find_route(start_vertex, end_vertex)
print("Distance from %s to %s is: %.2f" % (start_vertex, end_vertex, v[end_vertex]))
se = dijkstra.generate_path(p, start_vertex, end_vertex)
print("Path from %s to %s is: %s" % (start_vertex, end_vertex, " -> ".join(se)))

Output
Distance from B to C is: 3.00
Path from B to C is: B -> D -> E -> C

A: This is not my answer - my prof did it much more efficiently than my attempt.  Here is his approach, obviously using helper-functions for the repetitive tasks
def dijkstra(graph, source):

    vertices, edges = graph
    dist = dict()
    previous = dict()

    for vertex in vertices:
        dist[vertex] = float("inf")
        previous[vertex] = None

    dist[source] = 0
    Q = set(vertices)

    while len(Q) > 0:
        u = minimum_distance(dist, Q)
        print('Currently considering', u, 'with a distance of', dist[u])
        Q.remove(u)

        if dist[u] == float('inf'):
            break

        n = get_neighbours(graph, u)
        for vertex in n:
            alt = dist[u] + dist_between(graph, u, vertex)
            if alt < dist[vertex]:
                dist[vertex] = alt
                previous[vertex] = u

    return previous

Given a graph

({'A', 'B', 'C', 'D'}, {('A', 'B', 5), ('B', 'A', 5), ('B', 'C', 10), ('B', 'D', 6),  ('C', 'D', 2), ('D', 'C', 2)})

the command print(dijkstra(graph, 'A') yields

Currently considering A with a distance of 0
Currently considering B with a distance of 5
Currently considering D with a distance of 11
Currently considering C with a distance of 13

id est:

{'C': 'D', 'D': 'B', 'A': None, 'B': 'A'} => in random order

A: Implementation based on CLRS 2nd Ed. Chapter 24.3
d is deltas, p is predecessors
import heapq

def dijkstra(g, s, t):

    q = []
    d = {k: sys.maxint for k in g.keys()}
    p = {}

    d[s] = 0
    heapq.heappush(q, (0, s))

    while q:
        last_w, curr_v = heapq.heappop(q)
        for n, n_w in g[curr_v]:
            cand_w = last_w + n_w # equivalent to d[curr_v] + n_w
            # print d # uncomment to see how deltas are updated
            if cand_w < d[n]:
                d[n] = cand_w
                p[n] = curr_v
                heapq.heappush(q, (cand_w, n))

    print "predecessors: ", p
    print "delta: ", d
    return d[t]

def test():

    og = {}
    og["s"] = [("t", 10), ("y", 5)]
    og["t"] = [("y", 2), ("x", 1)]
    og["y"] = [("t", 3), ("x", 9), ("z", 2)]
    og["z"] = [("x", 6), ("s", 7)]
    og["x"] = [("z", 4)]

    assert dijkstra(og, "s", "x") == 9

if __name__ == "__main__":
    test()

Implementation assumes all nodes are represented as keys. If say node(e.g "x" in the example above) was not defined as a key in the og, deltas d would be missing that key and check if cand_w < d[n] wouldn't work correctly.

A: As others have pointed out, due to not using understandable variable names, it is almost impossible to debug your code.
Following the wiki article about Dijkstra's algorithm, one can implement it along these lines (and in a million other manners):
nodes = ('A', 'B', 'C', 'D', 'E', 'F', 'G')
distances = {
    'B': {'A': 5, 'D': 1, 'G': 2},
    'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5},
    'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3},
    'G': {'B': 2, 'D': 1, 'C': 2},
    'C': {'G': 2, 'E': 1, 'F': 16},
    'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2},
    'F': {'A': 5, 'E': 2, 'C': 16}}

unvisited = {node: None for node in nodes} #using None as +inf
visited = {}
current = 'B'
currentDistance = 0
unvisited[current] = currentDistance

while True:
    for neighbour, distance in distances[current].items():
        if neighbour not in unvisited: continue
        newDistance = currentDistance + distance
        if unvisited[neighbour] is None or unvisited[neighbour] > newDistance:
            unvisited[neighbour] = newDistance
    visited[current] = currentDistance
    del unvisited[current]
    if not unvisited: break
    candidates = [node for node in unvisited.items() if node[1]]
    current, currentDistance = sorted(candidates, key = lambda x: x[1])[0]

print(visited)

This code is more verbous than necessary and I hope comparing your code with mine you might spot some differences.
The result is:
{'E': 2, 'D': 1, 'G': 2, 'F': 4, 'A': 4, 'C': 3, 'B': 0}

A: This implementation use only array and heap ds.
import heapq as hq
import math

def dijkstra(G, s):
    n = len(G)
    visited = [False]*n
    weights = [math.inf]*n
    path = [None]*n
    queue = []
    weights[s] = 0
    hq.heappush(queue, (0, s))
    while len(queue) > 0:
        g, u = hq.heappop(queue)
        visited[u] = True
        for v, w in G[u]:
            if not visited[v]:
                f = g + w
                if f < weights[v]:
                    weights[v] = f
                    path[v] = u
                    hq.heappush(queue, (f, v))
    return path, weights

G = [[(1, 6), (3, 7)],
     [(2, 5), (3, 8), (4, -4)],
     [(1, -2), (4, 7)],
     [(2, -3), (4, 9)],
     [(0, 2)]]

print(dijkstra(G, 0))

I hope this could help someone, it's a little bit late.

A: I wrote it in a more verbose form to make it clearer for a novice reader:
def get_parent(pos):
    return (pos + 1) // 2 - 1

def get_children(pos):
    right = (pos + 1) * 2
    left = right - 1
    return left, right

def swap(array, a, b):
    array[a], array[b] = array[b], array[a]

class Heap:

    def __init__(self):
        self._array = []

    def peek(self):
        return self._array[0] if self._array else None

    def _get_smallest_child(self, parent):
        return min([
            it
            for it in get_children(parent)
            if it < len(self._array)
        ], key=lambda it: self._array[it], default=-1)

    def _sift_down(self):
        parent = 0
        smallest = self._get_smallest_child(parent)
        while smallest != -1 and self._array[smallest] < self._array[parent]:
            swap(self._array, smallest, parent)
            parent, smallest = smallest, self._get_smallest_child(smallest)

    def pop(self):
        if not self._array:
            return None
        swap(self._array, 0, len(self._array) - 1)
        node = self._array.pop()
        self._sift_down()
        return node

    def _sift_up(self):
        index = len(self._array) - 1
        parent = get_parent(index)
        while parent != -1 and self._array[index] < self._array[parent]:
            swap(self._array, index, parent)
            index, parent = parent, get_parent(parent)

    def add(self, item):
        self._array.append(item)
        self._sift_up()

    def __bool__(self):
        return bool(self._array)

def backtrack(best_parents, start, end):
    if end not in best_parents:
        return None
    cursor = end
    path = [cursor]
    while cursor in best_parents:
        cursor = best_parents[cursor]
        path.append(cursor)
        if cursor == start:
            return list(reversed(path))
    return None

def dijkstra(weighted_graph, start, end):
    """
    Calculate the shortest path for a directed weighted graph.

    Node can be virtually any hashable datatype.

    :param start: starting node
    :param end: ending node
    :param weighted_graph: {"node1": {"node2": weight, ...}, ...}
    :return: ["START", ... nodes between ..., "END"] or None, if there is no
            path
    """
    distances = {i: float("inf") for i in weighted_graph}
    best_parents = {i: None for i in weighted_graph}

    to_visit = Heap()
    to_visit.add((0, start))
    distances[start] = 0

    visited = set()

    while to_visit:
        src_distance, source = to_visit.pop()
        if src_distance > distances[source]:
            continue
        if source == end:
            break
        visited.add(source)
        for target, distance in weighted_graph[source].items():
            if target in visited:
                continue
            new_dist = distances[source] + weighted_graph[source][target]
            if distances[target] > new_dist:
                distances[target] = new_dist
                best_parents[target] = source
                to_visit.add((new_dist, target))

    return backtrack(best_parents, start, end)

A: I broke down the wikipedia description into the following pseudo-code on my blog rebrained.com:
Initial state:

*

*give nodes two properties - node.visited and node.distance

*set node.distance = infinity for all nodes except set start node to zero

*set node.visited = false for all nodes

*set current node = start node.

Current node loop:

*

*if current node = end node, finish and return current.distance & path

*for all unvisited neighbors, calc their tentative distance (current.distance + edge to neighbor).

*if tentative distance < neighbor's set distance, overwrite it.

*set current.isvisited = true.

*set current = remaining unvisited node with smallest node.distance

http://rebrained.com/?p=392
import sys
def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
    """Find the shortest path btw start & end nodes in a graph"""
    # detect if first time through, set current distance to zero
    if not visited: distances[start]=0
    # if we've found our end node, find the path to it, and return
    if start==end:
        path=[]
        while end != None:
            path.append(end)
            end=predecessors.get(end,None)
        return distances[start], path[::-1]
    # process neighbors as per algorithm, keep track of predecessors
    for neighbor in graph[start]:
        if neighbor not in visited:
            neighbordist = distances.get(neighbor,sys.maxint)
            tentativedist = distances[start] + graph[start][neighbor]
            if tentativedist < neighbordist:
                distances[neighbor] = tentativedist
                predecessors[neighbor]=start
    # neighbors processed, now mark the current node as visited
    visited.append(start)
    # finds the closest unvisited node to the start
    unvisiteds = dict((k, distances.get(k,sys.maxint)) for k in graph if k not in visited)
    closestnode = min(unvisiteds, key=unvisiteds.get)
    # now take the closest node and recurse, making it current
    return shortestpath(graph,closestnode,end,visited,distances,predecessors)
if __name__ == "__main__":
    graph = {'a': {'w': 14, 'x': 7, 'y': 9},
            'b': {'w': 9, 'z': 6},
            'w': {'a': 14, 'b': 9, 'y': 2},
            'x': {'a': 7, 'y': 10, 'z': 15},
            'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
            'z': {'b': 6, 'x': 15, 'y': 11}}
    print shortestpath(graph,'a','a')
    print shortestpath(graph,'a','b')
    """
    Expected Result:
        (0, ['a'])
        (20, ['a', 'y', 'w', 'b'])
        """

A: This started out as a small rewrite of Carlos' answer, but I ended up changing it quite a lot.
The class its constructer should be passed the graph. This makes it so the get_shortest_path() method can be called many times with different starting and ending arguments, without having to pass the graph every time.
The asserts showcase how the class should be used with a cyclic or acyclic graph.
I personally don't need the weight of the shortest path, so I don't let the get_shortest_path() method return that, but distances[node] can be added to the return statement of the method if it is desired.
import heapq

def main():
    showcase_cyclic()
    showcase_acyclic()

def showcase_cyclic():
    cyclic_graph = {
        "a": { "w": 14, "x": 7, "y": 9 },
        "b": { "w": 9, "z": 6 },
        "w": { "a": 14, "b": 9, "y": 2 },
        "x": { "a": 7, "y": 10, "z": 15 },
        "y": { "a": 9, "w": 2, "x": 10, "z": 11 },
        "z": { "b": 6, "x": 15, "y": 11 }
    }

    dijkstra = Dijkstra(cyclic_graph)

    assert dijkstra.get_shortest_path("a", "a") == ['a']
    assert dijkstra.get_shortest_path("a", "b") == ['a', 'y', 'w', 'b']

def showcase_acyclic():
    acyclic_graph = {
        "a": { "b": 1, "c": 2 },
        "b": { "d": 3 },
        "c": { "d": 4 },
        "d": { "e": 5 },
        "e": {}
    }

    dijkstra = Dijkstra(acyclic_graph)

    assert dijkstra.get_shortest_path("a", "a") == ['a']
    assert dijkstra.get_shortest_path("a", "e") == ['a', 'b', 'd', 'e']

class Dijkstra:
    def __init__(self, graph):
        self.graph = graph

    def get_shortest_path(self, start, end):
        distances = { key: float("inf") for key in self.graph.keys() }
        distances[start] = 0

        unvisited = { key for key in self.graph.keys() }

        parents = {}

        node = start

        while node != end:
            unvisited.remove(node)

            for neighbor in self.graph[node].keys():
                if neighbor in unvisited:
                    tentative_distance = distances[node] + self.graph[node][neighbor]
                    recorded_distance = distances[neighbor]

                    if tentative_distance < recorded_distance:
                        distances[neighbor] = tentative_distance
                        parents[neighbor] = node

            node = self.get_closest_node(unvisited, distances)

        return self.get_path(end, parents)

    def get_closest_node(self, unvisited, distances):
        unvisited_min_heap = [(distances[node], node) for node in unvisited]

        # Great explanation of heapify: https://stackoverflow.com/a/61446534/13279557
        heapq.heapify(unvisited_min_heap)

        _, closest_node = heapq.heappop(unvisited_min_heap)

        return closest_node

    def get_path(self, end, parents):
        path = []

        while True:
            path.append(end)

            if end not in parents:
                return list(reversed(path))

            end = parents[end]

if __name__ == "__main__":
    main()

A: Using heapq module to implement priority queue, you can do:
from collections import defaultdict
import heapq

graph = {
    'A': [('B', 2), ('C', 1)],
    'B': [('A', 2), ('C', 4), ('D', 3)],
    'C': [('A', 1), ('B', 4), ('E', 2)],
    'E': [('C', 2), ('D', 1), ('F', 4)],
    'D': [('B', 3), ('E', 1), ('F', 2)],
    'F': [('D', 2), ('E', 4)]

}

def dijkstra(graph, start: str):
    result_map = defaultdict(lambda: float('inf'))
    result_map[start] = 0

    visited = set()

    queue = [(0, start)]

    while queue:
        weight, v = heapq.heappop(queue)
        visited.add(v)

        for u, w in graph[v]:
            if u not in visited:
                result_map[u] = min(w + weight, result_map[u])
                heapq.heappush(queue, [w + weight, u])

    return result_map

print(dijkstra(graph, 'A'))

Output:
{'A': 0, 'B': 2, 'C': 1, 'E': 3, 'D': 4, 'F': 6}

A: Set a breakpoint in extract. You will see that you delete entries from Q but never from w. Everything else is a dict, but Q/w are a paired array which you do not keep up to date. You have to keep those two in sync, or replace them with a dict. Special note: Eventually, after the algorithm is working, you may want to replace Q/w with a list of edges and re-code the "extract" function with a priority queue (heapq module).
Additionally, you will see that w always has weights of 0 for the source, and 'inf' for all other nodes. You completely skipped the critical step where you update the candidate distances.
So you are basically always taking the first path you encounter, rather than selecting the shortest path. You later compute the actual distance of that path, so the returned array of distances has actual values, but they were chosen arbitrarily, and you have no reason to expect them to be shortest.
After you (incorrectly) find the next node, you look at all of its edges. This should have been the critical step I mentioned above in the second paragraph, where you update the candidates for the next node. Instead you do something completely different: You appear to be looping through all the previous solutions (which are guaranteed correct and should be left alone, if you correctly implement dijkstra), and you look for a two-step solution from source->current->any. The correct intent for looking at those would have been to add the next candidate from previous paths to the next node, but because they never get added, you don't look at (previous shortest path) + (one step), you only look at literally two node solutions.
So basically, you are looping through all possible two-node paths from source in order to find the shortest paths. This is a complete error and has nothing to do with dijkstra. But it almost works on your tiny tiny graph where most of the correct shortest paths are two-step paths.
(ps: I agree with everyone about your variable names. You would have done much better if you use verbose names telling what those variables represent. I had to rename them before I got anywhere analyzing your code.)

A: import sys
import heapq

class Node:

     def __init__(self, name):
        self.name = name
        self.visited = False
        self.adjacenciesList = []
        self.predecessor = None
        self.mindistance = sys.maxsize

    def __lt__(self, other):
        return self.mindistance < other.mindistance

class Edge:

    def __init__(self, weight, startvertex, endvertex):
        self.weight = weight
        self.startvertex = startvertex
        self.endvertex = endvertex

def calculateshortestpath(vertexlist, startvertex):
    q = []
    startvertex.mindistance = 0
    heapq.heappush(q, startvertex)

    while q:
        actualnode = heapq.heappop(q)
        for edge in actualnode.adjacenciesList:
            tempdist = edge.startvertex.mindistance + edge.weight
            if tempdist < edge.endvertex.mindistance:
                edge.endvertex.mindistance = tempdist
                edge.endvertex.predecessor = edge.startvertex
                heapq.heappush(q,edge.endvertex)
def getshortestpath(targetvertex):
    print("The value of it's minimum distance is: ",targetvertex.mindistance)
    node = targetvertex
    while node:
        print(node.name)
        node = node.predecessor

node1 = Node("A");
node2 = Node("B");
node3 = Node("C");
node4 = Node("D");
node5 = Node("E");
node6 = Node("F");
node7 = Node("G");
node8 = Node("H");

edge1 = Edge(5,node1,node2);
edge2 = Edge(8,node1,node8);
edge3 = Edge(9,node1,node5);
edge4 = Edge(15,node2,node4);
edge5 = Edge(12,node2,node3);
edge6 = Edge(4,node2,node8);
edge7 = Edge(7,node8,node3);
edge8 = Edge(6,node8,node6);
edge9 = Edge(5,node5,node8);
edge10 = Edge(4,node5,node6);
edge11 = Edge(20,node5,node7);
edge12 = Edge(1,node6,node3);
edge13 = Edge(13,node6,node7);
edge14 = Edge(3,node3,node4);
edge15 = Edge(11,node3,node7);
edge16 = Edge(9,node4,node7);

node1.adjacenciesList.append(edge1);
node1.adjacenciesList.append(edge2);
node1.adjacenciesList.append(edge3);
node2.adjacenciesList.append(edge4);
node2.adjacenciesList.append(edge5);
node2.adjacenciesList.append(edge6);
node8.adjacenciesList.append(edge7);
node8.adjacenciesList.append(edge8);
node5.adjacenciesList.append(edge9);
node5.adjacenciesList.append(edge10);
node5.adjacenciesList.append(edge11);
node6.adjacenciesList.append(edge12);
node6.adjacenciesList.append(edge13);
node3.adjacenciesList.append(edge14);
node3.adjacenciesList.append(edge15);
node4.adjacenciesList.append(edge16);

vertexlist = (node1,node2,node3,node4,node5,node6,node7,node8)

calculateshortestpath(vertexlist,node1)
getshortestpath(node7)

A: Here is my implementation of Dijkstra algorithm using min-priority-queue. Hope it will you.
from collections import defaultdict
from math import floor

class MinPQ:
    """
    each heap element is in form (key value, object handle), while heap
    operations works based on comparing key value and object handle points to
    the corresponding application object.
    """

    def __init__(self, array=[]):
        self._minheap = list(array)
        self._length = len(array)
        self._heapsize = 0
        self._build_min_heap()

    def _left(self, idx):
        return 2*idx+1

    def _right(self, idx):
        return 2*idx+2

    def _parent(self, idx):
        return floor((idx-1)/2)

    def _min_heapify(self, idx):
        left = self._left(idx)
        right = self._right(idx)
        min_idx = idx
        if left <= self._heapsize-1 and self._minheap[left] < self._minheap[min_idx]:
            min_idx = left
        if right <= self._heapsize-1 and self._minheap[right] < self._minheap[min_idx]:
            min_idx = right
        if min_idx != idx:
            self._minheap[idx], self._minheap[min_idx] = self._minheap[min_idx], self._minheap[idx]
            self._min_heapify(min_idx)

    def _build_min_heap(self):
        self._heapsize = self._length
        mid_id = int(self._heapsize-1)-1
        for i in range(mid_id, -1, -1):
            self._min_heapify(i)

    def decrease_key(self, idx, new_key):
        while idx > 0 and new_key < self._minheap[self._parent(idx)]:
            self._minheap[idx] = self._minheap[self._parent(idx)]
            idx = self._parent(idx)
        self._minheap[idx] = new_key

    def extract_min(self):
        minimum = self._minheap[0]
        self._minheap[0] = self._minheap[self._heapsize-1]
        self._heapsize = self._heapsize - 1
        self._min_heapify(0)
        return minimum

    def insert(self, item):
        self._minheap.append(item)
        self._heapsize = self._heapsize + 1
        self.decrease_key(self._heapsize-1, item)

    @property
    def minimum(self):
        return self._minheap[0]

    def is_empty(self):
        return self._heapsize == 0

    def __str__(self):
        return str(self._minheap)

    __repr__ = __str__

    def __len__(self):
        return self._heapsize

class DiGraph:
    def __init__(self, edges=None):
        self.adj_list = defaultdict(list)
        self.add_weighted_edges(edges)

    @property
    def nodes(self):
        nodes = set()
        nodes.update(self.adj_list.keys())
        for node in self.adj_list.keys():
            for neighbor, weight in self.adj_list[node]:
                nodes.add(neighbor)
        return list(nodes)

    def add_weighted_edges(self, edges):
        if edges is None:
            return None
        for edge in edges:
            self.add_weighted_edge(edge)

    def add_weighted_edge(self, edge):
        node1, node2, weight = edge
        self.adj_list[node1].append((node2, weight))

    def weight(self, tail, head):
        for node, weight in self.adj_list[tail]:
            if node == head:
                return weight
        return None

def relax(min_heapq, dist, graph, u, v):
    if dist[v] > dist[u] + graph.weight(u, v):
        dist[v] = dist[u] + graph.weight(u, v)
        min_heapq.insert((dist[v], v))

def dijkstra(graph, start):
    # initialize
    dist = dict.fromkeys(graph.nodes, float('inf'))
    dist[start] = 0
    min_heapq = MinPQ()
    min_heapq.insert((0, start))

    while not min_heapq.is_empty():
        distance, u = min_heapq.extract_min()
        # we may add a node multiple time in priority queue, but we process it
        # only once
        if distance > dist[u]:
            continue
        for neighbor, weight in graph.adj_list[u]:
            relax(min_heapq, dist, graph, u, neighbor)

    return dist

if __name__ == "__main__":
    edges = [('s', 't', 10), ('t', 'x', 1), ('s', 'y', 5), ('y', 't', 3), ('t', 'y', 2),
             ('y', 'x', 9), ('y', 'z', 2), ('z', 's', 7), ('x', 'z', 4), ('z', 'x', 6)]
    digraph = DiGraph(edges)
    res = dijkstra(digraph, 's')
    print(res)

A: I implement Dijkstra using priority-queue. Apart from that, I also implement min-heap myself. Hope this will help you.
from collections import defaultdict

class MinPQ:
    """
    each heap element is in form (key value, object handle), while heap
    operations works based on comparing key value and object handle points to
    the corresponding application object.
    """

    def __init__(self, array=[]):
        self._minheap = list(array)
        self._length = len(array)
        self._heapsize = 0
        self._build_min_heap()

    def _left(self, idx):
        return 2*idx+1

    def _right(self, idx):
        return 2*idx+2

    def _parent(self, idx):
        return int((idx-1)/2)

    def _min_heapify(self, idx):
        left = self._left(idx)
        right = self._right(idx)
        min_idx = idx
        if left <= self._heapsize-1 and self._minheap[left] < self._minheap[min_idx]:
            min_idx = left
        if right <= self._heapsize-1 and self._minheap[right] < self._minheap[min_idx]:
            min_idx = right
        if min_idx != idx:
            self._minheap[idx], self._minheap[min_idx] = self._minheap[min_idx], self._minheap[idx]
            self._min_heapify(min_idx)

    def _build_min_heap(self):
        self._heapsize = self._length
        mid_id = int((self._heapsize)/2)-1
        for i in range(mid_id, -1, -1):
            self._min_heapify(i)

    def decrease_key(self, idx, new_key):
        while idx > 0 and new_key < self._minheap[self._parent(idx)]:
            self._minheap[idx] = self._minheap[self._parent(idx)]
            idx = self._parent(idx)
        self._minheap[idx] = new_key

    def extract_min(self):
        if self._heapsize < 1:
            raise IndexError
        minimum = self._minheap[0]
        self._minheap[0] = self._minheap[self._heapsize-1]
        self._heapsize = self._heapsize - 1
        self._min_heapify(0)
        return minimum

    def insert(self, item):
        self._minheap.append(item)
        self._heapsize = self._heapsize + 1
        self.decrease_key(self._heapsize-1, item)

    @property
    def minimum(self):
        return self._minheap[0]

    def is_empty(self):
        return self._heapsize == 0

    def __str__(self):
        return str(self._minheap)

    __repr__ = __str__

    def __len__(self):
        return self._heapsize

class DiGraph:
    def __init__(self, edges=None):
        self.adj_list = defaultdict(list)
        self.add_weighted_edges(edges)

    @property
    def nodes(self):
        nodes = set()
        nodes.update(self.adj_list.keys())
        for node in self.adj_list.keys():
            for neighbor, weight in self.adj_list[node]:
                nodes.add(neighbor)
        return list(nodes)

    def add_weighted_edges(self, edges):
        if edges is None:
            return None
        for edge in edges:
            self.add_weighted_edge(edge)

    def add_weighted_edge(self, edge):
        node1, node2, weight = edge
        self.adj_list[node1].append((node2, weight))

    def weight(self, tail, head):
        for node, weight in self.adj_list[tail]:
            if node == head:
                return weight
        return None

def relax(min_heapq, dist, graph, u, v):
    if dist[v] > dist[u] + graph.weight(u, v):
        dist[v] = dist[u] + graph.weight(u, v)
        min_heapq.insert((dist[v], v))

def dijkstra(graph, start):
    # initialize
    dist = dict.fromkeys(graph.nodes, float('inf'))
    dist[start] = 0
    min_heapq = MinPQ()
    min_heapq.insert((0, start))

    while not min_heapq.is_empty():
        distance, u = min_heapq.extract_min()
        # we may add a node multiple time in priority queue, but we process it
        # only once
        if distance > dist[u]:
            continue
        for neighbor, weight in graph.adj_list[u]:
            relax(min_heapq, dist, graph, u, neighbor)

    return dist


text:
Q: How to refer environment varibales in MySQL configuration file Is there a way to use environment variables in my.cnf?
Ideally, I'd like to do something like
[client]
user = $MYSQL_USER
password = $MYSQL_PASSWORD
host = db

But, with the configuration above, when I try to connect to MySQL, I get

ERROR 1045 (28000): Access denied for user '$MYSQL_USER'@'188.1.1.5'
(using password: YES)

A: This is not possible. MySQL does not support variables in the configuration file.
If you want to ease deployment you should look into configuration management.

A: See mysql_config_editor as a convenient way to both establish your credentials and make them reasonably secure.
Since it is a one-time setup, you don't even need the $variables after that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python - Using the "except" after "try", as an "else" part for "try" I'm trying to understand (and could not find a definitive answer), whether it's considered good practice to use the "except" part of try-except, as a sort of "else" part.
EDIT - in order to try and be more clear:
Let's say I have 2 variables to test and I only "need" one of them as the answer (like if-else). Each of them would raise an exception if it fails. I try the first and it failed. Is it good practice to use the "except" section to continue the code with the second variable and set it as the chosen one, or should I only use the "except" part to handle the exception, and then do some other code (outside the "except" scope) to also test the second one?

Original:
That is - to write some code to the except, which is more then just a small except handle or print. More like a block of a few lines of code that would only happen if an the except is thrown, similar to an "else" statement. That is, in contrary to using the except just as a part to specifically handle the thrown exception and it's consequences.
Example -
try: perform-this-thing...

     perform-some-code

except:
     exception-raised-so-do-this-code...
     code
     code
     code

If that's not considered good practice - what is a more correct way to do what I seek?
Thank you all.

A: Exception handling is the process of responding to programming errors which disrupt the normal flow of program execution. The emphasis should be here on "disrupt the normal flow".
Use an exception handler to recover from such a programming error but don't mask real programming errors. Especially be careful with a wildcard exception handler and use it with extreme caution.
I'd argue that testing two variables and continuing with one of them if it is set is normal business logic and should be covered in an if-else statement as this is your normal flow.
If you can do this test only with a test for an exception then I'd say you can wrap the individual variable tests in a try-except and if unavoidable use nested exception handling but I'd advise against nested exception handling as it makes the code ugly and unmaintainable (nested would be here testing for the second variable in the except of the first).
Then if none of them is set that would cause an exception as this would disrupt the normal flow.
try:
    # Try to obtain variable 1
except ErrorObtainingVariable1
    # Log...
try:
    # Try to obtain variable 2
except ErrorObtainingVariable2
    # Log...
# Check to use variable 1 or 2
# If none set raise exception

(PS: There's also an optional else part of a try-except which follows all except clauses and is executed if no exception is raised. You could use this to avoid obtaining the second variable if obtaining the first variable was successful. See the Python documentation for more information.)

A: I would prefer to use the following approach to prevent indentation hell:
# create an auxiliary function to choose the valid variable
def choose_variable(*vars):
    default_value = -1 # you can change it or remove it if you the default return value is None
    for v in vars:
        try:
            # check your var here
            return v
        except:
            continue
    return default_value

and then use it in your code:
chosen_value = choose_variable(v1,v2,v3)
print(f"The chosen value is {chosen_value}")

A: In my opinion, these two forms of use of the try-except block are exactly the same if the use case is very simple. Something like this:
try:

    var1 = var + 1
    print(var1)

except:

    print(var)

    try:

        var1 = var + float(1)
        print(var1)

    except:

        print(var)

print('\n')

This version is equivalent to the first version of the try-except block
try:
    var1 = var + 1
    print(var1)

except:

    print(var)

try:

    var1 = var + float(1)
    print(var1)

except:

    print(var)

print('\n')

But depending on the effect that you're trying to achieve, the code can look differently, and have different results. Like this:
try:
    var1 = var + '1'
    print(var1)

except:

    print(var)

try:

    var1 = var + float(1)
    print(var1)

except:

    print(var)

print('\n')

This third version will have a different result than the second version.
Another way to write the code would be this, which is simplified.

try:
    var1 = var + '1'
    print(var1)

except:

    try:

        var1 = var + float(1)
        print(var1)

    except:

        print(var)

And this version is not the same as the first version of the try-except block.
When the code is executed, there will be different results.
15
15

15
15

151
15

151

Try-except blocks can become very complex and you have to choose the best version for your specific use case.


text:
Q: Print data of a clicked row from tableView model there is the dialog:
class classsearchresult(QDialog, Ui_Dialog):
def __init__(self, parent=None):
    QDialog.__init__(self, parent)
    self.setupUi(self)
    self.tableView.setShowGrid(False)
    self.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
    vh = self.tableView.verticalHeader()
    vh.setVisible(False)
    hh = self.tableView.horizontalHeader()
    hh.setVisible(False)
    hh.setStretchLastSection(True)
    self.pushButton_2.clicked.connect(self.close)
    db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('formuladatabase')
    db.open()
    self.projectModel = QtSql.QSqlQueryModel(self)
    self.projectModel.setQuery("select rowid, Name, Surname from search",db)
    self.tableView.setModel(self.projectModel)
    self.tableView.clicked.connect(self.handlebutton)

tableview works great just need to print that clicked row
def handlebutton(self):
    rows = self.tableView.selectionModel().selectedIndexes()
    print(self.projectModel.record(rows[0].row()).value("rowid").toInt())
    self.newwindow = classformularesult(self)
    self.newwindow.show()

been trying for a while but cant figure this one out.

A: Just a  note: I noticed you tagged PyQt5, but the docs aren't so good there, and I'm pretty confident all I'm stating here still applies (from PyQt4).
It appears as though you're assuming that rows is going to contain the data from your query, which it does not.  selectedRows(),selectedColumns,selectedIndexes() (documented here: http://pyqt.sourceforge.net/Docs/PyQt4/qitemselectionmodel.html#selectedRows) all return type list-of-QModelIndex, which are basically indexes.. not data.

list-of-QModelIndex QItemSelectionModel.selectedRows (self, int column
  = 0)
Returns the indexes in the given column for the rows where all columns
  are selected.

I think it's easier to use selectedIndexes

list-of-QModelIndex QItemSelectionModel.selectedIndexes (self)
Returns a list of all selected model item indexes. The list contains
  no duplicates, and is not sorted.

To get the data, model.record.value() returns a QVariant, to which you have to cast to the proper type for printing.  So, in your case:
rows = self.tableView.selectionModel().selectedIndexes()
print self.projectModel.record(rows[0].row()).value("rowid").toInt()
print self.projectModel.record(rows[0].row()).value("Name").toString()
print self.projectModel.record(rows[0].row()).value("Surname").toString()

The rows[0].row() is accessing element 0 of the "list-of-QModelIndex" type that's returned, and QModelIndex (http://pyqt.sourceforge.net/Docs/PyQt4/qmodelindex.html#details) has a row() method which returns the index of the row. Given the way you've set it up, the "list-of-QModelIndex" list should always be a single element list (you wired it up with the "clicked" signal), so the row[0] should return the proper element.
See here for additional information:
http://ftp.ics.uci.edu/pub/centos0/ics-custom-build/BUILD/PyQt-x11-gpl-4.7.2/doc/html/qtsql.html
About half way down there's a "Using the SQL Model Classes" heading with some good examples.

A: for the record and other in my situation the answers was
def handlebutton(self):
    rows = self.tableView.selectionModel().selectedIndexes()
    print(self.projectModel.record(rows[0].row()).value("rowid"))
    self.newwindow = classformularesult(self)
    self.newwindow.show()

thank you SEGFAULTCODER


text:
Q: Is the covariance matrix of multivariate normal distribution has to be positive definite? Let $\Sigma $ be the covariance matrix of a multivariate normal
distribution.
Thereotically, I guess it does not have to to strictly positive definition,
i.e., $\det (\Sigma )=0$ is possible.
In this case, the density function does not exist, how can I generate random
numbers(vectors) from such multivariate normal distribution?

A: A multivariate normal distribution has the density function:
$$f(X) = \frac{1}{\sqrt{(2\pi)^n |\Sigma|}} \exp\{\frac{-1}{2}X \Sigma^{-1} X^T\}$$
and the covariance should be positive definite.
So if you need multivariate normal samples you've got to generate them using a valid (meaning symmetric positive definite) covariance matrix.
But then, when you generated the random vectors, the calculated sample covariance can be not positive definite. As an example, consider a covariance matrix of rank 10. If you generate less than 10 sample vectors (i.e. 1 to 9 samples), and calculate their sample covariance, the calculated covariance matrix is not full rank, and its determinant becomes 0, although the generative model has a valid positive definite covariance.

A: This is one possible approach. Suppose that $X\sim N(0,\Sigma)$. We have that
$$
\Sigma=Q\Lambda Q^{\mathrm T},
$$
where $Q$ is an orthogonal matrix with the eigenvectors of $\Sigma$ as its columns and $\Lambda$ is a diagonal matrix with the eigenvalues of $\Sigma$ on its diagonal (this is the eigendecomposition or the spectral decomposition of $\Sigma$). Generate $Z\sim N(0,I)$. Then $Q\Lambda^{1/2}Z\sim N(0,\Sigma)$, where $\Lambda^{1/2}$ is the square root of $\Lambda$ obtained by taking the square roots of the eigenvalues on the diagonal. Indeed,
$$
\operatorname E[(Q\Lambda^{1/2}Z)(Q\Lambda^{1/2}Z)^{\mathrm T}]
=\operatorname E[Q\Lambda^{1/2}ZZ^{\mathrm T}\Lambda^{1/2}Q^{\mathrm T}]
=Q\Lambda^{1/2}I\Lambda^{1/2}Q^{\mathrm T}
=Q\Lambda Q^{\mathrm T}=\Sigma.
$$
The eigendecomposition of $\Sigma$ can by obtained using the $\texttt{eigen}()$ function in $\texttt R$.
I hope this is helpful.


text:
Q: Django admin: how to format readonly fields? I have a model, Director with two DateFields, and two subclasses (code below). I am trying to create an admin page for each Director which shows the corresponding subclass instance, and not the Director instance; this part is mostly easy (I create an inline for each subclass, give the main ModelAdmin a form with all fields excluded, and have the main ModelAdmin only request formsets from the inlines which have a corresponding instance - the code; there is an unresolved issue with this approach, which I note below, but is not the focus of this question).
The problem I have is that I want to massage the values displayed to the user, one of which is shown in a readonly field, one of which is not. The processing is that I want to change a magic value (date(1,1,1)) to the string "On incorporation".
Dates in readonly fields aren't rendered in a format very friendly to parsing, and I would like to reduce unnecessary dependence on javascript, so I would very much prefer a server-side solution.
The code below displays the forms as I want them, except that date values are not massaged at all, and when saving, there is a spurious "Please correct the error below" message, even though there are no errors, and all fields are saved correctly.
My question is: how do I intercept the values to be rendered on the page, both in readonly fields, and in forms fields, and alter them to display a string of my choosing?
The models (so far as material):
class Director(models.Model, Specializable):
    date_of_appointment = models.DateField()
    date_ceased_to_act = models.DateField(blank=True,null=True)

class DirectorsIndividual(Director):
     pass

class DirectorsCorporate(Director):
     pass

The admin code:
class DirectorAdmin(EnhancedAdmin):

    fields = ()

##    def formfield_for_dbfield(self, db_field, **kwargs):
##        return None

    def queryset(self, request):
        """ Directors for all companies which are incorporated by the current user's organisation """
        individual = Individual.for_user(request.user)
        return Director.objects.filter(company__incorporation_ticket__ordered_by__in = Organisation.all_organisations_for_which_individual_authorised_to_incorporate(individual))

    class form(forms.ModelForm):
        # have this return no html - that way only inlines are shown
        class Meta:
            fields = ()
            pass

        def is_valid(self):
            self._errors = {}
            return True

    class DirectorsIndividualInline(admin.StackedInline):
        model = DirectorsIndividual
        fk_name = 'director_ptr'
        extra = 0
        readonly_fields = ('deferred_on','company','date_of_appointment',)
        can_delete = False

        def get_readonly_fields(self, request, obj=None):
            if obj and obj.company and not obj.company.is_submitted(): return self.readonly_fields # allow editing of fields listed in else
            else:
                return itertools.chain(self.readonly_fields, ('individual', 'is_secretary'))

        def has_delete_permission(self, request, obj=None):
            return obj and ((obj.company and not obj.company.is_submitted()) or not obj.company)

        class form(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                super(forms.ModelForm, self).__init__(*args, **kwargs)
                self.fields['surrogate_for'].required = False
                self.fields['representative_for'].required = False
                if self.instance:
                    obj = self.instance
                    for field in (f for f in type(obj)._meta.fields if type(f) == fields.DateField):
                        val = field.value_from_object(obj)
                        assert (type(val) in (datetime.date, type(None),))
                        # assert field.name != 'date_of_appointment'
                        if val == inc_consts.EARLIEST_DATE:
                            self.initial[field.name] = "On incorporation"

            def is_valid(self):
                self._errors = {}
                return True

    class DirectorsCorporateInline(admin.StackedInline):

        model = DirectorsCorporate
        fk_name = 'director_ptr'
        extra = 0
        can_delete = False

        class form(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                super(forms.ModelForm, self).__init__(*args, **kwargs)
                if True:
                    for k in self.fields:
                        self.fields[k].required = False

            def is_valid(self):
                self._errors = {}
                return True

    inlines = (DirectorsIndividualInline,DirectorsCorporateInline)

    def get_inlines(self, request, obj=None):
        return (inline for inline in (self.inline_instances)
                if inline.model.objects.filter(**{(inline.fk_name or self.model._meta.object_name.lower()) : obj }))

    def get_formsets(self, request, obj=None):
        """ only return formset for inlines for which there exists an object """
        return (inline.get_formset(request, obj) for inline in self.get_inlines(request, obj))

I realise that there is an asymmetry between DirectorsCorporateInline and DirectorsIndividualInline; that is because I am testing on an instance with a DirectorsIndividual instance. The code above refers to model fields not shown in the models, because they are not material to the dates issue; it should be possible to render them immaterial for the spurious error issue without altering those fields (although I realise it is less helpful for that issue, I want to keep this question mostly focused on one issue). EnhancedAdmin is a ModelAdmin subclass with some minor alterations which shouldn't be of consequence. Extra code can be shown on reasoned request, but I don't want to confuse with irrelevant code.
For completeness: I am using django 1.3.1 on python 2.7.2.

A: The easiest way is to do it by defining a custom callback in the ModelAdmin.  Let's say the field is called my_datetime:
from django.contrib import admin
from django.utils.formats import localize

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ('my_datetime_localized',)

    def my_datetime_localized(self, obj):
        return localize(obj.my_datetime)
    my_datetime_localized.short_description = 'Date / time'

Note: if settings.USE_L10N is True, this will display the datetime in the local time of the viewer, which is probably what you want.  If you want to keep USE_L10N as False then you can override its behaviour like so: return localize(obj.my_datetime, use_l10n=True).

A: Define a member function of your Director class that renders the readonly_field as you want.
class Director(models.Model, Specializable):
    date_of_appointment = models.DateField()
    date_ceased_to_act = models.DateField(blank=True,null=True)
    def date_of_appointment_str(self):
        if self.date_of_appointment == datetime.date(1,1,1):
            return "On incorporation"
        else:
            return "%s" % (self.date_of_appointment) # format as you wish

and then just add 'date_of_appointment_str' to your list of readonly_fields in the admin.
EDIT: I should add that this is one quick solution.  A more robust solution is to subclass models.DateField into a MyCustomDateField that acts like a DateField except that when the value is date(1,1,1) it renders as "On incorporation" or when a user saves "On incorporation" it saves the value as date(1,1,1).  This would ensure that you can reuse this functionality everywhere this field type shows up.  However, if it only shows up in one place; this may be overkill.
You'd need something like (this is untested; you may need to additionally alter your the forms DateField and/or other things; e.g., if you use django-south you'll have to add custom introspection rules).
class MyCustomDateField(models.DateField):
    date_111_str = 'On incorporation'
    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        if val is None:
            data = ''
        elif val.year == val.day == val.month == 1:
            data = date_111_str
        else:
            data = datetime_safe.new_date(val).strftime("%Y-%m-%d")
        return data
    def get_prep_value(self, value):
        if value == date_111_str:
            value = datetime.date(1,1,1)
        return super(MyCustomDateField,self).get_prep_value(self, value)

A: As @drjimbob (and carljm on #django) suggested, the solution is to create a member function or property on the model, e.g.:
class Director(models.Model, Specializable):
    date_of_appointment = models.DateField()
    date_ceased_to_act = models.DateField(blank=True,null=True)

    #def date_formatter and def _date_format_factory omitted

    date_of_appointment_formatted = lambda self: self.date_formatter(getattr(self, 'date_of_appointment'))
    date_ceased_to_act_formatted = _date_format_factory(None, 'date_ceased_to_act') #for some reason, I get a 'classmethod/staticmethod object is not callable' error if I decorate _date_format_factory
    date_of_appointment_formatted.short_description = u'Date of appointment'

Note the date_of_appointment_formatted.short_description - the ModelAdmin will use the short_description as the label for a readonly_field.
To get the properties working with model fields, a custom form is needed:
class DirectorInlineForm(EnhancedModelForm):
    from django.utils import formats
    date_ceased_to_act_formatted = forms.DateField(required = False, widget = admin.widgets.AdminDateWidget,
                                                   label = u'Date officer\'s appointment terminated',
                                                   input_formats = formats.get_format('DATE_INPUT_FORMATS') + (Director.on_incorporation,))

            class Meta:
                model = Director # Note that model declaration is necessary for this to work with additional fields declared

    def __init__(self, *args, **kwargs):
        super(DirectorInlineForm, self).__init__(*args, **kwargs)
        # set initial values from model of declared fields
        if self.instance:
            self.initial['date_ceased_to_act_formatted'] = self.instance.date_ceased_to_act_formatted

    def save(self, commit = True):
        # save logic for magic formatted fields
        if self._raw_value('date_ceased_to_act_formatted') == Director.on_incorporation:
            sval = Director.on_incorporation
        else: sval = self.cleaned_data['date_ceased_to_act_formatted']

        self.instance.date_ceased_to_act_formatted = sval

        return super(forms.ModelForm, self).save(commit)

The ModelForm needs a custom field to display the property; a custom __init__ to set the initial value for the field from the property, and a custom save, to set the model property from the form field.
In my example, the save also has to be aware of the magic value, because of how DateField handles the magic value. You could push that code into a custom field instead.

A: I would massage field values with javascript. You can override the admin templates, and attach your javascript code into the {% block extrahead %} block ( some more info from the django book). Put your magic massage function example into .ready() (if you use jQuery).
I hope this will work for you, because I would like to do something similar, but haven't implemented yet. :)


text:
Q: Can MOSS2007 authenticate to other AD's? Let me explain what I have. I work for a local government and I currently have MOSS2007 Server running on our SBS2003 DC that runs Domain A.
The County recently purchased new servers and has a Server 2008 Standard R2 box that they use as a web server. This box, along with all the other main County servers are on Domain B, and yes there is a trust setup between the 2 domains.
I want to uninstall MOSS off of our server and move it over to the 2008 R2 box, but the question is, If I install Sharepoint on the 2008 R2 box that is on Domain B, can I configure Sharepoint to where still authenticates back to the Domain A AD?
Thanks for the help.

A: Yes since Domain A and Domain B trust each other. I don't see any issues with that.


text:
Q: Customize mgo upsert operation I've a game analytics rest API which stores the average performance statistics of the players. When a new statistic arrives, I want to update the existing game record in Mongodb by merging the new delta onto the existing document. I'm storing the past analytics data as well. So that, I can return data like the player's stats are decreasing or increasing since the game's last update.
The problem is: When I want to upsert my new game data into Mongodb with mgo, it overwrites all of a player's stats array. Actually, this is expected. I know how to fix it if I can modify my document that mgo tries to upsert into Mongodb.
Question: How can I customize mgo upsert behaviour? So that I can add a $push operator in front of Player.Stats to prevent Mongodb erasing the stats array inside the document.
My Real Question: It doesn't matter which Mongo commands I'm going to use. I'll figure it out somehow. What I actually want to know is: How can I customize the behaviour of mgo before upsert?
Some Solutions: I've tried some solutions myself before. Like, encoding/decoding Game struct into bson.M to customize it. However, I found it cumbersome and messy. If there's no other way, I'd use it.
Blocks: I don't want to hand-write all of my structs fields with bson.M, just to use a $push operator on one field. Because there are dozens of fields, that would be error-prone and will increase my code complexity.

Example:
// Assume that, this is an existing game in Mongodb:
existingGame := Game{
    ID: 1,
    Name: "Existing game",
    // The game has just one player
    Players: []Player{
        // The player has some stats. The newest one is 2.0.
        {1, "foo", []{3.5, 2.0}},
    }
}

// This is a new request coming to my API
// I want to upsert this into the existing Game
newGame := Game{
    ID: 1,
    Players: []Player{
        // As expectedly, this will reset player foo's stats to 5.0
        //
        // After upserting, I want it to be as:
        //
        // []{3.5, 2.0, 5.0}
        //
        // in Mongodb
        {1, "foo", []{5.0}},
    }
}

// Example 2:
// If new Game request like this:
newGame := Game{ID: 1, Players: []Player{{1, "foo", []{5.0},{1, "bar", []{6.7}}}}
// I'm expecting this result:
Game{ID: 1, Players: []Player{{1, "foo", []{3.5, 2.0, 5.0},{1, "bar", []{6.7}}}}

func (db *Store) Merge(newGame *Game) error {
    sess := db.session.Copy()
    defer sess.Close()

    col := sess.DB("foo").C("games")
    // I want to modify newGame here to add a $push operator
    // into a new `bson.M` or `bson.D` to make mgo to upsert
    // my new delta without resetting the player stats
    _, err := col.UpsertId(newGame.ID, newGame)

    return err
}

type Game struct {
    ID int `bson:"_id"`
    Name string
    Players []Player `bson:",omitempty"`
    // ...I omitted other details for simplicity here...
}

type Player struct {
    // This connects the player to the game
    GameID int `bson:"game_id"`
    Name string
    // I want to keep the previous values of stats
    // So, that's why I'm using an array here
    Stats []float64
    // ...
}

I tried this Mongodb command in the console to update the specific game's player:
db.competitions.update({
   _id: 1,
   "players.game_id": 1
}, {
   $push: {
       "players.$.stats": 3
   }
}, {
   upsert: true
})

A: To answer the "My Real Question: How can I customize the behaviour of mgo before upsert?" - you can customise bson marshalling by defining bson Getter to the model.
To illustrate how it works, lets simplify the model to avoid nested documents:
type Game struct {
    ID int `bson:"_id"`
    Name string
    Stats [] float64
}

With newGame as following:
newGame := Game{
    ID: 1,
    Name: "foo",
    Stats: []{5.0}
}

The update col.UpsertId(newGame.ID, newGame) by default marshals newGame into JSON, producing mongo query like:
update({_id:1}, {name: "foo", stats: [5]}, {upsert: true});

To make use of $set, $push etc, you can define a custom bson getter. E.g.
func (g Game) GetBSON() (interface{}, error) {
    return bson.M{
        "$set": bson.M{"name": g.Name},
        "$push": bson.M{"stats": bson.M{"$each": g.Stats}},
    }, nil
}

So the update col.UpsertId(newGame.ID, newGame) will produce a mongodb query
update({_id:1}, {$set: {name: "foo"}, $push: {stats: {$each: [5]}}}, {upsert: true});

To make it crystal clear - the custom marshaler will be used in all mgo queries, so you probably don't want to define it directly to the model, but to its derivative to use in upsert operations only:
type UpdatedGame struct {
    Game
}

func (g UpdatedGame) GetBSON() (interface{}, error) {
    return bson.M{....}
}

.....

newGame := Game{
    ID: 1,
    Name: "foo",
    Stats: []{5.0}
}

col.UpsertId(newGame.ID, UpdatedGame{newGame})


text:
Q: Stop rearrangement of windows on Alt+Tab I expect Alt+Tab and Shift+Alt+Tab to cycle through all open applications in a workplace in order or in reverse order, even after I switch applications (like in Windows), but that's not the default behavior.
Here's what I mean:
Given applications A, B, C in that order, A is in focus.
The behavior I want

*

*I use Alt+Tab to switch focus to application B.

*The order of applications remains A, B, C.

*I use Shift+Alt+Tab to switch focus back to application A.

The current behavior, which I find counter-intuitive

*

*I use Alt+Tab to switch focus to application B.

*The order of applications swaps between A and B. The order is now B,
A, C.

*I use Shift+Alt+Tab thinking I'll switch back to application A but instead I find application C.

Is there an extension or Gnome setting that'll allow for the behavior I want, or is this hard-coded?


text:
Q: Zero padding the employee no. field in Talend Job While developing Talend job using tMap,
I am in need of executing zero padding of a field that contains numbers (example: 1542) and is of 20 characters length.

*

*Will my proposed formula

StringHandling.STR('0',20-(StringHandling.LEN(row1.eno)))+row1.eno
work?

*If not, what would be the best way to do so?

A: Why don't you use StringHandling.LPAD(row1.eno, 20, '0') or something of a kind?
Left zero padding is what you require, if I understood you correctly...
R

A: A simple String.format() can do that :
String.format("%020d",row1.eno)


text:
Q: Docker Build with ARG not passing Docker file:
# copy over system jboss configs
    ARG SYSTEM_TYPE
    COPY $SYSTEM_TYPE/AP/standalone.conf  $JBOSS_HOME/bin/standalone.conf
    COPY $SYSTEM_TYPE/AP/standalone-ha-bob.xml  $JBOSS_HOME/bin/standalone-ha-bob.xml

Docker Command:
docker build --build-arg SERVER_TYPE=jbossconf/ENT-UAT/ -f /usr/etc/repos/docker-files/test-dockerfile-app -t appserver/test:1.0 .

Docker Build Result:
Step 15 : COPY $SYSTEM_TYPE/AP/standalone.conf $JBOSS_HOME/bin/standalone.conf
lstat AP/standalone.conf: no such file or directory

The --build-arg does not appear to be passing to the dockerfile. Where am I going wrong?

A: On your build args you are passing SERVER_TYPE and referencing  $SYSTEM_TYPE on your dockerfile, that should fix it!


text: Q: Firebase remove authenticated users created with "test phone numbers" after some time? I am using smartphone authentication feature from firebase to register my users, but some of my users do not receive SMS codes in their mobile phones(signal problems...), and sometimes i really need these customers, so i create a test SMS code (using the real phone number, so they can receive SMS in the future). When they authenticate with the fake SMS Code, firebase create an ID with an UID and i can login again later with no problems, but happened that 3 times these users created with the fake number feature and with an valid and registered UID were deleted from the authentication list after some time, i cant find them anymore, and when i register them again, a new UID is generated, is this a real behavior of firebase, exclude test numbers UID generated after some time?


text:
Q: how to use Action_view intent to post on facebook wall? how to use Action_view intent to post on facebook wall in android?
I have done facebook sdk integration with my Android app it is working fine for me.
But i want to do it with Action_view intent.

A: Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.facebook.com/dialog/feed?app_id=YOUR_APP_ID&redirect_uri=REDIRECT_URI");

It works fine for me.
Add your appid and redirected uri to above url.

A: Please refer to this question:
Android and Facebook share intent
The share Intent for Facebook has been broken for quite some time. They still haven't completely fixed it.


text:
Q: WooCommerce order-received redirect based on payment method Usually in WooCommerce submitted orders are redirect to /order-received/ once payment is completed.
Is it possible to redirect customer to a custom page for a particular payment method?
For example:
Payment method 1 -> /order-received/
Payment method 2 -> /custom-page/
Payment method 3 -> /order-received/

A: With a custom function hooked in template_redirect action hook using the conditional function is_wc_endpoint_url() and targeting your desired payment method to redirect customer to a specific page:
add_action( 'template_redirect', 'thankyou_custom_payment_redirect');
function thankyou_custom_payment_redirect(){
    if ( is_wc_endpoint_url( 'order-received' ) ) {
        global $wp;

        // Get the order ID
        $order_id =  intval( str_replace( 'checkout/order-received/', '', $wp->request ) );

        // Get an instance of the WC_Order object
        $order = wc_get_order( $order_id );

        // Set HERE your Payment Gateway ID
        if( $order->get_payment_method() == 'cheque' ){

            // Set HERE your custom URL path
            wp_redirect( home_url( '/custom-page/' ) );
            exit(); // always exit
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.

How to get the Payment Gateway ID (WC settings > Checkout tab):

A: A small correction.
"exit" needs to be within the last condition
add_action( 'template_redirect', 'thankyou_custom_payment_redirect');
    function thankyou_custom_payment_redirect(){
    if ( is_wc_endpoint_url( 'order-received' ) ) {
        global $wp;

        // Get the order ID
        $order_id =  intval( str_replace( 'checkout/order-received/', '', $wp->request ) );

        // Get an instance of the WC_Order object
        $order = wc_get_order( $order_id );

        // Set HERE your Payment Gateway ID
        if( $order->get_payment_method() == 'cheque' ){

            // Set HERE your custom URL path
            wp_redirect( home_url( '/custom-page/' ) );
            exit(); // always exit
        }
    }
}


text:
Q: Face bounding box for face landmark detection In face landmarks detection, we first find the face bounding box from the whole image, and then second we find the landmarks from this bounding box.
My question is, during training, should I use the ground truth face box, or the detected face box (just like how we find the box during testing)?
Thanks in advance!
Best,
Ruixin


text:
Q: How to get only "date" in DateTime format using syncfusion_flutter_datepicker in Flutter What i want:
I want to get only the startDate and endDate in DateTime format so that i can find the difference of days between the two dates. Instead i'm getting startDate and endDate in String format.
My code:
  void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) {
    print("Printing start date before setstate");
    print(startDate);
    setState(() {
      if (args.value is PickerDateRange) {
        _range = DateFormat('dd/MM/yyyy')
                .format(args.value.startDate)
                .toString() +

            ' - ' +
            DateFormat('dd/MM/yyyy')
                .format(args.value.endDate ?? args.value.startDate)
                .toString();
 } else if (args.value is DateTime) {
        _selectedDate = args.value.toString();
      } else if (args.value is List<DateTime>) {
        _dateCount = args.value.length.toString();
      } else {
        _rangeCount = args.value.length.toString();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.teal[50],
      body: Container(
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height * 0.40,
                child: Card(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25.0)),
                  child: SfDateRangePicker(
                    view: DateRangePickerView.month,
                    monthViewSettings: DateRangePickerMonthViewSettings(
                        showTrailingAndLeadingDates: true),
                    selectionColor: Colors.teal,
                    startRangeSelectionColor: Colors.teal[400],
                    endRangeSelectionColor: Colors.teal[400],
                    rangeSelectionColor: Colors.teal[200],
                    rangeTextStyle:
                        const TextStyle(color: Colors.white, fontSize: 15),
                    onSelectionChanged: _onSelectionChanged,
                    selectionMode: DateRangePickerSelectionMode.range,
                    initialSelectedRange: PickerDateRange(
                      DateTime.now(),
                      DateTime.now().add(
                        const Duration(days: 5),
                      ),
                    ),
                  ),
                ),
              ),

What i've tried:
I tried to print the startDate like this:
        print(args.value.startDate);
        final DateFormat formatter = DateFormat('yyyy-MM-dd');
        final String formattedStartDate =
            formatter.format(args.value.startDate);
        print(formattedStartDate); // printing only date

and i successfully got the date but it is the String type instead of DateTime type.

A: If you want to get a DateTime object from String do that:
DateFormat('yyyy-MM-dd').parse('some string date')

A: Try to use the dates in a required format in the method difference.
var berlinWallFell = DateTime(1989, DateTime.november, 9);
var dDay = DateTime(1944, DateTime.june, 6);
Duration difference = berlinWallFell.difference(dDay);
assert(difference.inDays == 16592);

Link: https://api.flutter.dev/flutter/dart-core/DateTime/difference.html


text:
Q: Bluemix Git connect to Git Desktop I have created a new project in Bluemix with a Text to Speech Service. I added a toolchain with a new Git Repo. I have created a key on the computer and copied that key into the Bluemix RepositoryDeploy Keys section.
When I go to the computer Git Desktop I get an authentication error. I have tried everything and can't get it to authenticate.

A: Here are the steps I used to import a GitLab repository into GitHub Desktop:

*

*Set up git authentication with SSH (I had trouble getting this to work with HTTPs -- kept getting Failed authentication errors). To generate a key, follow the instructions here.

*Clone the repository using the git cli (git clone git@git.ng.bluemix.net:...)

*Add to GitHub Desktop by going File > Add Local Repository

*Finally, after making a change, I was able to sync the repository and push the changes up

I got a gpg error when I ran it for the first time and found this solution to solve that (you may / may not run into this):
git config --global gpg.program $(which gpg)

https://github.com/isaacs/github/issues/675


text:
Q: Am getting error " Zend_Db_Adapter_Abstract->fetchAll('UPDATE nmcatalo...') "when am executing UPDATE Query?
public function listAction()
{
    $resource = Mage::getSingleton('core/resource');
    $readConnection = $resource->getConnection('core_read');
    $qur = 'SELECT * FROM nmcatalog_category_product where category_id = 3 AND product_id = 1';
    $results1 = $readConnection->fetchAll($qur);
    if(!empty($results1)){
      $writeConnection = $resource->getConnection('core_write');
      $updatequry = 'UPDATE nmcatalog_category_product SET position = 6 where category_id = 3 AND product_id = 1';
      $updateresult = $writeConnection->fetchAll($updatequry);
    }else{
      echo "Array Empty";
    }

}

A: Use below code:
change fetchAll with query
public function listAction()
{
    $resource = Mage::getSingleton('core/resource');
    $readConnection = $resource->getConnection('core_read');
    $qur = 'SELECT * FROM nmcatalog_category_product where category_id = 3 AND product_id = 1';
    $results1 = $readConnection->fetchAll($qur);
    if(!empty($results1)){
      $writeConnection = $resource->getConnection('core_write');
      $updatequry = 'UPDATE nmcatalog_category_product SET position = 6 where category_id = 3 AND product_id = 1';
      $updateresult = $writeConnection->query($updatequry);
    }else{
      echo "Array Empty";
    }

}


text:
Q: How checking lookup depth into nested dictionary as class attribute? I created a nested dictionary based on AttrDict found there :
Object-like attribute access for nested dictionary
I modified it to contain str commands in "leaves" that gets executed when the value is requested/written to :
commands = {'root': {'com': {'read': 'READ_CMD', 'write': 'WRITE_CMD'} } }

class AttrTest()
    def __init__:
        self.__dict__['attr'] = AttrDict(commands)

test = AttrTest()
data = test.attr.root.com.read    # data = value read with the command
test.attr.root.com.write = data   # data = value written on the com port

While it works beautifully, I'd like to :

*

*Avoid people getting access to attr/root/com as these returns a sub-level dictonary

*People accessing attr.root.com directly (through __getattribute__/__setattr__)

Currently, I'm facing the following problems :

*

*As said, when accessing the 'trunk' of the nested dict, I get a partial dict of the 'leaves'

*When accessing attr.root.com it returns {'read': 'READ_CMD', 'write': 'WRITE_CMD'}

*If detecting a read I do a forward lookup and return the value, but then attr.root.com.read fails

Is it possible to know what is the final level Python will request in the "path" ?

*

*To block access to attr/root

*To read/write the value accessing attr.root.com directly (using forward lookup)

*To return the needed partial dict only if attr.root.com.read or attr.root.com.write are requested

Currently I've found nothing that allows me to control how deep the lookup is expected to go.
Thanks for your consideration.

A: For a given attribute lookup you cannot determine how many others will follow; this is how Python works. In order to resolve x.y.z, first the object x.y needs to be retrieved before the subsequent attribute lookup (x.y).z can be performed.
What you can do however, is return a proxy object that represents the (partial) path instead of the actual underlying object which is stored in the dict. So for example if you did test.attr.com then this would return a proxy object which represents the path attr.com to-be-looked up on the test object. Only when you encounter a read or write leaf in the path, you would resolve the path and read/write the data.
The following is a sample implementation which uses an AttrDict based on __getattr__ to provide the Proxy objects (so you don't have to intercept __getattribute__):
from functools import reduce

class AttrDict(dict):
    def __getattr__(self, name):
        return Proxy(self, (name,))

    def _resolve(self, path):
        return reduce(lambda d, k: d[k], path, self)

class Proxy:
    def __init__(self, obj, path):
        object.__setattr__(self, '_obj', obj)
        object.__setattr__(self, '_path', path)

    def __str__(self):
        return f"Path<{'.'.join(self._path)}>"

    def __getattr__(self, name):
        if name == 'read':
            return self._obj._resolve(self._path)[name]
        else:
            return type(self)(self._obj, (*self._path, name))

    def __setattr__(self, name, value):
        if name != 'write' or name not in (_dict := self._obj._resolve(self._path)):
            raise AttributeError(f'Cannot set attribute {name!r} for {self}')
        _dict[name] = value

commands = {'root': {'com': {'read': 'READ_CMD', 'write': 'WRITE_CMD'} } }

test = AttrDict({'attr': commands})
print(f'{test.attr = !s}')                # Path<attr>
print(f'{test.attr.root = !s}')           # Path<attr.root>
print(f'{test.attr.root.com = !s}')       # Path<attr.root.com>
print(f'{test.attr.root.com.read = !s}')  # READ_CMD
test.attr.root.com.write = 'test'
test.attr.root.write = 'illegal'  # raises AttributeError


text:
Q: Как использовать netflix eureka и feign без spring-boot? Добрый день. Я пытаюсь перейти на микросервисную архитектуру. У меня есть сервер eureka и сервисы которые взаимодействуют между собой с помощью Feign. Но к сожалению так же есть очень большое web приложения с jsf, spring, hibernate и т.д. которое я не могу переписать на spring-boot, но которое обязательно должно так же взаимодествовать с остальными сервисами. В подключении в него любых библиотек типа spring-cloud или чего-то наподобия я не ограничен. Как я могу использовать в нем eureka и feign? Заранее благодарен.

A: Боюсь в таком случае вам понадобиться не только feign - feign это всего лишь враппер над http клиентом. Для доступа к сервисам по имени, необходимо подключиь и настроить Ribbon.
За помощью можно обратиться в официальную документацию Ribbon: ribbon
Там же есть и описание ribbon-eureka.
Spring-Boot уже сам конфигурирует Feign клиентов для работы с Ribbon. Не уверен, что это в конечном итоге вообще пригодится, но если будет нужно, знания можно черпать из процесса конфигурирования Feign в проекте spring boot netflix. Начать стоит с класса FeignClientsRegistrar

A: Можно попробовать подключить спрингбутовский стартер, например spring-cloud-starter-eureka-server. Залезть в jar этого стартера и посмотреть файл META-INF/spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration
А теперь заимпортить эту конфигурацию самому:
@Import(EurekaServerAutoConfiguration.class)


text:
Q: 2-way ANOVA (aov) produces no F or P values I have data that has been subjected to one of two treatments (solution added or not) and is in a random block design. I have 8 blocks (numbered 1-8) but in the aov, df=1. R didn't recognise there were 8, so I lettered them (B1, B2 etc). Now there is no F value or p value in the two-way aov, although now the df=7.
Originally:
soilaov <- aov(Si.arc.leaf~Block*Treatment, data=soilbd)
summary(soilaov)

Output
                `Df`    `Sum Sq`   `Mean Sq` `F value` `Pr(>F)`

Block            `1` `5.174e-05` `5.174e-05`   `3.941` `0.0705 .`

Treatment        `1` `2.526e-05` `2.526e-05`   `1.924` `0.1907`
Block:Treatment  `1` `7.310e-06` `7.310e-06`   `0.557` `0.4699`
Residuals       `12` `1.576e-04` `1.313e-05`

Now:
soilaov <- aov(Si.arc.leaf~Block*Treatment, data=soilbd)
summary(soilaov)

Output
                `Df`    `Sum Sq`   `Mean Sq`
Block            `7` `1.647e-04` `2.352e-05`

Treatment        `1` `2.526e-05` `2.526e-05`

Block:Treatment  `7` `5.193e-05` `7.419e-06`


text:
Q: Connection refused When I try to install any package in Ubuntu 16.04.3 LTS It show me this Error Message :
`Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',))'
pip :
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)


text:
Q: JSON schema - objects with same datatype I generated the following JSON:
{
 "someString" : "example",
 "obj1" : {
     "opt1" : 1,
     "opt2" : 1,
     "opt3" : "aaa"
 },
 "obj2" : {
     "opt1" : 55,
     "opt2" : 55,
     "opt3" : "bbb"
 }
}

and there will be more of objects(obj1, obj2, obj3, obj4, ...) with same data type (opt1, opt2, opt3)
now I want to create schema for this but i don't know how to combine all this objects in schema.
EDIT:
I created schema:
root: {
    "type" : "object",
    "oneOf" : [
        {
        "properties" : {
            "someString" : { "type" : "string" }
        },
        "patternProperties" : { "^.*$" : { "$ref" : "./schemas/myPatternProperties.json#" } },
        "additionalProperties" : false }
        }
    ]
}

and myPatternProperties.json looks:
{
    "type" : "object",
    "properties" : {
        "opt1" : { "type" : "number" },
        "opt2" : { "type" : "number" },
        "opt3" : { "type" : "string" },
    }
    "required" : [ "opt1", "opt2", "opt3" ]
}

Is there anything wrong because, my generated JSON is still not recognized as this schema type.

A: As I understand your problem is to describe object with a lot of properties with the same type and some naming rules. To solve that you must specify patternProperties section
{
    "patternProperties": {
        "^(/[^/]+)+$": { "$ref": "http://some.site.somewhere/entry-schema#" }
}

that construction specify pattern to match for properties. Example how to use patternProperties Read more at specification
UPDATE
Actually full scheme must be something like that
{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "type": "object",
    "properties": {
        "someString": {
            "type": "string"
        }
    },
    "patternProperties": {
        "^obj([0-9]+)$": {
            "$ref": "#/definitions/objEntity"
        }
    },
    "additionalProperties": false,
    "required": [ "someString" ],

    "definitions": {
        "objEntity": {
            "type": "object",
            "properties": {
                "opt1": { "type": "number" },
                "opt2": { "type": "number" },
                "opt3": { "type": "string" }
            },
            "required": ["opt1", "opt2", "opt3"]
        }
    }
}

Of course you can split that scheme to more than 1 file, and  change links to type definitions.


text:
Q: How can I use a variable outside an async function in Node.js? I am trying to use the variable bida elsewhere in my code. For example, when I try to create the variable mida. Is there a way to do that without nesting everything inside the getFX() function? I understand it's an async function issue but how can I get around it?
const fetch = require("node-fetch");

async function getFX() {

let bida;

  try {

    var req = await fetch('https://economia.awesomeapi.com.br/all/USD-BRL');
    var response = await req.json()

   bida = await response.USD.bid;
   aska = await response.USD.ask;

    console.log(bida, aska)

  } catch (e) {
    // handle error
    console.error(e)
  }
}

getFX()

var mida = bida + 1;

console.log (mida);

A: you should initialize the bida variable outside of the getFX() function to be able to access it elsewhere in that file, and also set the value of mira variable only when getFX resolves using .then() to be able to use the value of bida because getFX is an async function. Here is how I did it:
const fetch = require("node-fetch");

let bida;

async function getFX() {

    try {

       var req = await fetch('https://economia.awesomeapi.com.br/all/USD-BRL');
       var response = await req.json()

       bida = await response.USD.bid;
       aska = await response.USD.ask;

       console.log(bida, aska)

    } catch (e) {
        // handle error
        console.error(e)
    }
}

getFX().then(() => {
    var mida = bida + 1;
    console.log (mida);
})

Hope it helps !


text:
Q: openpyxl how to highlight all other columns that differ if column A is same? I have one excel file that contains multiple columns. First column contains the key and there are duplicates.
What I want to achieve is to compare values in all columns that contain same key, and highlight if they differ.
Below is an example:
values = {'product_key': [101, 102, 103, 101, 105, 103],
        'date': ['2020-01-01', '2020-05-05', '2019-11-15', '2020-03-02', '2019-03-01', '2019-11-15'],
        'price': ['$15', '$13', '$11', '$14',' $20', '$18']}
df = pd.DataFrame(values, columns = ['product_key', 'date', 'price'])

And my table look like this:
   product_key  date      price
      101    2020-01-01   $15
      102    2020-05-05   $13
      103    2019-11-15   $11
      101    2020-03-02   $14
      105    2019-03-01   $20
      103    2019-11-15   $18

I want to have the two price and date of 101 highlighted, and the price of 103 highlighted. I'm currently using openpyxl. And if openpyxl cannot do that, is there any other library (available in anaconda) can help?

A: I did not attempt to achieve this with only openpyxl, but that will require you to iterate over the entire sheet (=dataframe) and manually grouping by each product_key then compare using openpyxl/"Excel" syntax.
Using styleframe (of which I'm one of the maintainers) will allow you to solve this on the dataframe level, using pandas syntax.
First we group by the product_key then using .apply to call a custom function on each sub dataframe. Then we can use duplicated with negation (~) and style using styleframe.
from styleframe import StyleFrame, Styler

values = {'product_key': [101, 102, 103, 101, 105, 103],
          'date': ['2020-01-01', '2020-05-05', '2019-11-15', '2020-03-02', '2019-03-01', '2019-11-15'],
          'price': ['$15', '$13', '$11', '$14',' $20', '$18']}
full_df = pd.DataFrame(values, columns=['product_key', 'date', 'price'])

yellow_bg_style = Styler(bg_color='yellow')
full_sf = StyleFrame(full_df)

def style_non_matching(grouped_df):
    if len(grouped_df) == 1:
        return
    grouped_sf = StyleFrame(grouped_df)
    for column in ('date', 'price'):
        grouped_sf.apply_style_by_indexes(grouped_sf[~grouped_sf[column].duplicated(keep=False)],
                                          yellow_bg_style,
                                          cols_to_style=column)

full_sf.groupby('product_key').apply(style_non_matching)
full_sf.to_excel('test.xlsx').save()

Will produce


text:
Q: Best way to structure code that calls a web service I am calling a web service via a httpwebrequest,  and getting a response. The web service is meant to run 24/7.
What is the best way to structure this code, with checks that the service is "available"?
What I have:
if (NetworkIsAvailable())
{
  // Call web service
 // Handle exceptions within here.
}

else
{
 // to throw a relevant exception that there is no network
}

Is it wise to throw an exception, or just return false? The svc should never be down

A: Depending on the type of data you are receiving back, the frequency of checks, etc I would use a general purpose solution that tries the connection multiple times on a failure and then categorizes "exceptions" on failure (no two exceptions are ever the same in my experience).
For instance:
var failCount = 0;
var succeeded = false;

while ((failCount < 3) && (!succceeded)) {
   try {
      //call service....
      succeeded = true;
   } catch(WebException wex) {
      //handle wex, for instance look for timeout and retry
   } catch(...) {
     //Handle other exceptions differently...
     LogError("BOOOM: " + excep);
     throw;
   } catch(Exception ex) {
     //handle a general exception
     failCount++;
   }
}

if (failCount >= 4) {
   //Unspecified error multiple times, react appropriately...
}

Obviously you dont want to do this multiple tries if its expensive call, here I assume its a sort of "heartbeat" check thats not too expensive. The "failCount" can be adjusted depending on how "turbulent" you expect the connection to be.


text:
Q: GKE Beta Logging experience - JSON Parsing lost we log json content to STDOUT from our pods and GKE nicely sends them to stackdriver logging and it gets parsed into a jsonPayload within stackdriver logging.
when we check the  Try the new Beta Monitoring and Logging experience checkbox in the GKE cluster definition, the json parsing ability is lost and the log content is just taken as a textPayload with all json parsing gone.
Is this a bug - any ETA for a fix?

A: As explained in the release note fixed issue section,

If you use Stackdriver Kubernetes Monitoring Beta with structured JSON logging, an issue with the parsing of structured JSON log entries was introduced in GKE v1.11.4-gke.12.

This is fixed by upgrading your cluster:
GKE v1.11.6-gke.2
You may also see the following issue thread or the release guide for Stackdriver Kubernetes Monitoring for more details.


text:
Q: 36 chars MAC addresses on Windows Server 2012 DHCP server When I connect devices on my network, the DHCP server running on a Windows Server 2012 sometimes reports their MAC address correctly (12 characters), but sometimes it reports their MAC address 36 characters long with a random prefix.
Why is this happening? How can I solve it?
Requested screenshot
As mentioned in comments, maybe is an ID, but last 12 digits of it is always equal to the MAC address of the machine. In this case: Why is the same device sometimes shown with its MAC address and sometimes with this ID (with its MAC address as a suffix)?

A: The primary identifier for DHCP requests isn't actually the "MAC address" field – it's the "Client ID" field. (It's optional, but most devices include it.)
DHCP Client IDs can have several types. Most devices generate a Client ID of type 1, which just uses the same MAC address and nothing else. (So for example, instead of binding a client to MAC address AA-BB-CC-DD-EE-FF, you would bind it to Client ID "01:aa:bb:cc:dd:ee:ff".) Often this also happens in reverse – whenever a DHCP server sees a Client ID of type 1, it just shows a MAC address.
However, there are other Client ID types which are not MAC-based, for example type 0 which contains a DNS domain name, or type 255 which contains a DHCPv6 IAID+DUID (RFC4361 format). Systemd-networkd is one such DHCP client which by default sends a type-255 client ID, which some DHCP servers will show as having a ff: prefix.
(And also importantly, even if the Client ID is MAC-based, it doesn't have to match the client's actual MAC address. Some DHCP servers enforce this, but as far as I know, most do not. It's quite likely that if device A sent a client ID belonging to device B, it would receive device B's IP address assignment too.)
The DHCPv6 DUID in itself has subtypes, some of which are MAC-based and others aren't. It so happens that systemd-networkd uses type 1 (DUID-LLT), which includes the MAC address at the end – and is indeed 18 bytes (or 36 hex digits) long when combined with the IAID.
Although uncommon, this is still fully standard and nothing to be "solved". But if it creates difficulties when assigning static leases (reservations) in your DHCP server, then the device's owner can tell systemd-networkd to use a traditional MAC-based Client ID using the option:
[DHCPv4]
ClientIdentifier=mac


text:
Q: Mapping Jersey URI Template in Filter I have what I feel should be a quick question, but perhaps I'm not too sure on the proper terminology to be searching under for the answer to this question.
I currently am running Jetty 9.2 web server with Jersey 2.0. I successfully have been able to map url templates to requests as seen below:
@GET
@Path("/box/{boxId}/container/{containerId}/")
@Produces(MediaType.TEXT_PLAIN)
public String GetBoxContainer(@PathParam("boxId") int boxId,
        @PathParam("containerId") String containerId) {
    ....
}

I have also put a filter in front as seen below:
public class AuthenticationFilter implements ContainerRequestFilter{
    public void filter(ContainerRequestContext requestContext) {
        System.out.println("Hello Authentication filter!!!");
    }
}

Is there a similar way I can do a similar @Path("...") inside of the filter? It would be the same authentication argument requirement for GET/POST/PUT etc... Authentication of this resource is dependent on boxId and containerId.
I think something along the lines of Name Binding is what I'm looking for, but not positive.


text:
Q: Jquery else if statement I came up with some jquery to come from an external page and to show the hidden div (#section2) on another page. The problem is that I can't seem to get #section3 to work the same as #section2. Here's the code.
jQuery(document).ready(function() {
    var hash = window.location.hash.substring(0);
    jQuery(hash).css({
        "display": "block"
    });
    if (hash != '#section2') {
        jQuery('#section1').css({
            "display": "block"
        });
    }
    else {
        jQuery('#section1').css({
            "display": "none"
        });
    }
});

I tried else if
     if(hash != '#section3'){
         jQuery('#section1').css({"display":"block"});
          }
I can only seem to get either #section2 or #section3 to appear with section1 hidden when their respective urls with the hash are entered. I can't seem to get them both of them to function correctly at the same time. Basically I need some thing that will produce
     if(hash != '#section2' or '#section3'). I'm learning so any help would be much appreciated.

A: jQuery(document).ready(function() {
    var hash = window.location.hash.substring(0);
    jQuery(hash).css({
        "display": "block"
    });
    if (hash != '#section2' && hash != '#section3') {
        jQuery('#section1').css({
            "display": "block"
        });
    }
    else {
        jQuery('#section1').css({
            "display": "none"
        });
    }
});

Also, look into using the jQuery .show() and .hide() instead of those css changes (same effect, but less wordy, and it remembers the previous state).

A: Try;
$(document).ready(function(){
  var sectionhash = window.location.hash.substring(0);
  $(hash).css({"display":"block"});
  if(hash != '#section2' || hash != '#section3'){
    $('#section1').css({"display":"block"});
  }else {
    $('#section1').css({"display":"none"});
  }
});

OR
$(document).ready(function(){
  var sectionhash = window.location.hash.substring(0);
  $(hash).css({"display":"block"});
  if(hash != '#section2'){
    $('#section1').css({"display":"block"});
  }else if(hash != '#section3'){
    $('#section1').css({"display":"block"});
  }else {
    $('#section1').css({"display":"none"});
  }
});

A: (function($) {
    var hash = window.location.hash;
    $(hash).css('display', 'block');
    $("#section1").toggle(!(hash=='#section2'||hash=='#section3'));
})(jQuery);


text:
Q: Modify a macro to copy and paste using range and retaining formula I found the code below on this site which works perfectly once I referenced the appropriate cells etc. However, I tried to modify it to keep formulas but I am not having much luck. Any help is greatly appreciated.
Sub test()
    Dim names As New Collection
    Dim ws As Worksheet, ws1 As Worksheet
    Dim wb As Workbook
    Dim lastrow As Long
    Dim cell As Range
    Dim nm As Variant
    Dim res As Range
    Dim rngHeader As Range

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set ws = ThisWorkbook.Worksheets("Sheet1")
    With ws
        'change "A" to column with "Names"
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        'change "A" to column with "Names"
        For Each cell In .Range("A2:A" & lastrow)
            On Error Resume Next
            'collect unique names
            names.Add CStr(cell.Value), CStr(cell.Value)
            On Error GoTo 0
        Next cell

        'disable all filters
        .AutoFilterMode = False

        'change "A1:C1" to headers address of your table
        Set rngHeader = .Range("A1:C1")

        For Each nm In names
            With rngHeader
                'Apply filter to "Name" column
                .AutoFilter Field:=1, Criteria1:=nm
                On Error Resume Next
                'get all visible rows
                Set res = .Offset(2).Resize(lastrow - 1).SpecialCells(xlCellTypeVisible)
                On Error GoTo 0

                'if there is visible rows, create new WB
                If Not res Is Nothing Then
                    'create new workbook
                    Set wb = Workbooks.Add
                    'add sheet with name form column "Names" ("Paul", "Nick" or etc)
                    wb.Worksheets.Add.name = nm
                    'delete other sheets from new wb
                    For Each ws1 In wb.Worksheets
                        If ws1.name <> nm Then ws1.Delete
                    Next

                    'copy/paste data
                    With wb.Worksheets(nm)
                        'copy headers
                        .Range("A1").Resize(, rngHeader.Columns.Count).Value = rngHeader.Value
                        'copy data
                        .Range("A2").Resize(res.Rows.Count, res.Columns.Count).Value = res.Value
                    End With

                    'save wb
                    wb.Close saveChanges:=True, Filename:=ThisWorkbook.Path & "\Spreadsheet_" & nm & ".xlsx"
                    Set wb = Nothing
                End If
            End With
        Next
        'disable all filters
        .AutoFilterMode = False
    End With

    Set names = Nothing

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

A: There is a part in your code which states that it copies / pastes data:
            'copy/paste data
            With wb.Worksheets(nm)
                'copy headers
                .Range("A1").Resize(, rngHeader.Columns.Count).Formula = rngHeader.Formula
                'copy data
                .Range("A2").Resize(res.Rows.Count, res.Columns.Count).Formula = res.Formula
            End With

If you copy the .Formula instead of the .Value then it should work. Give it a try and let us know.


text:
Q: Is there a way to calculate the proper wire gauge? I'm looking for the right copper wire gauge for my project.  I've found several charts listing the maximum current that various gauges, solid and stranded, can transmit.  The charts often disagree.  One says an 8 gauge wire with a stranding of "7" has an allowable ampacity of 95A, another says 40A, another says 150A, and another says 75A for a solid wire, but 20A for 43 strands.  I've found some charts that say stranded wire can handle much, much less current, and others that say that stranded wire "might not" be able to handle as much.  How do I know what the right answer is?  Is there a formula I can use to right the right gauge?
Specifically, here's what I'm doing:

*

*Running a heater

*12 volts (needs to be low voltage for safety reasons)

*around 40 amps

*maybe 10 meters of wire

*on a mobile application, so must be stranded for durability

A: There is no single formula which will do what you want to do. Rather, it is a series of steps.

*

*What is your total power? - We already know the answer: 12 volts @ 40 amps, or 480 watts.

*How much power are you willing to waste in your wire? - Let's use 5% as an illustration. As a check, this is 12 watts. Dissipated over a 10-meter cable, this is about 1.2 watts / meter, which seems reasonable. The wire will get warm but not hot, as long as the cable is not contained in an enclosed, insulating cable run.

*5% of 12 volts is .6 volts. Since the cable runs to the heater and also back from the heater, the voltage drop on a single conductor is .3 volts in 10 meters, or .03 volts/meter.

*Since the voltage drop in the cable occurs at 40 amps, the resistance of the wire must follow Voltage = Current x Resistance, and Resistance = Voltage/Current = .03/40 = .00075 ohms/meter. Note that this is the maximum resistance allowable. Any greater value produces more drop in the wire and more power dissipated.

*From a standard table http://www.daycounter.com/Calculators/AWG.phtml you can see that a 3-guage wire will have a resistance of .000647 ohm/meter, while a 4-guage wire has .000815 ohms/meter.
Is this pretty heavy wire? Yup. Can you do better? Well, only if you're willing to heat up the cable more. The problem here is that your supply voltage is so low that you can't afford much resistance. As illustration of this, consider 480 watts at 120 volts. Then the current is 4 amps while the allowable (5%) voltage is 6 volts. Then you can repeat the calculations above and see that you only need 23 guage wire.
Oh yes, and at 3 ga, you want stranded, not for durability, but just so you can bend the suckers.

A: check out the 16th ed. of the wiring regs,BS1716,cable selection,and cable calculations.
Of course this is a British publication,so it doesn't deal in 'gauges',but deals in conductor cross-sectional-area,in millimeters.
hope this helps...