text:
Q: Trouble balancing a binary search tree using AVL I'm unable to identify where I'm going wrong with my AVL implementation for balancing an existing binary search tree. I'm not getting any errors but my binary search tree does not come out to be properly balanced. After insertion, my binary search tree looks like (it would be prudent here to mention that my display_keys method gives us a visualization that is rotated by 90 degrees):
        ∅
    The-Dreamers
            ∅
        Saint-Laurent
                ∅
            Pierrot-le-Fou
                    ∅
                Contempt
                        Cold-War
                    Before-Sunrise
                        ∅
Basic-Instinct
    ∅

This is correct as it seems be to be following the rules for a BST.
But after calling the BalanceTree() method on my binary search tree, I seem to get:
        ∅
    The-Dreamers
        Saint-Laurent
Pierrot-le-Fou
            Contempt
        Cold-War
            Before-Sunrise
    Basic-Instinct
        ∅

which as you can see, is not Balanced. But wait, and here's the catch, if I call BalanceTree() again, the tree comes out to be perfectly balanced and isBSTBalanced returns True also. After the second call to BalanceTree(), our tree looks like:
        ∅
    The-Dreamers
        Saint-Laurent
Pierrot-le-Fou
        Contempt
    Cold-War
            Before-Sunrise
        Basic-Instinct
            ∅

I am adding the complete source code for my BST class for clarity and if somebody wants to execute the code, but I have added a comment (#Addition of new methods for AVL starts here) in the BST class to indicate where the methods for AVL start. You need only concern yourself with them. I would like for you help me pinpoint what exactly is going wrong in my code.
class BST:

    class TreeNode:
        def __init__(self, key, value, left=None, right=None, parent=None):
            self.key = key
            self.value = value
            self.left = left
            self.right = right
            self.parent = parent
            self.height = 1

    def __init__(self):
        self.root = None
        self.size = 0

    def __len__(self):
        return self.size

    def insert(self, key, value):
        if self.root == None:
            self.root = self.TreeNode(key, value)
        else:
            self._insert(key, value, self.root)

        self.size += 1

    def _insert(self, key, value, curr_node):
        if key < curr_node.key:
            if curr_node.left is not None:
                self._insert(key, value, curr_node.left)
            else:
                curr_node.left = self.TreeNode(key, value, parent=curr_node)
        elif key > curr_node.key:
            if curr_node.right is not None:
                self._insert(key, value, curr_node.right)
            else:
                curr_node.right = self.TreeNode(key, value, parent=curr_node)

    def search(self, key):
        if self.root:
            found = self._search(key, self.root)
            if found:
                return found.value
            else:
                return None
        else:
            return None

    def _search(self, key, curr_node):
        if not curr_node:
            return None
        elif curr_node.key == key:
            return curr_node
        elif key < curr_node.key:
            return self._search(key, curr_node.left)
        else:
            return self._search(key, curr_node.right)

    def find_min(self):
        curr = self.root
        while curr.left is not None:
            curr = curr.left
        return curr

    def find(self, node):
        curr = node
        while curr.left is not None:
            curr = curr.left
        return curr

    def delete(self, key):
        node_to_remove = self._search(key, self.root)
        if node_to_remove.left is None and node_to_remove.right is None:
            #Then we identify this as a leaf node
            if node_to_remove is node_to_remove.parent.left:
                #Setting the parent's reference to this to None
                node_to_remove.parent.left = None
            elif node_to_remove is node_to_remove.parent.right:
                node_to_remove.parent.right = None

        #2nd Case --> Two child
        elif node_to_remove.left and node_to_remove.right:
            minimum = self.find(node_to_remove.right)
            self.delete(minimum.key) #We will still have a ref to this node afterwards
            node_to_remove.key, node_to_remove.value = minimum.key, minimum.value

        #3rd Case -> One child
        else:
            if node_to_remove.left:
                node_to_remove.left.parent = node_to_remove.parent
                node_to_remove.parent.left = node_to_remove.left
            elif node_to_remove.right:
                node_to_remove.right.parent = node_to_remove.parent
                node_to_remove.parent.right = node_to_remove.right

    def traversal(self, root):
        res = []
        if root:
            res = self.traversal(root.left)
            res.append(root)
            res = res + self.traversal(root.right)
        return res

    def inorder_traversal(self, root):
        if root:
            self.inorder_traversal(root.left)
            print(root.key)
            self.inorder_traversal(root.right)

    #Addition of new methods for AVL starts here

    def display_keys(self, node, space='\t', level=0):
        """
        Allows us to visualize the tree (albiet rotated by 90 degrees)
        """
        # print(node.key if node else None, level)

        # If the node is empty
        if node is None:
            print(space*level + '∅')
            return

        # If the node is a leaf
        if node.left is None and node.right is None:
            print(space*level + str(node.key))
            return

        # If the node has children
        self.display_keys(node.right, space, level+1)
        print(space*level + str(node.key))
        self.display_keys(node.left,space, level+1)

    def height(self):
        return self._height(self.root)

    def _height(self, curr_node):
        if curr_node is None:
            return -1 #since we are counting number of edges, we will return -1
        else:
            return 1 + max(self._height(curr_node.left), self._height(curr_node.right))

    def isBSTBalanced(self):
        return self._isBSTBalanced(self.root)

    def _isBSTBalanced(self, curr_node):
        if curr_node is None:
            return True
        hleft_subtree = self._height(curr_node.left)
        hright_subtree = self._height(curr_node.right)

        if hleft_subtree - hright_subtree in [-1,0,1]:
            return self._isBSTBalanced(curr_node.left) and self._isBSTBalanced(curr_node.right)
        else:
            return False

    def balance_factor(self):
        if self.root is not None:
            return self._balance_factor(self.root)
        else:
            return 0

    def _balance_factor(self, curr_node):
        if curr_node is None:
            return

        hleft_subtree = self._height(curr_node.left)
        hright_subtree = self._height(curr_node.right)

        b_factor = hleft_subtree - hright_subtree
        return b_factor

    def BalanceTree(self):
        if self.isBSTBalanced() == False:
            return self._rebalance(self.root)

    def _rebalance(self, curr_node):
        if curr_node is None:
            return None
        curr_node.left = self._rebalance(curr_node.left)
        curr_node.right = self._rebalance(curr_node.right)
        curr_node.height = 1 + max(self._height(curr_node.left), self._height(curr_node.right))
        #print(curr_node.height)
        if self._balance_factor(curr_node) > 1 and self._balance_factor(curr_node.left) >= 0:
            #left heavy subtree
            return self._rotate_right(curr_node)
        if self._balance_factor(curr_node) < -1 and self._balance_factor(curr_node.right) <= 0:
            #right heavy subtree
            return self._rotate_left(curr_node)
        if self._balance_factor(curr_node) < 0 and self._balance_factor(curr_node.right) > 0:
            self._rotate_right(curr_node.right)
            return self._rotate_left(curr_node)
        if self._balance_factor(curr_node) > 0 and self._balance_factor(curr_node.left) < 0:
            self._rotate_left(curr_node.left)
            return self._rotate_right(curr_node)
        return curr_node

    def _rotate_left(self, oldRoot):
        newRoot = oldRoot.right #the newRoot is the right child of the previous root
        oldRoot.right = newRoot.left #replacing right child of the old root with the left child of the new
        if newRoot.left is not None:
            newRoot.left.parent = oldRoot
        newRoot.parent = oldRoot.parent
        if oldRoot == self.root:
            self.root = newRoot
        else:
            if oldRoot.parent.left is oldRoot: #Checking isLeftChild
                oldRoot.parent.left = newRoot
            else:
                oldRoot.parent.right = newRoot

        newRoot.left = oldRoot
        oldRoot.parent = newRoot

        oldRoot.height = 1 + max(self._height(oldRoot.left), self._height(oldRoot.right))
        newRoot.height = 1 + max(self._height(newRoot.left), self._height(newRoot.right))

        return newRoot

    def _rotate_right(self, oldRoot):
        newRoot = oldRoot.left #the newRoot is the left child of the previous root
        oldRoot.left = newRoot.right #replacing left child of the old root with the right child of the new
        if newRoot.right is not None:
            newRoot.right.parent = oldRoot
        newRoot.parent = oldRoot.parent
        if oldRoot == self.root:
            self.root = newRoot
        else:
            if oldRoot.parent.right is oldRoot: #Checking isRightChild
                oldRoot.parent.right = newRoot
            else:
                oldRoot.parent.left = newRoot

        newRoot.right = oldRoot
        oldRoot.parent = newRoot

        oldRoot.height = 1 + max(self._height(oldRoot.left), self._height(oldRoot.right))
        newRoot.height = 1 + max(self._height(newRoot.left), self._height(newRoot.right))

        return newRoot

if __name__ == '__main__':
    obj = BST()
    obj.insert('Basic-Instinct', 0)
    obj.insert('The-Dreamers', 1)
    obj.insert('Saint-Laurent', 2)
    obj.insert('Pierrot-le-Fou', 3)
    obj.insert('Contempt', 4)
    obj.insert('Before-Sunrise', 5)
    obj.insert('Cold-War', 8)

    obj.display_keys(obj.root) #displays a visual representation of our tree, albeit rotated by 90 degrees
    print()
    print("isBSTBalanced:", obj.isBSTBalanced())
    obj.BalanceTree()
    print("isBSTBalanced:", obj.isBSTBalanced()) #After executing BalanceTree(), isBSTBalanced still returns False
    print()
    obj.display_keys(obj.root)

Progress: Revamped _isBSTBalanced method so that it visits every node recursively and not just the root node. The final outcome, however, remains the same.
Progress: I was able to identify one of the major issues being that while I was calling _rotate_left and _rotate_right methods in the _rebalance method, I was not returning them. In addition to this, I was not recursively visiting the left and right subtrees of curr_node, which was initially set to the root of the tree, to be able to traverse the tree in a bottom up manner. I have resolved this too. I have added a display_keys method which allows us to visualize the tree, albeit rotated by 90 degrees. I'm updating the code and prompt in this post accordingly. The problem that still remains is that I have to call the BalanceTree() method more than once in some cases for isBSTBalanced to return True.


text:
Q: Подписка на событие с передачей параметров Здравствуйте,у меня есть 3 объекта
  public  Rectangle rect = new Rectangle();
  public Rectangle square = new Rectangle();
  public Ellipse circ = new Ellipse();

я хочу чтобы они двигались.Создал функцию
 private void TimerTickForRect(object source, EventArgs e)
        {
            Canvas.SetLeft(rect, Canvas.GetLeft(rect) + 1);
        }

И добавил таймер
  timer.Interval = TimeSpan.FromMilliseconds(50); // update 20 times/second
            timer.Tick += TimerTickForRect;
            timer.Start();

Вопрос.Как мне не плодить функции  в стиле
private void TimerTickForRect(object source, EventArgs e)
        {
            Canvas.SetLeft(rect, Canvas.GetLeft(rect) + 1);
        }
        private void TimerTickForSquare(object source, EventArgs e)
        {
            Canvas.SetLeft(square, Canvas.GetLeft(square) + 1);
        }
        private void TimerTickForCircle(object source, EventArgs e)
        {
            Canvas.SetLeft(circ, Canvas.GetLeft(circ) + 1);
        }

а просто сделать универсальную функцию?

A: Возможно, вы хотите просто лямбду?
timer.Interval = TimeSpan.FromMilliseconds(50); // update 20 times/second
timer.Tick += (o, args) => Canvas.SetLeft(rect, Canvas.GetLeft(rect) + 1);
timer.Start();

Отдельная функция TimerTickForRect оказывается не нужна.

Если функция разрастётся, то возможно вы хотите такое:
timer.Interval = TimeSpan.FromMilliseconds(50); // update 20 times/second
timer.Tick += (o, args) => MoveRight(rect); // именно rect!
timer.Start();

void MoveRight(UIElement e)
{
    Canvas.SetLeft(e, Canvas.GetLeft(e) + 1);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two density functions for the same distribution Let $p_1, p_2$ be two density functions for a stochastic variable $(X,Y)$. Assume that $p_1 = f^2$, where $f$ are the density functions of $X$ and $Y$, that is, $X$ and $Y$ are identically distributed and independent.
Does it follow that $p_2 = f^2 = p_1$?
I have a theorem which allows me to conclude that it holds that $p_1 = p_2$ almost everywhere just by the fact that they give the same distribution, but now I wonder if it holds everywhere, since $p_2$ must also split into $f^2$?

A: You still only have that $p_2 = p_1$ almost everywhere.
For instance, if $f$ is the density of the uniform distribution on $[0,1]$ (so that $(X,Y)$ is uniformly distributed on $[0,1]^2$), then you can define another function $g$ by $g(x) = 1$ for $x\in [0,1]\setminus\{1/2\}$, and $g(1/2) = 2$.
Then $g^2$ is still the density of $(X,Y)$. Even though $g^2$ is different from $f^2$, they are only different on the null set $[0,1]\times\{1/2\}\cup \{1/2\}\times [0,1]$, and the integrals of $f^2$ and of $g^2$ will still be equal.


text:
Q: How do I access response headers using HttpClient in Angular 5? I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.
My request looks like this:
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
  'username': username,
  'password': password
}, {
  headers: new HttpHeaders()
    .set('Content-Type', 'application/json')
})
  .toPromise()
  .then(response => {
    console.log(response);
    return response;
  });

}
How do I access the authorization header of the response?
When I write the response to the console, like above, it says 'null'. I know the error is  not in the backend because I captured the traffic and the backend is indeed sending the bearer token.
Any help is very much appreciated.

A: To access the full response (not just the body of the response), you must pass the observe: 'response' parameter option in your http request. Now you can access the headers with res.headers
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
        'username': username,
        'password': password
    }, {
        headers: new HttpHeaders()
            .set('Content-Type', 'application/json'),
        observe: 'response'
    })
    .map(res => {
        let myHeader = res.headers.get('my-header');
    });

Docs


text:
Q: Company Intranet, PHP/MySQL hosted locally on serve I created an intranet for my company, but I'm having a problem. The files and MySQL tables are hosted on our local server, and is written in PHP. Basically it has a login system for employees and a bulletin board, calendar, etc.
Anyways, I created accounts for the employees, but nobody can login from their own computers, only my computer and the server computer. Is it because I only have PHP installed on these two computers? Do I need to install it on all computers?
Any help is appreciated!

A: You need to make your intranet ip address of server static . Type ipconfig /all in your command promt of server there will be ip address like 192.168.1.*  (not 192.168.1.1) copy that and then use it from other computers to access your local website.


text:
Q: How to make a button sandwiched in between two divs I have 2 Divs on a view port that with height 50vh each, so that the entire view port is filled.
I was able to accomplish the button in the middle by including it under the upper div, then setting the button's margin-top to a negative value, so that it would sit lower.
However, I need to use min-height: 50vh (instead of height: 50vh) for the cases when the content is longer to allow scrolling. Because of min-height, the upper div ends up getting taller to include the entire button.
How can I do this? I tried making a div in between upper and the lower divs (as opposed to under the upper one) but I can't seem make it work. I have included a picture below of what I am trying to accomplish. What is the ideal way to achieve this?

A: Voilà!
The button between two
s gets these styles:
display: block;
position: absolute;
left: 50%;
transform: translateY(-50%) translateX(-50%);

*

*display: block Allows for width and height to be set.

*position: absolute Places it independently of all other elements.

*left: 50% Sends it 50% of the way across the page (to the right).

*transform: translateY(-50%) translateX(-50%) Translates it up 50% of its width (because otherwise, its top would be aligned with the 2nd
's top), and translates it to the left 50% of its width.

Snippet:

html,
body {
  font-family: sans-serif;
  font-weight: bold;
  font-size: 30px;
  outline: 0;
  margin: 0;
  padding: 0;
}
.top {
  min-height: 50vh;
  color: #00bfa5;
  padding: .1em 1em;
}
.main-btn {
  background-color: #ffc400;
  border: 0;
  width: 2.5rem;
  height: 2.5rem;
  display: block;
  position: absolute;
  transform: translateY(-50%) translateX(-50%);
  font-weight: bold;
  font-size: 2em;
  color: white;
  left: 50%;
  border-radius: 50%;
  filter: drop-shadow(16px 16px 20px blue);
  -webkit-filter: drop-shadow(0 2px 3px rgba(0, 0, 0, 0.5));
  cursor: pointer;
  transition: background-color 0.1s ease-out;
}
.main-btn:hover {
  background-color: #ffcc11;
}
.bottom {
  min-height: 50vh;
  background-color: #00bfa5;
  color: white;
  font-size: .8em;
  padding: 2em;
}
input {
  width: 2em;
  height: 2em;
}

  DID YOU EXERCISE FOR 30 MINUTES PER DAY OVER THE LAST 3 DAYS?

<button class="main-btn">></button>

    <input type="radio" name="e" id="yes" />
    I did.

    <input type="radio" name="e" id="mostly" />
    I mostly did.

    <input type="radio" name="e" id="no" />
    Not this time.

A: Just make it absolutely positioned and centered while keeping the element between the other two. The heights of the outer divs won't matter, it will always be in place.
Or you can make it a child of one of the outer ones, make the outer one relatively positioned, the button absolutely positioned and centered horizontally with top or bottom (depending on which outer div you selected as a parent) set to the negative half height of the button.

div {height: 50px; width: 200px;}
#b {background: #efe; position: relative}
#g {background: green}
button {position: absolute; height: 40px; width: 40px; background: orange; border-radius: 40px; margin: auto; left: 0;right: 0;bottom: -20px}

<button></button>

A: Here is a simple example where setting the btn to position:relative; and setting top and left locations.

DIV 1

DIV 2

BTN

#mybtn {
  position:relative;
  top: -125px;
  left: 50px;
}

Here is a demo, you can set the height of the fist div in the end of the css, the button will still stay where it should be.


text:
Q: filtering multiple arrays ngrx I have a store setup that has multiple arrays
I'm trying to search all arrays at once, via a textfield.
I can get this done, by calling a selector function on keyup, that filters the 4 arrays and pushes to a new array.
I've thought about merging all the arrays to one array before filtering, but I want to keep the results separate, as they are going to be displayed in categories.
Just trying to see if I can streamline the performance at all and if there's a more concise way of doing this, in case I need to do something similar with larger arrays.
my textField function:
this.renderer.listen(this.serachField.nativeElement, 'keyup', (event) => {
      if (this.serachField.nativeElement.value.length < 3) { return; }
      this.store.pipe(select(search(this.serachField.nativeElement.value)),take(1))
      .subscribe(data => {
          console.log(data);
        });
    })

The selector function:
export const search = (searchString: string): any => {
    return createSelector(
             appState,
             (state: AppState) => {
                 let arr: any = [];
                 let s = searchString.toUpperCase();
                const comics = state.comics.results.filter((item: Comic) => {
                    let title = item.title.toUpperCase();
                    console.log(title);
                    return title.includes(s);

                });

                const music = state.music.items.filter((item: Album) => {
                    let title = item.name.toUpperCase();
                    console.log(title);
                    return title.includes(s);

                });

                const movies = state.movies.results.filter((item: Movie) => {
                    let title = item.title.toUpperCase();
                    console.log(title);
                    return title.includes(s);

                });

                const games = state.games.filter((item: Game) => {
                    let title = item.title.toUpperCase();
                    console.log(title);
                    return title.includes(s);

                });
                arr.push(comics, music, movies, games);
                return arr;
             }
         );

 };

EDIT: After @GustavMH correct answer I had to slightly change the code to be a little more dynamic in terms of the array naming as follows
export const search = (searchString: string): any => {
    return createSelector(
             appState,
             (state: any) => {
                 let s = searchString.toUpperCase();
                 const keys = [{state: "comics", item: "title", array: 'results'},
                               {state: "music", item: "name", array: 'items'},
                               {state: "movies", item: "title", array: 'results'},
                               {state: "games", item: "title", array: ''}]

                 return keys.map((key) => {
                 let arr = key.array ? state[key.state][key.array] : state[key.state];
                return arr.filter((item: any) => {
                     const title = item[key.item].toUpperCase();
                     console.log(item);
                     return title.includes(s);
                 })})
             }
         );

 };

A: This should implement the selector function with less code and make it more adaptable to kinds of data, if needed you can specify a more precise type in the filter function.
export const search = (searchString: string): any => {
    return createSelector(
             appState,
             (state: AppState) => {
                 let s = searchString.toUpperCase();
                 const keys = [{state: "comics", item: "title"},
                               {state: "music", item: "name"},
                               {state: "movies", item: "title"},
                               {state: "games", item: "title"}]

                 return keys.map(key => state[key.state].results.filter((item: any) => {
                     const title = item[key.item].toUpperCase();
                     console.log(title);
                     return title.includes(s);
                 }))
             }
         );

 };


text:
Q: IDAS not connecting to the ContextBroker i'm having a problem sending the mesurements to the contextBroker.
I have the ContextBroker running on a CentOS virtual machine. On another CentOS virtual machine i'm setting the figway config.ini file with the host=/ContextBroker Virtual Machine Host IP/ and Port=1026. When i send mesurements to my ContextBroker:
python2.7 SendObservation.py Bus1 't|1'

it simply doesn't stick the values to the entity. It gives me a code:200 but the response is just blank.
What am i doing wrong?
UPDATE:
Even when i do from one VM to another (to the one where the contextBroker is running) the command:
GET *ip*:1026/version

, it returns nothing.
UPDATE:
Running
GET localhost:1026/version

works. Returns what's supose to return.

A: The problem could be similar to the one described in the answer to this question. The most probable causes of Orion connection problems are:

*

*Something in the Orion host (e.g a firewall or security group) is blocking the incoming connection

*Something in the client host (e.g a firewall) is blocking the outcoming connection

*There is some other network issue is causing the connection problem.


text:
Q: Use Chinese LiPo battery charger units in series (Create a 2s charger) I have received two LiPo charging modules on eBay with under-voltage and overcharge protection built in.
I would like to achieve a voltage of 7.4V, by connecting the outputs of the two modules in series. I am aware of the many dangers of LiPo batteries and so I am trying to take precaution and make sure that I haven't missed anything.
As far as I can see it will be safe to wire up each of the charging modules with a battery (I am using batteries of the same capacity for each module)
I can then wire up the outputs of the modules in series to achieve the 7.4V output. I can use a single 5V rail to power both modules to allow for simultaneous charging of both batteries. When either of the batteries dies, the circuit will break and thus the over discharge will work normally.

*

*Have I got anything wrong here?

*Is there anything that I should be
cautious about when using the modules in series instead of the
normal, single battery with a single cell?

A: From the image I can see that the OUT- and the IN- are connected together. This means that if you power them in parallel and wire the output in series you effectively have created a short.
Which means that during charging you have to disconnect the series connector and during use have to disconnect the inputs.


text:
Q: What are the ways to make layered block in css I need to make the following page design

I came up with the following coordinates rotation idea, but it's not working for now: I tried to stack it in Y-axis but the first one overlayes others and I don't know how to make others two visible.

body {
    margin: 0;
    background: #b4e0e1;
}

.layer-container {
    width: 400px;
    height: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -100px 0 0 -250px;
    perspective: 500px;
   transform-style: preserve-3d;
}

.layer {
    width: 500px;
    height: 250px;
    position: absolute;
    transition: all 1.5s ease-in-out;
    cursor: pointer;
    z-index: 1;
}

/* dark blue layer */

.dark-blue-layer {
    background: #234688;
}

/* light blue layer */

.light-blue-layer {
    background: #2abfd5;
}

.white-layer {
    background: #fff;
}

.bottom-layer {
    transform: rotateX(0deg) rotateY(-25deg) translateX(0px);
}

.mid-layer {
    transform: rotateX(0deg) rotateY(-25deg) translateX(20px);
}

.top-layer {
    transform: rotateX(0deg) rotateY(-25deg) translateX(40px);
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="styles.css">

How can it be improved and is there another simplier way to implement this?

A: I'm confused by your transform settings and what you are trying to achieve, but to get the look from the green image you can use box-shadow to simulate "background layers":

body {
    margin: 0;
    background: #b4e0e1;
}

.layer-container {
    width: 260px;
    height: 140px;
    background-color: #fff;
    margin: 20px auto;
    box-shadow: 5px 5px 0 0 #234688, 10px 10px 0 0 #2abfd5;
}


text:
Q: Saving checkpoints and resuming training in tensorflow I was playing with saving checkpoints and resuming training from saved checkpoints. I was following the example given in - https://www.tensorflow.org/versions/r0.8/api_docs/python/train.html#import_meta_graph
To keep things simple, I have not used any 'real' training of a network. I just performed a simple subtraction op and each check point saves the same operation on same tensors again and again.
A minimal example is provided in the form of the following ipython notebook - https://gist.github.com/dasabir/29b8f84c6e5e817a72ce06584e988f10
In the first phase, I'm running the loop for 100 times (by setting the value of the variable 'endIter = 100' in the code) and saving checkpoints every 10th iteration. So, the checkpoints being saved are numbered as - 9, 19, ..., 99. Now when I'm changing the 'enditer' value to say 200 and am resuming training, the checkpoints again start to be saved from 9, 19, ... (not 109, 119, 129, ...). Is there a trick I'm missing?

A: Can you print out 'latest_ckpt', and see if it points to the latest ckpt file? Also, you need to maintain the global_step using a tf.variable:
global_step = tf.Variable(0, name='global_step', trainable=False)
...
ckpt = tf.train.get_checkpoint_state(ckpt_dir)
if ckpt and ckpt.model_checkpoint_path:
    print ckpt.model_checkpoint_path
    saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
start = global_step.eval() # get last global_step
print "Start from:", start

for i in range(start, 100):
...
    global_step.assign(i).eval() # set and update(eval) global_step with index, i
    saver.save(sess, ckpt_dir + "/model.ckpt", global_step=global_step)

You can take a look at the full example:
https://github.com/nlintz/TensorFlow-Tutorials/pull/32/files


text:
Q: How to include large input/output? Is there a convention to include large input or output in the question?  The author of this post was kind enough to upload the large input in an external site so that the readers don't have to scroll down a lot to finish reading the question and the responses:
Simplifying a very long symbolic expression by automatically introducing temporal variables or in any other way
The external site features ads that may be offensive to some readers.  There are many fine website for (legal) filesharing.  Any recommendations?

A: I would recommend not including large content in a question, as that is frequently suggestive of "Not a Real Question" or "Too Localized", and suggests that the asker might not know enough about what is happening to be asking in the first place.
That said, I can imagine that there could be cases where it would still be legitimate to do so. Maybe.
If so, and if there isn't a well-accepted, well-known-as-safe tool that would apply already (like jsfiddle.com for JavaScript/HTML/CSS problems, or Pastebin.com for more general code), what I would do is post such content on my own site, within a plain HTML page that does not require any special plugins, works well without JavaScript enabled, and is very clear about any resources that are included.
I would absolutely avoid any attachments that can seem to be dangerous. So, absolutely no exe, zip, or doc files, for instance.
My goal, as someone hoping to get someone to look at my content to learn more about my problem, would be never to include that content in a way that would discourage them from doing so. Long content itself does that, as do links to pages that are unfamiliar, or have content which is perceived to potentially be dangerous.


text:
Q: How can I Configure localhost and remote server with single config file I'm using different configuration files in my localhost and remote server. It makes me very uncomfortable because every time I need to change the server name, password and db name.
Is that any other to have single config method to connect both localhost and remote server?
This is my config file:
<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
    }

    $conn->close();
?>

A: You need to check the host run time.
The following code will check the host whenever the file runs.
And depending upon the host, it will use different credentials.
<?php
$host = $_SERVER['HTTP_HOST'];
if ($host == 'localhost') {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
}
else {
    $servername = "REMOTE_HOST";
    $username = "REMOTE_USERNAME";
    $password = "REMOTE_PASSWORD";
    $dbname = "REMOTE_DB";
}

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>

A: You can check superglobal $_SERVER array's HTTP_HOST value which stores current host.
It is better to use strpos instead of comparison. Your HTTP_HOST can have a specified non-default port like localhost:8080. It is OK since your remote host will very unlikely contain localhost in it's name.
<?php
    if (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false)
    {
        $servername = "localhost";
        $username = "username";
        $password = "password";
        $dbname = "myDB";
    } else {
        $servername = "10.11.12.13";
        $username = "username";
        $password = "P@$$w0rd";
        $dbname = "myDBName";
    }

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $conn->close();
?>

A: Set in your virtual host the environment
    SetEnv environment {production/development}

So your virtual host might looks like this:
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "/path/httpd"
    ServerName mysite.local
    ServerAlias mysite.local
    SetEnv environment production
</VirtualHost>

php code:
<?php
if (getenv('environment') == 'production') {
    $servername = "localhost";
    $username = "production-username";
    $password = "production-password";
    $dbname = "myDB";
} else {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
}

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
$conn->close();

?>


text:
Q: Remove all references to Parallels 7 Windows 7 VM programs My system has been polluted with references to programs residing in a Windows 7 VM in Parallels 7.
For example, Windows programs show up in Spotlight, and in Safari settings under General->Default browser I get an annoyingly long list of irrelevant Windows programs.
I've tried to disable "Share Windows applications with Mac" in Parallels settings, to no avail.
This blog post suggests to add the Applications (Parallels) folder to the Spotlight privacy list, but I can't do that because I don't have that folder. I deleted it some months ago in an unsuccessful attempt to remove the same references as now.
The VM is on a USB disk that's usually not connected so these references must be stored in OS X somewhere. How and where are this links stored and how can I get rid of them?

A: I found a solution that may be specific to my setup, buy may be useful to others too.

*

*I had moved the folder with the Windows applications shortcuts
elsewhere and had forgotten about it. I deleted this folder.

*I deleted duplicates from Finder's 'Open With' menu using /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user followed by sudo killall Finder. You may read more about it here.


text:
Q: Log message style guide I'm looking for a style guide to log messages:
For example:

*

*What & when

*Conventions

*Style & Formatting

*Readability

i.e. what makes a good / bad log message string
I'm particularly interested in what make a good log string - beyond including the TIME, SEVERITY and COMPONENT, as I tend to use log4j which gives me this information for free.

A: Whatever you decide, if it's a text log, start each line with a good timestamp in, preferably, ISO format:
YYYY-MM-DDTHH:MM:SS.mmm
In all likelihood, you will want to follow the timestamp with a severity code.
Some good logging guidelines can be found here:
http://watchitlater.com/blog/2009/12/logging-guidelines/
and here
http://download.oracle.com/docs/cd/B32110_01/web.1013/b28952/logging.htm

A: The 10 Commandments of Logging is the perfect introduction into the world of logging.
This website will teach you the do's & dont's of creating your own log files.

A: That really depends on your application. I may draw inspiration from anything at /var/log/*

A: Effective logging is an art, but there are a few major items that can help:

*

*Thread ID: Enterprise applications are often executed in a multithreaded environment. With thread ID information, you can distinguish one request from another.

*Caller identity: The identity (or principal) of the caller is also an important piece of information. Because different users have different privileges, their execution paths could be very different. Putting the user's identity in the log messages can be a great help for a security-aware application.

*Timestamp: Generally, users can only approximate the time at which a problem occurred. Without a timestamp, it's difficult for the support personnel to identify the problem.

*Source code information: This includes class name, method name, and line number.
(These tips taken from this IBM article on Java logging.)

A: On the convention side, for a few years I've been formatting my logs as:
severity timestamp source message

With severity being symbols for:
(-) Info
(!) Warning
(*) Error

E.g.:
(-) 2010-10-13T18:53:42 foo: Starting up...
(!) 2010-10-13T18:54:11 foo: bar: Unable to lock file "quux", will try again in 4 seconds.
(-) 2010-10-13T18:56:13 foo: Loading plugin "baz"...
(*) 2010-10-13T18:57:39 foo: baz: Error 0xbaadbeef during RPC.
(-) 2010-10-13T18:58:04 foo: Shutting down...

I found out it's easier to glance-search for specific message classes (all errors, all warnings), especially while browsing the logs using a pager in a terminal.


text:
Q: Implementing OpenLayers "Geolocation with Orientation" example with Ionic 3 I am trying to implement the OpenLayers "Geolocation with orientation" example from their GitHub page (https://github.com/openlayers/openlayers/blob/master/examples/geolocation-orientation.js) within my Ionic 3 application.
Basicly, what is my issue: the "postrender" event for TileLayer never gets called in my example so my location never displays on a map. Let's show t he code:
So, first, importing all the neccesary libraries:
import OlMap from 'ol/Map';
import OlXYZ from 'ol/source/XYZ';
import OlTileLayer from 'ol/layer/Tile';
import OlView from 'ol/View';
import OlOSM from 'ol/source/OSM';
import OlOverlay from 'ol/Overlay';
import OlLineString from 'ol/geom/LineString';
import { fromLonLat } from 'ol/proj';
import OlGeolocation from 'ol/Geolocation';

So, next, I do stuff in Ionic's ionViewDidLoad() method:
ionViewDidLoad()
{
    // let myPosition = await this.getLocation();

    this.view = new OlView({
        center: fromLonLat([5.8713, 45.6452]),
        zoom: 19
    });

    this.layer = new OlTileLayer({
        source: new OlOSM()
    });

    this.map = new OlMap({
        layers: [this.layer],
        target: 'map',
        view: this.view
    });

    this.markerEl = document.getElementById('geolocation_marker');
    this.marker = new OlOverlay({
        positioning: 'center-center',
        element: this.markerEl,
        stopEvent: false
    });

    // this.marker.setPosition(fromLonLat([myPosition.coords.longitude, myPosition.coords.latitude])); // sets marker just fine

    this.map.addOverlay(this.marker);

    // COPIED EXAMPLE

    this.positions = new OlLineString([], 'XYZM');

    // Geolocation Control
    this.olgeolocation = new OlGeolocation({
        projection: this.view.getProjection(),
        trackingOptions: {
            maximumAge: 10000,
            enableHighAccuracy: true,
            timeout: 600000
        }
    });

    let self = this;

    this.olgeolocation.on('change', function() {
        console.log('Location changed');
        const position = self.olgeolocation.getPosition();
        const accuracy = self.olgeolocation.getAccuracy();
        const heading = self.olgeolocation.getHeading() || 0;
        const speed = self.olgeolocation.getSpeed() || 0;
        const m = Date.now();

        self.addPosition(position, heading, m, speed);

        const coords = self.positions.getCoordinates();
        const len = coords.length;
        if (len >= 2) {
            self.deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
        }
    });

    this.olgeolocation.on('error', function() {
        alert('geolocation error');
    });

    this.olgeolocation.setTracking(true);

    this.layer.on('postrender', this.updateView); // never called to updateView
    this.map.render();
}

Pretty much the same, I only declared variables as class properties and used those. Also, there are a few other methods, which are also just copied from their example:
// modulo for negative values
private mod(n)
{
    return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI);
}

private addPosition(position, heading, m, speed)
{
    console.log('Add Position called');

    const x = position[0];
    const y = position[1];
    const fCoords = this.positions.getCoordinates();
    const previous = fCoords[fCoords.length - 1];
    const prevHeading = previous && previous[2];

    if (prevHeading) {
        let headingDiff = heading - this.mod(prevHeading);

        // force the rotation change to be less than 180°
        if (Math.abs(headingDiff) > Math.PI) {
            const sign = (headingDiff >= 0) ? 1 : -1;
            headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff));
        }

        heading = prevHeading + headingDiff;
    }

    this.positions.appendCoordinate([x, y, heading, m]);

    // only keep the 20 last coordinates
    this.positions.setCoordinates(this.positions.getCoordinates().slice(-20));

    if (heading && speed) {
        this.markerEl.src = 'https://raw.githubusercontent.com/openlayers/openlayers/master/examples/data/geolocation_marker_heading.png';
    } else {
        this.markerEl.src = 'https://raw.githubusercontent.com/openlayers/openlayers/master/examples/data/geolocation_marker.png';
    }
}

// recenters the view by putting the given coordinates at 3/4 from the top or
// the screen
private getCenterWithHeading(position, rotation, resolution)
{
    console.log('Get Center with Heading called');

    const size = this.map.getSize();
    const height = size[1];

    return [
        position[0] - Math.sin(rotation) * height * resolution * 1 / 4,
        position[1] + Math.cos(rotation) * height * resolution * 1 / 4
    ];
}

private previousM = 0;

private updateView()
{
    console.log('Update View Called');

    // use sampling period to get a smooth transition
    let m = Date.now() - this.deltaMean * 1.5;
    m = Math.max(m, this.previousM);
    this.previousM = m;
    // interpolate position along positions LineString
    const c = this.positions.getCoordinateAtM(m, true);
    if (c) {
        this.view.setCenter(this.getCenterWithHeading(c, -c[2], this.view.getResolution()));
        this.view.setRotation(-c[2]);
        this.marker.setPosition(c);
    }
}

And that's it; my location is successfully retrieved, it is also correct, if I set my marker directly on the map, it will also show up - however if I do it their way, updateView method is never called and it should be called when TileLayer's event 'postrender' is triggered - but that never happens.
Tested it inside a browser, tested it on emulator (Android, iOS), tested in on actual Android device, it's the same. Ofcourse, there's no error in DevTools console so I have basicly nothing to work on.
Any suggestions?


text:
Q: Passing an array by reference as a function parameter in C++ How can I pass an array, declared in main method by reference as a parameter to a function? Also the compiler wants dimentions, but when i give them with variables, the compiler gives errors of invalid integer dimensions of the array, here's the code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int scanV(int Row, int value, int M, int (&tableValues)[])
{
for (int i = 0; i <= M; ++i)
{
    if (tableValues[Row - 1][i] == 1)
    {
        if (i + value <= M)
        {
            tableValues[Row][i+value] == 1;
        }
        if (i - value >= 0)
        {
            tableValues[Row][i-value] = 1;
        }
    }
}
}

int main()
{
int C, B, M;
cin>>C;
int integers[C];

for (int i = 1; i < C; ++i)
{
    cin>>integers[i];
}
cin>>B;
cin>>M;
integers[0] = B;
int tableValues[C][M + 1];
tableValues[0][B] = 1;
for (int i = 1; i < C; ++i)
{
    scanV(i, integers[i], M, tableValues);
}

return 0;
}

A: One simple solution is to use vectors. Consider this simple example:
#include <iostream>
#include <vector>

void f (std::vector<std::vector<int> > &v)
{
    for (int i = 0; i < 3; ++i)
        for (int j = 0; j < 3; ++j)
            v[i][j] = i * 3 + j;
}

int main()
{
    std::vector<std::vector<int> > v (3, std::vector<int> (3, 0));
    f (v);

    for (int i = 0; i < 3; ++i)
        for (int j = 0; j < 3; ++j)
            std::cout << v[i][j] << ' ';
}

In main, a 2D vector of ints (3x3) is created. The constructor shows 3 elements, all initialized with a vector of ints, which are in turn created with 3 elements initialized to 0.
Then, the vector is passed by reference to the function f, which assigns increasing values. When the vector is printed in main, it shows:
0 1 2 3 4 5 6 7 8

As you can see, their use is very similar to normal arrays, but they are actually contained, and provide easy access to a new level of programming using the STL.
In C++11, their use becomes even more familiar. You can assign vectors as follows:
std::vector<int> v0 = {2, 5};
std::vector<std::vector<int> > v1 { {1,2,3} , {4,5,6} , {7,8,9} };

Note that for vectors of multiple dimensions it's a good idea to encapsulate it in a matrix class of some sort with an underlying 1D vector type instead.
Edit:
Here's an example of initializing a 1D and 2D vector to specified elements. As seen above, this is easy in C++11, but if you have an array already, it's still pretty quick.
int a [5] = {1,2,3,4,5}; //normal
std::vector<int> v1 (a, a +5); //create using beginning and ending addresses of a

int b[3][3] = { {1,2,3} , {4,5,6} , {7,8,9} }; //normal
std::vector<std::vector<int> > v2; //empty vector

for (int i = 0; i < 3; ++i) //3 in first dimension
    v2.push_back (std::vector<int> (b [i], b [i] + 3)); //push a vector with the appropriate 3 elements of b onto the back of v2

For going through one element at a time, you can do this:
std::vector<std::vector<int> > v (3, std::vector<int> (3));

for (int i = 0; i < v.size(); ++i) //v.size() == 3
    for (int j = 0; j < v [i].size(); ++j)
        adjustElement (v [i][j]); //replace with what you need

A: std::vectors are the way to go in C++ as variable-length arrays (such as int integers[C];) are forbidden.
I recommend typedefing these to make your code easier to read:
#include <vector>

typedef std::vector<int> row_t;
typedef std::vector<row_t> table_t;

Then you can declare:
void scanV(int Row, int value, int M, table_t& tableValues)

I've made this void since it doesn't return anything.
Your variables in int main() then become:
row_t integers;
table_t tableValues;

Watch out for this line:
            tableValues[Row][i+value] == 1;

You probably meant to assign, rather than to check equivalence!
And please try to pick some more meaningful variable names than B, M, C...


text:
Q: How do I make a button highlighted with a description in an android app? I'm building an android app and I want to highlight a button on the first use. I have seen exactly what I want in other apps, such as the BBC iPlayer app. As shown in the image, there is a wide black circle around the cast button with a description of what is is.
screenshot from phone
How can I implement something similar in my own app?
Thank you very much for any help in advance.

A: This library  will do the trick, here is how you use it :
In your grade :
implement 'com.github.amlcurran.showcaseview:library:5.4.3'

And in your code :
new ShowcaseView.Builder(this)
.setTarget(new ActionViewTarget(this, ActionViewTarget.Type.HOME))
.setContentTitle("title text")
.setContentText("some text")
.hideOnTouchOutside()
.build();


text:
Q: Arithmetic hierarchy I'm curious by Arithmetic Hierarchy. I'm trying to do the following ones:
1) How to show that $\{e\mid \mathrm{dom}(\phi_e)\text{ is recursive}\}$ is $\Sigma_3^0$?
For showing this, I need to really relate it to the characteristic function.
2) $F=\{e\mid \mathrm{dom}(\phi_e)\text{ is finite}\}$ is $\Sigma_2^0$?
Is finite a synonym for recursive?
Thanks

A: Since it seems that you are interested in solving these problems yourself, I'll do a modified version of (2). You can adjust the proof to figure out (2), and that might give you some idea of how to attack (1). Let me just first clarify the notation I am using. $W_{e}$ is the domain of $\phi_{e}$. $T$ is the Kleene T-predicate. $S_{m}^{n}$ is Kleen's $S-m-n$ function, $\mu$ is the minimization operator, and $\# g$ is the code for a function $g$.
Classify in the arithmetical hierarchy the set $A = \{e|W_{e} \mbox{ is finite and nonempty}\}$.
Solution: This set $A$ is given by the $\Sigma_{2}^{0}$ relation
$$ (\exists w \exists c \forall w' \forall c' \forall (n > 0))[T(e,w,c) \wedge (w + n= w' \to \neg T(e,w',c'))] $$
I.e. there exists an input $w$, and a code for computation on $w$, written here as $c$, such that for any other input $w'$ and any other code for the potential convergence of that input, not only does $e$ convergene on $w$ (as witnessed by $c$), but if $w'$ is larger than $w$ (so that there is some $n > 0$where $w+n = w'$), then any $c'$ does not witness convergence on $w'$.
Now, we prove that $A$ is $\Sigma_{2}^{0}$-complete. To see this, let $B$ be the $\Sigma_{2}^{0}$ set $\exists u \forall v Q(u,v,x)$, with $Q$ recursive. Define
$$ g(x,t) = \left\{ \begin{array}{cc}
0 & t = 0\\
\sum_{u \leq t} \mu_v \neg Q(u,v,x) & \mbox{otherwise}
\end{array} \right. $$
If $x \in B$, then for some $u$ and onward, this summation stops converging, as for that $u$ there is no $v$ such that $\neg Q(u,v,x)$ and so there is certainly no least such $v$! However, by construction, $g(x,t)$ always converges for $t= 0$, so the domain of $g$ is non-empty and finite. If $x \notin B$, then for every $u$, there is some $v$ such that $\neg Q(u,v,x)$, and so $g$ is total. Thus, the function
$$f :x \to S_{1}^{1}(\# g,x)$$
reduces $B$ to $A$.


text:
Q: IOS/Objective-C: MakeUILabel Flow to Multiple Lines with Autolayout I am trying to get a UILabel to flow to multiple lines and push the elements below it downwards using autolayout.
Here is my code called in viewwillappear.
self.myLabel.numberOfLines = 0;
self.myLabel.lineBreakMode = NSLineBreakByWordWrapping;
[_myLabel setContentCompressionResistancePriority:1000
               forAxis:UILayoutConstraintAxisVertical];
[self.myLabel setNeedsDisplay];
[self.myLabel layoutIfNeeded];
[self.view setNeedsDisplay];
[self.view layoutIfNeeded];

The UILabel is constrained at the top to the content view and the image below it is constrained to the bottom of the UILabel. The label also has a height constraint of >=21.
On initial load, the label only shows one line.
The weird thing is that after launching a modal VC and the closing it, the label does go to multiple lines but fails to push down the elements below it.
On initial load.

After launching and canceling modal VC

I am wondering if the problem has something to do with timing of laying out subviews but have tried almost every thing.
Thanks in advance for any suggestions.

A: Simple example:

*

*Create a new ViewController.

*Add a button, constrain 40-pts from the top and centered horizontally

*Add a UIView (green view). Constrain centered horizontally, width of 240, and top-space to button of 20.

*Add two labels to the green view.

*Top label, number of lines = 0, leading and trailing constraints of 16, top constraint of 8 (to green superview)

*Bottom label, centered horizontally, top space to Top label of 8, bottom constraint of 8 (to green superview).

*Connect the Top label to @IBOutlet var multiLineLabel: UILabel! in the view controller.

*Connect the button touch-up-inside to the @IBAction func didTap(_ sender: Any) function in the view controller.

*NO CHANGES to priorities.
Run the app. Each tap of the button will add text to the top / multi-line label, and it will "push down" the bottom label, which will, in turn, "push down" the bottom edge of the green view.

class ExpandingLabelViewController: UIViewController {

    @IBOutlet var multiLineLabel: UILabel!

    @IBAction func didTap(_ sender: Any) {

        if let s = multiLineLabel.text {

            multiLineLabel.text = s + " Here is some more text."

        }

    }

}

Once you have that working, you can add other elements to the view. Just make sure you have a "chain" of vertical spacing constraints, with the top-most element constrained to the top of the green superview, and the bottom-most element constrained to the bottom of the green superview.


text:
Q: Normal bundle of a section of a projective bundle Let $X=\mathbb{P}^1$, $E=\mathcal{O}\oplus\mathcal{O}(1)\oplus \mathcal{O}(2)$ and let $Y=\mathbb{P}(E)$. Denote $\pi:Y\to X$ the projection map. There is a section of $\pi$ corresponding to the surjection $E\to \mathcal{O}$. Let $C$ be the image of this section in $Y$. How can we compute the normal bundle of this curve?
The case when $E$ is a rank 2 vector bundle is discussed here.Normal bundle of a section of a $\mathbb{P}^1$-bundle. However, I believe in our case, the argument cannot be directly applied.
Thanks for the help!

A: Let us do this more generally, so that we do not have to look at many cases. Let $E$ be a vector bundle on a scheme $X$ and assume we have an exact sequence $0\to F\to E\to L\to 0$, with $L$ a line bundle. This gives a section $D$ of $\pi:P=\mathbb{P}_X(E)\to X$, the projective bundle. Let us calculate the normal bundle of $D$ in $P$.
We have a natural map $\pi^*F\to \mathcal{O}_P(1)$ and one easily checks that the cokernel is just $\mathcal{O}_D(1)$, which can easily seen to be $L$ (identifying $D$ with $X$). So, we get a surjection $\pi^*(F\otimes L^{-1})\to I_D$, the ideal sheaf of $D\subset P$. Since codimension of $D$ is just the rank of $F$, we see that $D$ is a local complete intersection, coming from a correct rank vector bundle. Thus the normal bundle of $D$ then is just $F^*\otimes L$.


text:
Q: Bad URL check performed on edit, but not on initial question submission? I am not sure if this is a bug or a design error, but I came across this issue on SE Information Security. I assume that the same code is employed across the various SE sites, so I am posting my question here.
I was trying to edit the question, trackback spotted in multple http errors, when I noticed that I could not submit the edit, due to a URL containing mydomain.net, which I had not added.

However, the question was obviously asked and entered with this URL in the body text, so was the same URL check not performed when the question was initially submitted? Here is the question containing the erroneous URL


text:
Q: Showing that $\int_0^\infty \frac{|\cos x|}{1+x} \, dx$ diverges (Baby Rudin Exercise 6.9) Motivated by Baby Rudin Exercise 6.9
I need to show that $\int_0^\infty \frac{|\cos x|}{1+x} \, dx$ diverges.
My attempt:
$\frac{|\cos x|}{1+x} \geq \frac{\cos^2 x}{1+x}$, and then $\int_0^\infty \frac{\cos^2 x}{1+x} \, dx + \int_0^\infty \frac{\sin^2 x}{1+x} \, dx = \int_0^\infty \frac{1}{1+x} \, dx$.
Since the right integral diverges, either or both of the integrals on the left most diverge. Since both diverge (at least I'm inclined to believe), now if I show that $\int_0^\infty \cos^2 x / (1+x) \, dx \geq \int_0^\infty \sin^2 x / (1+x) \, dx $ we'll be done. Here's where I am stuck.

A: You're on the right track. Since $\cos^2(x + {\pi \over 2}) = \sin^2 x$,
$$\int_{0}^{\infty} {\cos^2 x   \over 1 + x}\,dx = \int_{{\pi \over 2}}^{\infty} {\cos^2 (x - {\pi \over 2})  \over 1 + (x - {\pi \over 2})}\,dx $$
$$= \int_{{\pi \over 2}}^{\infty} {\sin^2 x  \over 1 + (x - {\pi \over 2})}\,dx $$
$$> \int_{{\pi \over 2}}^{\infty} {\sin^2 x  \over 1 + x}\,dx $$
Although the integral here starts at ${\pi \over 2}$, the first part will always be finite. So if $\int_{0}^{\infty} {\sin^2 x  \over 1 + x}\,dx $ is
infinite, so is $\int_{{\pi \over 2}}^{\infty} {\sin^2 x  \over 1 + x}\,dx$, and therefore by the above so is $\int_{0}^{\infty} {\cos^2 x   \over 1 + x}\,dx $.

A: $\int_{\pi/2}^{\infty} \frac{|\cos x|}{1+x} =
\sum_{r=0}^{\infty} \int_{\pi/2 + \pi r}^{\pi/2 + \pi r+1} \frac{|\cos x|}{1+x}dx \geq
\sum_{r=0}^{\infty} \int_{\pi/2 + \pi r}^{\pi/2 + \pi r+1} \frac{|\cos x|}{1+(\pi/2 + \pi r+1)}dx =
\sum_{r=0}^{\infty} \frac{1}{1+(\pi/2 + \pi r+1)} \int_{\pi/2 + \pi r}^{\pi/2 + \pi r+1} |\cos x| dx =
 \int_{\pi/2}^{\pi/2 + \pi} |\cos x| dx \sum_{r=0}^{\infty} \frac{1}{1+(\pi/2 + \pi r+1)} =
\infty$
Basically, split the integral up into regions from $[\pi/2, 3\pi/2], [3\pi/2, 5\pi/2] \dotso $ and consider the lowest value of $\frac{1}{1+x}$ in that region. Use the fact that the Harmonic series diverges.
[edit] Fixed.

A: We have
\begin{align}
I_n & = \int_{n\pi}^{(n+1)\pi} \dfrac{\vert \cos(x) \vert}{1+x}dx = 2\int_{n\pi}^{n\pi+\pi/2} \dfrac{\vert \cos(x) \vert}{1+x}dx \geq 2\int_{n\pi}^{n\pi+\pi/6} \dfrac{\vert \cos(x) \vert}{1+x}dx\\
& \geq 2 \int_{n\pi}^{n\pi+\pi/6} \dfrac{1/2}{1+x}dx =\int_{n\pi}^{n\pi+\pi/6} \dfrac{dx}{1+x} > \int_{n\pi}^{n\pi+\pi/6} \dfrac{dx}{(n+2)\pi} = \dfrac1{6(n+2)}
\end{align}
Hence, your integral is bounded below by $\sum_{n=0}^{\infty} I_n$, which clearly diverges.

A: The integrand function is positive and for every $x\in\mathbb{R}^+$ close to an element of $\pi\mathbb{Z}$ we have that $|\cos x\,|$ is close to one. For instance, if the distance between $x$ and $\pi\mathbb{Z}$ is $\leq\frac{\pi}{3}$ we have $|\cos x\,|\geq\frac{1}{2}$. That gives:
$$\int_{0}^{n\pi}\frac{\left|\cos x\right|}{1+x}\,dx = \pi \int_{0}^{n}\frac{\left|\cos(\pi x)\right|}{1+\pi x}\,dx \geq \frac{\pi}{2}\sum_{k=1}^{n-1}\int_{k-1/3}^{k+1/3}\frac{dx}{1+\pi x}$$
and the last sum is greater than:
$$\frac{\pi}{3}\sum_{k=1}^{n-1}\frac{1}{\left(1+\frac{\pi}{3}\right)+\pi k}\geq\frac{H_n-1}{3}.$$
We may also use integration by parts together with the identity:
$$ \int_{0}^{y}|\cos x\,|\,dx =\frac{2}{\pi} y +O(1) $$
that gives:

$$ \int_{0}^{y}\frac{|\cos x\,|}{1+x}\,dx = O(1)+\frac{2}{\pi}\int_{0}^{y}\frac{x\,dx}{(1+x)^2} =\frac{2}{\pi}\,\log(y+1)+O(1).$$


text:
Q: When do you need to use ssh for sending data to a db? This may be a dumb question to most of you but I am lost with understanding when you would need to use ssh(secure shell) to access a remote server. Using a MySQL database do you need to open port 3306 by default or change any settings in MySQL, in order for you to send data to your database via a webpage. What prompted this question is I am working on a webpage with a star rating system and I was having an issue where when you click on a star to rate an item that rating is not being stored in the database. If I manually put ratings in using phpmyadmin the results of those ratings show up on the page, but still when I click the stars to rate it's like I'm not able to use 'INSERT INTO' to put data into the database. From reading around and asking another question on here it led me to believe that I need to set up 'ssh'? to access my testing server to 'open up port 3306'so that I can send data to my database from my page. Does this sound correct to any of you? Here is one of the links where I was getting this idea from = http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html.
If not, does it look like I have something wrong with my code keeping it from working on the code end of things?
<?php $ratingData = Rating::OutputRating('cams');
        if (Error::HasErrors())
        {
        echo Error::ShowErrorMessages();
        Error::ClearErrors();
         }
        else
        {
            echo $ratingData;
        }
        ?>

Above is the code that is placed in my page where I want the rating system to display.
    class Rating
  {
  // Output the Rating information
  // Returns a string of HTML
  public static function OutputRating($varItem)
  {
    // Verify $varItem was provided
    if ($varItem != null && strlen(trim($varItem)) != 0)
    {
      // Information for the Output
      $averageStars = Rating::CalculateAverageRating($varItem);

      // Check to see that the user has not already rated this item
      if (Rating::CheckRatingsByIp($varItem) == 0)
      {
        $classes      = "rating " . Rating::ShowStars($averageStars);

        // Write Output HTML for the Rating Data
        $output  = "\r\n";
        $output .= "
\r\n";
        $output .= "
1
\r\n";
        $output .= "
2
\r\n";
        $output .= "
3
\r\n";
        $output .= "
4
\r\n";
        $output .= "
5
\r\n";
        $output .= "
\r\n";
      }
      else
      {
        $classes      = "rated " . Rating::ShowStars($averageStars);

        // Write Output HTML for the Rating Data
        $output  = "\r\n";
        $output .= "
\r\n";
        $output .= "
1
\r\n";
        $output .= "
2
\r\n";
        $output .= "
3
\r\n";
        $output .= "
4
\r\n";
        $output .= "
5
\r\n";
        $output .= "
\r\n";
      }

It appears to my like $rating data will display one of the 2 html tables above, if the user has not already rated that item it will display the first table.
    function RateItem(varItemId, varRating)
{
  var varOrigClassName = document.getElementById(varItemId).className;
  // Retrieve Ajax Feeds
  new Ajax.Request('RatingSystem/ajax.rate.item.php',
    {
      method: 'post',
      parameters: {item: varItemId, rating: varRating, classes: varOrigClassName},
      onSuccess: ReloadRating,
      onFailure: RatingError
    }
  );
}

Then it will call up the function above

  // Check that the data was sent
  if (sizeof($_POST) == 0
    || $_POST['item'] == null
    || strlen(trim($_POST['item'])) == 0
    || $_POST['rating'] == null
    || strlen(trim($_POST['rating'])) == 0
    || $_POST['classes'] == null
    || strlen(trim($_POST['classes'])) == 0)
  {
    die("You shouldn't be attempting to access this file in this manner.");
  }

  echo Rating::RateItem($_POST['item'], $_POST['rating'], $_POST['classes']);
?>

Which leads to this chunk of code above
public static function RateItem($varItem, $varRating, $varClasses)
      {
        $newClassNames = $varClasses;

        // Verify $varName was provided
        if ($varItem != null && strlen(trim($varItem)) != 0
          && $varRating != null && strlen(trim($varRating)) != 0 && is_numeric($varRating)
      && $varClasses != null && strlen(trim($varClasses)) != 0)
    {

      // Check to see that the user has not already rated this item
      if (Rating::CheckRatingsByIp($varItem) == 0)
      {
        $ipAddress = $_SERVER['REMOTE_ADDR'];

        Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating");
        Database::FetchResults("InsertRating");
        Database::FreeResults("InsertRating");
        Database::RemoveSavedResults("InsertRating");

And then to this function where it will insert that data into my table. I got the code for this star rating system from this source = http://www.search-this.com/2007/06/04/css-the-star-matrix-pre-loaded-part-2/.


text:
Q: MySQL Primary Key with non unique data in fields What is the best way to generate a primary key in the following table structure?  Using MySQL 5.6 community.
PosDateTime varchar(24)
Model varchar(5)
Hour Int(11)
Lat double
Lon double
Wind Int(11)
Pres Int(11)

There will be many instances of each of these fields containing the same value throughout the table, but there will not be a record that is exactly identical (at least one field will be different).  So if I'm not mistaken, I can't use any of these fields as a Primary Key because of duplicates, right??
This table will have up to about 50,000 records.
Currently, before I insert into the table, I check to see if the record already exists, then do the insert if it's not there, it takes a little longer because I do not have a primary key setup.
I'll also need to search on the table to get values.
Should I use a composite primary key using all fields?
This table will not relate to other tables in any way.
Thanks for your input.  Bryan


text:
Q: ReactJS onClick trigger does not fire itself React rookie here!
I've got a fairly simple component here, as a small part of an educational project:
import React, {PropTypes} from 'react';

class CoursesPage extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      course: {title: ""}
    };

    this.onTitleChange = this.onTitleChange.bind(this);
    this.onClickSave = this.onTitleChange.bind(this);
  }

  onTitleChange(event) {
    const course = this.state.course;
    course.title = event.target.value;
    this.setState({course: course});
  }

  onClickSave() {
    alert(`Saving ${this.state.course.title}`);
  }

  render() {
    return (

Courses

Add Course

        <input
          type="text"
          onChange={this.onTitleChange}
          value={this.state.course.title} />

        <button type="submit" onClick={this.onClickSave}>Save</button>

    );
  }

}

export default CoursesPage;

My problem now is that when I click on the save button, the alert dialog does not pop itself up.
Until now I've got two theories about this:

*

*the onClick trigger does not work

*for some reason the alert dialog does not present itself.

Note: I haven't forgotten to bind this in the component class constructor.
Any ideas?

A: In your constructor you are binding incorrectly, there is a typo:
this.onClickSave = this.onTitleChange.bind(this);
should be:
this.onClickSave = this.onClickSave.bind(this);

A: You can use the arrow function, like this:
onClickSave = () => {
    alert(`Saving ${this.state.course.title}`);
}

In this way, you need't bind this in constructor


text:
Q: glyphicon add margin in JSX What is the proper way to add the margin to the glyphicon used in React component?
I tried simple:
 but it doesn't add the required margin.
According to this:
https://zhenyong.github.io/react/tips/inline-styles.html
what should work I believe is  but it gives me error:
Module build failed: SyntaxError: Unexpected token, expected , I tried also adding the styled-component (which we use over the css) like
const glyp = styled.span.attrs({
  className: 'glyphicon glyphicon-exclamation-sign'
)}`
  margin-left: 10px
`

but it doesn't render the exclamation mark sign at all (however takes space).
What's the proper way to do it?

A: Replace "margin-left" with "marginLeft".
From the React docs (which you linked in your question):

Style keys are camelCased in order to be consistent with accessing the
  properties on DOM nodes from JS (e.g. node.style.backgroundImage).


text:
Q: Insert textbox in RadzenDataGrid I have a RadzenDataGrid that has a series of columns with data, one of this is a string that I want to represent as a textbox so the user can input data and then when clicking a "submit"  execute the stored procedure that updated these fields, I don't understand how to do the 2 way binding as it's giving me error when I try to ad the "@bind-Value=@Comments" property.
my datagrid has the following:
<RadzenDataGrid AllowSorting="true" AllowColumnReorder="true"  AllowMultiColumnSorting="true"  PageSize="40" AllowFiltering="true" FilterMode="FilterMode.Simple" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive" Data="@FilteredExpendituresList" TItem="Expenditure" AllowPaging="true" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true">
    <Columns>
        <RadzenDataGridColumn TItem="Expenditure" Property="EmployeeName" Title="Employee Name" Visible=@FilteredExpendituresList.Any(x=>x.EmployeeName is not null) />
        <RadzenDataGridColumn TItem="Expenditure" Property="EmployeeNumber" Title="Employee Number" Sortable="false" Width="125px" Visible=@FilteredExpendituresList.Any(x=>x.EmployeeNumber is not null)  TextAlign="TextAlign.Center"/>
        <RadzenTextBox  @bind-Value=@Comment  Class="w-100" />
    </Columns>
</RadzenDataGrid>

and my object filling receives:
[Parameter]
    public IEnumerable<Expenditure> FilteredExpendituresList { get; set; } = null!;

with the class being:
public class Expenditure
{
    public string EmployeeName { get; set; }

    public string EmployeeNumber { get; set; }

    public string Comment { get; set; }
}

How should I do so the datagrid can have the 2 way binding and have the Comment field that is input being passed from the textbox to the object?

A: You need to use Template:
<RadzenDataGrid AllowSorting="true" AllowColumnReorder="true" AllowMultiColumnSorting="true" PageSize="40" AllowFiltering="true" FilterMode="FilterMode.Simple" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive" Data="@FilteredExpendituresList" TItem="Expenditure" AllowPaging="true" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true">
    <Columns>
        <RadzenDataGridColumn TItem="Expenditure" Property="EmployeeName" Title="Employee Name" Visible=@FilteredExpendituresList.Any(x => x.EmployeeName is not null) />
        <RadzenDataGridColumn TItem="Expenditure" Property="EmployeeNumber" Title="Employee Number" Sortable="false" Width="125px" Visible=@FilteredExpendituresList.Any(x => x.EmployeeNumber is not null) TextAlign="TextAlign.Center" />

        <RadzenDataGridColumn TItem="Expenditure">
            <Template Context="data">
                <RadzenTextBox @bind-Value="@data.Comment" Class="w-100" />
            </Template>
        </RadzenDataGridColumn>

    </Columns>
</RadzenDataGrid>

Documentation

A: You can use the Template RenderFragment<T> inside a RadzenDataGridColumn if you have a global save.
If you want to use the EditTemplate RenderFragment<T>, you need to tell the Data Grid component that you want to edit by using a RadzenDataGrid<T> referenced object and call EditRow(T item). It will then go into an edit state.
Within a RadzenDataGridColumn you need to then add an EditTemplate tag for the RenderFragment<T>.
Refer to their documentation for detailed examples: https://blazor.radzen.com/datagrid-inline-edit


text:
Q: How to disable current and future month in Java.util.Calendar How to disable current and future month in java.util.Calendar?
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MONTH, -1);
    dateBox.setValue(calendar.getTime());

Here dateBox is id for the input type DateBox in UI.


text:
Q: Can't get submit button work I am new to java and trying to learn how to add data into database.
I cannot make my submit button work. I am getting error of "target unreachable". I am using hibernate and phpMyAdmin.
As I said I new to this. Please let me know if I am missing information that needed.
Instead of calling class in my submit button should I create private String method for the text boxes?
I am confused.
Thanks a lot for your help.
additem.xhtml

<h:body>
    <ui:composition template="template.xhtml">

        <ui:define name="content">

Add a New Item

            <h:form>

                <h:outputLabel value="Item Number" />Item Number:

                <h:outputLabel value="Title" />Title:

                <h:outputLabel for="type" value="Type">Item Type:

                        <f:selectItem itemValue="" itemLabel="Select One" />
                        <f:selectItem itemValue="book" itemLabel="Book" />
                        <f:selectItem itemValue="magazine" itemLabel="Magazine" />
                        <f:selectItem itemValue="movie" itemLabel="Movie" />
                        <f:selectItem itemValue="music" itemLabel="Music" />

                </h:outputLabel>

                <h:outputLabel value="Status" />Status:

            </h:form>
        </ui:define>
    </ui:composition>
</h:body>

AddLibraryItem.java
@Named
@ManagedBean
@Scope("request")
public class AddLibraryItem  {

    //no arg constructor
    public AddLibraryItem(){

    }

    @Inject private LibraryItem libraryItem;
    @Inject private ILibraryService libraryService;

    public String addItem(){

        //return value
        String returnValue = "success";

        //assign values
        libraryItem.setStatus("CHECKED_IN");

        //add to library
        try {
        libraryService.add(libraryItem);

        displayMessage("Success","Item added");
        }catch (Exception e){
            displayMessage("Error", e.toString());
            return "fail";
        }
        return returnValue;
    }

    //Getters and Setters
    public LibraryItem getLibraryItem() {
        return libraryItem;
    }

    public void setLibraryItem(LibraryItem libraryItem) {
        this.libraryItem = libraryItem;
    }

    public ILibraryService getLibraryService() {
        return libraryService;
    }

    public void setLibraryService(ILibraryService libraryService) {
        this.libraryService = libraryService;
    }

    //method to display messages
    private void displayMessage(String title, String message){
        //get faces context
        FacesContext currentInstance = FacesContext.getCurrentInstance();
        //message to show
        FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, title, message);
        //display the message
        currentInstance.addMessage(null, fm);
    }

}


text:
Q: Does passing a large component around actually use a lot of server resources? I've made an Avatar component for my gaming page, which since it is required for gaming I've put on the gaming section's layout page.
The Avatar control is quite complex, with several modes for choosing avatars from a gallery, selecting a color palette, and then displaying various versions of the chosen character (animated full-size svg, portrait thumbnail, etc.)
My question is this: if I pass this component as a Cascading Parameter from the layout, am I actually persisting and passing entire rendered components, potentially 200Kb or more, or just a reference to the class with whatever variables I've set, with it only "blowing up" when the component actually needs to be rendered?  (I'm guessing the latter)
Or, more importantly, what tools / steps would I need to use to determine for myself what's going on under the hood?

A:
am I actually persisting and passing entire rendered components

No, there is no need for that

or just a reference to the class

Yes, for the C# part it's just a reference (same size as a long).

[...] "blowing up" when the component actually needs to be rendered?

that depends a little. You have a shadow DOM that is rebuild (where needed) and the differences are applied to the actual DOM by JavaScript.
When you have large changes that could be I/O intensive for Blazor server, but SignalR is quite efficient.


text:
Q: Problem with python croniter with all asterisks I have made a script in python to perform FTP transfers that will run in crontab every minute. The script queries the mysql database and translates the cron language with the croniter library. If the current date and time match the programmed date, the ftp transaction will be performed.
It seems to work correctly except when the programming is cron is minutes and hours in asterisks. With the date it seems that there is no problem.
The crontotime function receives in the variable "programmed" the time and date programmed in cron language: "* * * * *" or "05 17 * * *" and translates it to date and time.
https://crontab.guru/ for help
Thanks.
 def crontotime(self,programada):
        crontask = croniter.croniter(programada)
        nextcrontask = crontask.get_next(datetime.datetime).strftime("%Y-%m-%d %H:%M")
        return nextcrontask

Results: If there are no defined minutes and hours, an error appears
========================================================
Now:                    2019-03-25 16:56
Scheluded:   #* 16 * * *#   2019-03-25 16:00
========================================================
Now:                    2019-03-25 16:56
Scheluded:  #56 16 * * *#   2019-03-25 16:56
========================================================
Now:                        2019-03-25 17:05
Scheluded   #* * * * *#     2019-03-25 16:06  ERROR
========================================================
Now:                    2019-03-25 17:05
Scheluded:  #05 17 * * *#   2019-03-25 17:05
========================================================

A: class Crontask(object):

def crontask(self,datoscron,ahora):
    for row_task in datoscron:
        programada = (' '.join(i for i in row_task[2:7]).strip())
        nuevatarea = Crontask().crontotime(programada)
        if nuevatarea == ahora:
            FTPtask().ftptask(row_task)
            LogTransfer().log_tareas(row_task)
        else:
            print("========================================================")
            print("///////////////// NO TRANSFER /////////////////////////")
            print("========================================================")
    return

def crontotime(self,programada):
    crontask = croniter.croniter(programada)
    nextcrontask = crontask.get_next(datetime.datetime).strftime("%Y-%m-%d %H:%M")
    return nextcrontask

========================================================
Now:                        2019-03-26 11:57
Scheluded:   #* * * * *#    2019-03-26 10:58
For example: scheluded is * * * * * and time is 2019-03-26 11:57, croniter return 2019-03-26 10:58 1 more minute, then task never runs.


text:
Q: My Travis keeps erroring All tests are passing, but in in the end, it gives
The command "make html" failed and exited with 2 during .
This happens since I started using cache.
Initially I just had
cache:
  apt: true
  directories:
    - $HOME/virtualenv/python2.7/lib/python2.7/site-packages
    - node_modules

in travis.yml
but I also added - $HOME/virtualenv/bin and cleared my cache in master branch before I ran another build. It passed once, but then keeps failing. I cleared the cache multiple times but no avail.


text:
Q: Android. Hide SupportActionBarin the top I have hided SupportActionBar like this:
requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Objects.requireNonNull(getSupportActionBar()).hide();

before setContentView(R.layout.activity_main);
my activity theme android:theme="@style/AppTheme"
but i have this line in the top

requirement!
my listener in navigationView menu items dont work if i do like this:
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

so i need hide toolbar only programmaticaly
UPD
Activity:
public class MainActivity extends AppCompatActivityimplements NavigationView.OnNavigationItemSelectedListener, DrawerLayout.DrawerListener {

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

  getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getSupportActionBar().hide();

        setContentView(R.layout.activity_main);

/////code

}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/activity_main_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/view_nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

activity_main_container
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/actionbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.timecontrolapp.activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:theme="@style/AppTheme.AppBarOverlay">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="90dp"
                android:layout_height="?attr/actionBarSize"
                android:layout_alignParentStart="true"
                android:background="?attr/colorAccent"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

            <RelativeLayout
                android:id="@+id/rlt_middle"
                android:layout_width="wrap_content"
                android:layout_height="?attr/actionBarSize"
                android:layout_toStartOf="@+id/lnr_timer"
                android:layout_toEndOf="@+id/toolbar">

                <TextView
                    android:id="@+id/txt_bar_title"
                    android:layout_width="wrap_content"
                    android:layout_height="?attr/actionBarSize"
                    android:layout_centerInParent="true"
                    android:gravity="center"
                    android:text="12 November 18"
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/fontLarge"
                    tools:ignore="SpUsage" />

                <RelativeLayout
                    android:id="@+id/rlt_search_container"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:visibility="gone">

                    <EditText
                        android:id="@+id/edt_search"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/dp40"
                        android:layout_centerInParent="true"
                        android:background="@drawable/edit_search"
                        android:gravity="center_vertical"
                        android:imeOptions="actionDone"
                        android:maxLength="25"
                        android:paddingStart="35dp"
                        android:paddingEnd="35dp"
                        android:singleLine="true"
                        android:textColor="@color/colorWhite"
                        android:textCursorDrawable="@null" />

                    <RelativeLayout
                        android:id="@+id/rlt_voice"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_centerVertical="true">

                        <ImageView
                            android:layout_width="22dp"
                            android:layout_height="23dp"
                            android:layout_marginStart="@dimen/dp10"
                            android:layout_marginLeft="@dimen/dp10"
                            android:layout_marginTop="@dimen/dp10"
                            android:layout_marginEnd="@dimen/dp10"
                            android:layout_marginRight="@dimen/dp10"
                            android:layout_marginBottom="@dimen/dp10"
                            android:background="@drawable/rounded_button_white"
                            android:padding="3dp"
                            android:scaleType="fitCenter"
                            android:src="@drawable/icon_voice"
                            android:tint="@color/colorAccent" />
                    </RelativeLayout>

                    <RelativeLayout
                        android:id="@+id/rlt_cancel"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_alignParentEnd="true"
                        android:layout_centerVertical="true">

                        <ImageView
                            android:layout_width="22dp"
                            android:layout_height="23dp"
                            android:layout_marginStart="@dimen/dp10"
                            android:layout_marginLeft="@dimen/dp10"
                            android:layout_marginTop="@dimen/dp10"
                            android:layout_marginEnd="@dimen/dp10"
                            android:layout_marginRight="@dimen/dp10"
                            android:layout_marginBottom="@dimen/dp10"
                            android:background="@drawable/rounded_button_white"
                            android:padding="3dp"
                            android:scaleType="fitCenter"
                            android:src="@drawable/icon_cancel"
                            android:tint="@color/colorAccent" />
                    </RelativeLayout>
                </RelativeLayout>
            </RelativeLayout>

            <LinearLayout
                android:id="@+id/lnr_timer"
                android:layout_width="90dp"
                android:layout_height="?attr/actionBarSize"
                android:layout_alignParentEnd="true"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/txt_bar_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="00:00"
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/fontExtra"
                    tools:ignore="SpUsage" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/time_elapsed"
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/fontSmall"
                    tools:ignore="SpUsage" />
            </LinearLayout>
        </RelativeLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/activity_main_content" />
</android.support.design.widget.CoordinatorLayout>

activity_main_content
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/view_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.timecontrolapp.activities.MainActivity"
    tools:showIn="@layout/activity_main_container">

</RelativeLayout>


text:
Q: What is perfect elimination bipartite graph? I am not a Maths guy, and  I was required to read a paper on Graph Theory.
Now after few pages the definition of perfect elimination bipartite graph comes up, no matter how hard I try grasp the meaning I could not put it together.
Heres the definition

I understand individual parts but couldn't put it together. Too many abstract symbols and I couldn't find anything google too.
Can anyone please what it is actually in simpler words with example.
Thank you.


text:
Q: Have user input into JTextField in for loop in Action Listener I'm decently new to Java. I want the user to be able to input 4 different inputs separately by clicking submit. I'm using a for loop to count, but I do not know how to have the user input their answer multiple times. The for loops just repeats all at once. I'm using arrays to hold the user's answers.  Here is part of my code. If you have questions or need more explanation I will def. explain more
private void Question1()
{
    int count = 1;
            QuestionsPanel.add(new JLabel(Q1.getQuestion()));
    QuestionsPanel.add(new JLabel(Arrays.toString(mans1)));

    AnswerField = new JTextField(10);
    AnswerPanel.add(AnswerField);

    Submit = new JButton("Submit");
    AnswerPanel.add(Submit);
    Submit.addActionListener(this);

}

public void actionPerformed(ActionEvent e)
{
    if ((e.getSource() == Submit) && count == 0)

    {
        int value = Integer.parseInt(AnswerField.getText());

        for (int i = 0; i < 4; i++)
        {

            if (value == -1) break;
            ans[i] = value - 1;
            AnswerField.setText("");

        }

A: This doesn't work because you placed the loop in the ActionListener, which is executed once on button click.
What you should do is to keep a counter of the current answer somewhere
int count = 0;

public void actionPerformed(ActionEvent e) {
  if ((e.getSource() == Submit) && count < 4) {
    int value = Integer.parseInt(AnswerField.getText());

    if (value == -1) break;
    ans[count++] = value - 1;
    AnswerField.setText("")
  }
}

In this way the loop is implicitly managed by the actionlistener: everytime you press submit count is incremented by 1 and the correct answer is placed inside the array. Of course you should do something, like disabling the submit button, upon submitting the fourth answer.


text:
Q: SMS уведомление пользователей Хотел спросить, может есть информация о каких-либо бесплатных компонентах или проектах, в которых можно отправлять sms уведомление для пользователей. Пользователей порядка 50к, но не все будут получать уведомление, где-то по 100 сообщений в день от всего проекта.

A: *

*смс-ки рассылает сервер оператора мобильной связи

*у этого сервера есть протокол обмена данными, обычно - SMPP

*доступ к серверу оператора для массовой рассылки смс/ммс можно получить у оператора, заключив соответствующий договор

*пишется обработка, или используются готовые решения (kannel) которые буду массово слать смс по заранее подготовленным базам

*смс-ки в конечном итоге таки стоят денег, немного - но стоят

в вашем случае логичнее договорится с каким-нибудь оператором рынка мобильных рассылок, чтобы работать напрямую с оператором нужны миллионные объемы
A: Ничего бесплатного для работы с gsm нет, так же как и бесплатного интернета который можно было бы использовать в коммерческих целях, тоже нет.
A: Так же можно подключить 3g модем к серверу. И через него отправлять смс. А стоимость смс, согласно тарифу.


text:
Q: PHP -> TCP to NODE.JS vs PHP -> HTTP to NODE.JS I currently use TCP the method described here:
Connection between Node.JS and PHP via UNIX Socket - EPIPE write error
And I see other people are using HTTP instead here:
Sending messages from PHP to Node.js
Besides the fact the TCP implementation has slightly less code, and no cURL, are there any disadvantages to using the TCP method?
Such as queuing problems for many simultaneous requests or I have no idea, so I'm asking those with experience with this kind of thing if there are any pro's and con's involved between these two implementations of PHP to NODE.JS.
Answers appreciated - silly comments not.


text:
Q: dlib library is not installing on gcloud I'm deploying a flask application on google cloud run but I'm facing issue regarding installation on dlib library. dlib started to install then it goes to loop to build dlib wheel then after some time it throws an error. CMake libray is already installed successfully.
Here is the Dockerfile
# Use the official lightweight Python image.
# https://hub.docker.com/_/python
FROM python:3.8-slim

# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./

# Install production dependencies.
#RUN apt-get update && apt-get install -y cmake
#RUN sudo apt-get update && sudo apt-get install build-essential
#RUN apt-get update && apt-get install build-essential cmake

RUN apt update && apt install -y gcc clang clang-tools cmake python3
RUN pip install dlib

RUN pip install --no-cache-dir -r requirements.txt
RUN pip install gunicorn

# Run the web service on container startup. Here we use the gunicorn
# webserver, with one worker process and 8 threads.
# For environments with multiple CPU cores, increase the number of workers
# to be equal to the cores available.
# Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling.
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

Here is the error
Building wheels for collected packages: dlib, face-recognition-models
  Building wheel for dlib (setup.py): started
  Building wheel for dlib (setup.py): still running...
  Building wheel for dlib (setup.py): still running...
  Building wheel for dlib (setup.py): still running...
  Building wheel for dlib (setup.py): still running...
  Building wheel for dlib (setup.py): still running...
  Building wheel for dlib (setup.py): still running...
  Building wheel for dlib (setup.py): still running...
ERROR
ERROR: build step 0 "gcr.io/cloud-builders/docker" failed: step exited with non-zero status: 2

A: Using gcloud command: gcloud run deploy when deploying your application to Cloud Run will allow you to build image in Cloud Build for only 10 minutes. When the image is successfully built, it will deploy to Cloud Run automatically, but if it is fails, you will receive timeout error or Cloud Run deployment error:

Deployment failed
ERROR: (gcloud.run.deploy) DEADLINE_EXCEEDED

According to this link, the dlib and necessary package will be installed for 5-10 minutes which lead you to fail.
HOW TO FIX AND DEPLOY?
You should manually create the container image and deploy it to Cloud Run.

*

*Create Docker Repository in Artifacts registry:

gcloud artifacts repositories create AR-REPO-NAME --repository-format=docker \
--location=us-central1 --description="Docker repository"

*

*Replace the AR-REPO-NAME to your preferred Docker Repository name.

*Build a Docker image with --timeout flag to extend the total build time of the image:

gcloud builds submit --tag us-central1-docker.pkg.dev/PROJECT-ID/AR-NAME/IMAGE-NAME \
/path/to/your/application --timeout=30m

*

*Replace the PROJECT-ID to your Cloud Project ID

*Replace the IMAGE-NAME to your preferred image name

*Replace the /path/to/your/application to your application and Dockerfile directory

*Deploy the container image to Cloud Run:

gcloud run deploy SERVICE-NAME --image IMAGE_URL

*

*Replace the SERVICE-NAME to your preferred Cloud Run Service name

*Replace the IMAGE_URL to your container image URL in your Artifacts Registry, for example:

gcloud run deploy SERVICE-NAME \
--image us-central1-docker.pkg.dev/PROJECT-ID/AR-REPO-NAME/IMAGE-NAME


text:
Q: Issue with overflow and width I have a container that have a bunch of <a> tags and they are all inside a container that have 465px in width. that container is named AssetBrowsercolumn-right and is inside in container that have overflow-y auto and a width of 760px that is named Container.  Container have also AssetBrowsercolumn-right.
The problem I have is that when the scrollbar is visible the width of the AssetBrowsercolumn-right is correct but when the scrollbar is not displayed there is a space. I cant figure out a way to fix this. Beacuse if I add 15px to the AssetBrowsercolumn-right the space is gone but then when the scrollbar is displayed it gets messed up..
it seems that when scrollbar is visible it adds 10-20px. and when its not displayed 10-20px is removed.
Is there any good fix for this?
#container{
height:500px;
width: 760px;
overflow-y:auto;
}

.assetbrowserColumn {
    float: left;
    width: 280px;

}

.assetbrowsercolumn-right {
    float: right;
    width:465px;
}

.link-items {
padding-top: 4px;
padding-bottom: 4px;
display:block;
padding: 5px 5px 5px 34px;
}

Any kind of help is appreciated
JSFIDDLE
Remove some A tags that are inside assetbrowserColumn in the jsfiddle to see what I mean.

A: Fiddle would be helpfull, but you could try this:
.assetbrowsercolumn-right {
    float: right;
    width: 100%;
    max-width:480px;
}

EDIT
You can set dynamic width like this to solve it:
.assetbrowsercolumn {
    float: left;
    width: 35%;
   border: 0px solid black;
}

.assetbrowsercolumn-right {
    float: right;
    width:65%;
       border: 0px solid black;
}