text:
Q: Microservices database migration with existing foreign key We have a rails application where we need to run a database migration (to add transactional reference data) which refers to a primary key on another independent service. The only way I can think of doing this as of now is adding a http call in the migration to get the key from the other service. Was wondering if there was a cleaner way of achieving this ?

A: Sometimes you just have to get a console and do the work. What's the philosophical point of a migration? To change the database in a replicable/repeatable way, i.e., if you were to re-provision the app or instigate a new development environment. In this case? I'd say screw it, just run a task on production outside a migration.
Maybe, have it make background jobs, so if one fails due to the external service being down, your whole task doesn't restart.


text:
Q: git branch and merging I am tryin gto understand branches in git.I have worked with SVN so trying to get the directory structures
i create a  git main repo with
mkdir git_repo
cd git_repo
git init --bare
cd ../
git clone git_repo new_clone
cd new_clone
touch test.txt
git add test.txt
git commit test.txt
git push origin master
//So now the contents are in git_repo
git branch new_branch
git branch
/*master
*new_branch is the output */
git checkout new_branch
//Switched to branch 'new'

My question is that
1.How to switch back to new_clone
2.how to push files to new_repo from the branch
3.How can i see the diff in files beteen the new_branch and new_clone
4.How can i push the files to git_repo
5.When i do use merge in this case
6.How to list the files in new_branch and new_clone separately
Can any one please explain these with the examples.
Thanks..

A: *

*You cannot "switch back to new_clone", because new_clone is not a branch. You have a repository with two branches, named master and new_branch. What does "switch to [repository path]" mean?

*I think what you mean to ask here is "how do I retrieve commits made to git_repo into my working copy in new_clone?" The answer is you do a git fetch to retrieve the changes, and git merge or git rebase to incorporate them locally (or git pull to do both in one operation).

*git diff new_branch new_clone. For a particular file, git diff new_branch:path/to/file new_clone:path/to/file. For the diff in terms of changesets, not patch format, use git log --oneline --left-right new_clone...new_branch or the like.

*git push, as you already did.

*Use merge when you want to incorporate one branch's changes and history into another branch. Merging is a very powerful concept, but you should already be familiar with the basic idea from SVN - git tends to work better, though, because it takes better account of shared ancestry between the revisions to be merged even in a 2-way.

A: GIT is different from SVN - it is a distributed version control system. Don't think of it like SVN with a server and multiple clients, rather it helps to think of it in terms of peer to peer.
Let me first answer your questions:

*

*Switching back:
There is no question of switching back to new_clone - new_clone is a repository and not a branch, the branches are master and new_branch as is listed by git branch. If you want to switch to master (the original branch) use: git checkout master or in general git checkout <branch-name>.

*You can use git push origin new_branch to push a branch to origin.

*As described in (1) there is no new_clone branch. Use this: git diff new_branch master

*See (2)

*You don't use merge in this case. But let's say you have 2 working copies and you want to share code among them, you can use git merge to merge changes from one copy into another.
Let us look at a full run to help you understand all the concepts. Alice and Bob are 2 users (peers) who are using GIT:
Create 2 users Alice and Bob
sudo adduser alice
sudo adduser bob

Login as Alice and configure
su alice
git config --global user.name "Alice"
git config --global user.email alice@example.com

Login as Bob and configure
su bob
git config --global user.name "Bob"
git config --global user.email bob@example.com

Alice creates a GIT repository
mkdir project
cd project/
git init
echo "Some text" > test
git add test
git commit -m "Adding test"
git status

Bob clones it, edits and commits changes
cd ~
git clone /home/alice/project myclone
cd myclone/
git log # See the changes from Alice
echo "Some text - edited by Bob" > test
git commit -m "Making changes to test" -a
git diff

Alice merges changes from bob
git remote add bob /home/bob/myclone
git fetch bob
git branch -a # To list
git log -p master..bob/master
git merge --no-ff bob/master # Merge changes from Bob

Alice makes changes on an experimental branch and then commits it:
git branch experimental
git branch # To list
git checkout experimental
git branch # To list
echo "Some text - edited by Bob, further edited by Alice" > test
git commit -m "Further modifying test" -a
git checkout master
git log -p master..experimental
git merge --no-ff experimental
git branch -d experimental # To delete the branch

Bob pulls the changes:
git pull

Note that there is no central server here, Alice and Bob are peers.
More details here:

*

*http://book.git-scm.com/3_distributed_workflows.html

*http://nvie.com/posts/a-successful-git-branching-model/

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ weird cin.ignore behaviour i'm trying to build a sample app for my students which should demonstrate how to enter multiple c-strings using cin.getline and cin.ignore but i'm getting weird results. in my code below there are two commented cin.ignore statements. if i uncomment first one then in runtime it is required to press Enter twice to input the first string and only once to input the second. if i uncomment second one instead then both strings inputted with one Enter but second string somehow lose first letter.
#include <iostream>
using namespace std;

struct Unit{
    int uid;
    char* name=new char[50];
    char* shname=new char[10];
};

int main() {
    Unit u;
    cout << "Record number: ";
    cin >> u.uid;
    cout << "Unit name: ";
    cin.ignore();
    cin.getline(u.name,50);
    //cin.ignore();
    cout << "Unit short name: ";
    //cin.ignore();
    cin.getline(u.shname,10);
    cout << "Record number: " << u.uid << endl
         << "Unit name: " << u.name << endl
         << "Unit short name: " << u.shname << endl;
    return 0;
}

i cant quite understand what am i doing wrong

A: cin.ignore() ignores only one character, no matter if it is white space or not.
I guess you want to ignore until the first non-white character.
For example:
while (iswspace(cin.peek()))
   cin.ignore();

And as said in the comment, getline will read also the end of line. you need to ignore it after use the stream operator (>>) because then it stop before the end of line and the first getline will read just the new line.

A: You'll need to understand why it is sometimes necessary to use ignore()! The built-in  formatted input pperations (operator>>()) use any space chararcter as a separator which is not extracted. On the other hand, getline() scans the input for the first occurance of the newline character (by default '\n') and stores and stores and extracts all those characters. It finishes with extracting the newline character (the variation you are using also has a size constraint; I'd recomend using std::string with the non-memeber std::getline()).
The net effect is that after a formatted input function the next character in the buffer is a separating space. When intaracting with a user using the standard input it is most likely a newline character which causes a following getline() to immediately finish. Thus, it is common that these space characters are extract, preferably using in >> std::ws rather than in.ignore() to deal with other stray space characters. After using getline() there is generally no need to skip any characters as the newline is already extracted. Put differently: the commented ignore()s are best removed.
Also, make sure you always verify the input was successful after trying to read! The vaste majority of errors with inout are due to no checking (as is the case in the code you posted) or checking before the input operations. Learning to check afterwards is sufficiently important that the argument of "making the code simple" doesn't hold: it isn't making the code simple but plain wrong!


text:
Q: Check the value of an attribute in magento I have a custom attribute yes/no and what i want to do is on the product detail page of my magento site show or hide an image based on wether the value of this attribute is yes or no
my custom attribute is is_real_wood

A: If your attribute was called, say, show_image then you read it back like this:
<?php if ($_product->getShowImage()) : ?>
    <img .... /><!-- PUT WHATEVER ELSE HTML YOU NEED HERE -->
<?php endif; ?>


text:
Q: Why am I getting some paddingLeft kind of gap in LinearLayout despite of setting its padding to 0? Following is the layout of the Toolbar I am using, but I am getting a strange gap towards the left side of the first ImageView (the gap between the left edge of the screen and the right edge of the left-ImageView). The question is why, and how can I get rid of it?

I even tried to set a android:padding="0dp" to LinearLayout and a android:layout_margin="0dp" to the relevant ImageView, but that doesn't seem to work. I am using Material Design if that matters.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#F4FA58"
    android:elevation="4dp" >

    <LinearLayout
        android:id="@+id/appBar_linearLayout"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:radius="25dp"
        android:background="#B45F04"
        android:padding="0dp" >

        <ImageView
            android:id="@+id/appBar_imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_action_back"
            android:contentDescription="@string/appBar_imageView_contentDescription"
            android:layout_margin="0dp" />

        <include
            android:id="@+id/appBar_searchView"
            layout="@layout/searchview" />

        <ImageView
            android:id="@+id/appBar_imageViewOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_action_cancel"
            android:contentDescription="@string/appBar_imageViewOne_contentDescription" />

    </LinearLayout>

</android.support.v7.widget.Toolbar>

A: I've seen this problem before, and figured out how to fix it by doing the following:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#F4FA58"
    android:elevation="4dp"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp" >

Notice the contentInsetLeft I added. There is a default 16dp padding set by the toolbar you remove by adding the 0dp. Hope this helps, let me know if it doesn't work!
EDIT: Also, check out this link I found from someone else's question Android API 21 Toolbar Padding


text:
Q: How am I able to telnet to HTTP port 80? After searching in google I found out that we can telnet to web-server to its http port and use GET to retrieve a html page.
For ex:
$ telnet web-server-name 80

But I am not able to understand how is this possible ?
I thought that if port 80 is for http server, then port 80 will only listen for http requests. But how am I able to telnet to an HTTP port ?
Aren't telnet and HTTP two different protocol ?

A: telnet is a tool that can connect to any tcp port.
By default, it connects to the telnet port (23), but you can tell it to connect to the http port (80) or smtp port (25) or whatever instead.
You need to know how to "speak" the protocol that the remote server is listening for on that port, though.
For example, if you want to get the headers of a web site (domain names etc changed to protect the guilty):
$ telnet www.example.com 80
Trying xxx.xxx.xxx.xxx...
Connected to www.example.com.
Escape character is '^]'.
HEAD http://www.example.com/ HTTP/1.0

HTTP/1.1 200 OK
Date: Fri, 30 Oct 2015 09:28:58 GMT
Server: Apache/2.4.17 (Debian)
Last-Modified: Sun, 14 Nov 2010 06:30:26 GMT
ETag: "843-494fd75830480"
Accept-Ranges: bytes
Content-Length: 2115
Vary: Accept-Encoding
Connection: close
Content-Type: text/html

Connection closed by foreign host.

The HEAD line is what i typed into the connection.  Note that the http protocol requires you to send a blank line to indicate the end of your HEAD or GET or whatever request.  That's the blank line immediately after the HEAD request.

A: The initial negotiation for both protocols uses text-commands, so you can connect and start to enter commands.  This is true of other old protocols such as SMTP, and telnet has long been used to troubleshoot connections to the respective services.
For example

*

*HTTP Help: How to test HTTP using Telnet

*XFOR: Telnet to Port 25 to Test SMTP Communication
The protocols are independent of the port on which they communicate.  Almost all implementations can be configured to listen on any port.
Some protocols (such as HTTPS) do not use text commands for negotiation.  You can however (usually) connect to the port on which the server listens, but do nothing useful.

A: Some of your understanding is correct and some isn't. Port 80 is generally reserved for HTTP, but that's just a convention; any program can listen on any open port on the system. If there's a webserver listening on port 80 on the system you're connecting to, you do need to use HTTP to communicate with it.
telnet isn't a protocol at all, it's a program that lets you send raw text to any host on any port. The remote host has no idea what program is connecting to it; all it can see are the packets being sent to it. Any program that sends packets that comply with the protocol the remote host is expecting will work, so you can use telnet to communicate over any text-based protocol.
You sent something along the lines of GET /path/to/a/file HTTP/1.1, which is a valid HTTP 1.1 command and looks the same as a request that would be sent by a web browser, so it works fine.

A: Congratulations, you've just delved into the concept of networking layers by realizing that ports and protocols are not directly connected with each other. As others are saying, telnet can be used to connect to any TCP port. However to understand why this is possible you need to understand a bit about networking layers. If you've ever heard of the OSI 7 layer model this is what allows you to use telnet to connect to another port.  Although on the Internet, they only concern themselves with 4 of the layers and its called the Internet Protocol Suite.  Without layers of networking, each program would not only need to understand its own protocol, but would have to define its own IP addressing scheme and port system, which means each router would need to understand how to route these schemes and different protocols would be much harder to learn and diagnose. To put it simply, the Internet wouldn't work nearly as well without layers.
What you are concerned with are the transport layer and the application layer. At the transport layer we have Internet protocols like TCP and UDP with port numbers ranging from 1 to 65535 on each.  At the application layer we have protocols such as HTTP, SMTP and DNS. Usually each Internet standards document that defines a protocol specifies a default TCP or UDP port that the protocol should use by default. Such as TCP port 80 for HTTP,  TCP port 25 for SMTP, UDP port 53 for DNS and TCP port 23 for Telnet. The telnet program actually speaks the TELNET protocol, which is a standard protocol, but mostly an ancient one by current standards. Because its protocol sequences are made from 8-bit characters, you rarely see the protocol itself and its mostly transparent when compared with other more modern protocols like HTTP and SMTP that use human visible words in ASCII such as GET, POST, HELO, LOGIN, etc.
Because its protocol isn't generally visible, telnet made for a decent tool for connecting to other TCP ports and allowing the user to type in protocols manually. Some network administrators use this technique in order to diagnose problems with servers.  However because the telnet program still has its own protocol and may send extra bits of data sometimes, you can still experience problems with this technique. When you use telnet you really are "making a connection" at the application layer as well as the transport layer. It just happens that other application layer protocols may work ok through it for most diagnostics and won't interfere with the telnet protocol. There is a better program for doing this through called nc (Net Cat. It gets its name from being a Network based version of the cat command).
$ nc www.stackexchange.com 80

The nc program doesn't speak any application layer protocol and when you make a connection with it you are "making a connection" only at the Internet layer (IP address) and Transport layer (TCP or UDP). What that means is that you control what application layer protocol is used. Almost anything is fair game, even binary protocols. This also allows you to do useful things like transfer files without them being corrupted and listen on ports for incoming traffic:
nc -l 9000 < movie.mp4  (Your friend runs this)

nc friends.computer.hostname 9000 > movie.mp4  (you run this)

And then movie.mp4 is transfered over the network using no application layer protocol (such as FTP) at all. The application protocol is actually your friend telling you that they are ready for you to run your command.
nc can also handle UDP packets and UNIX-domain sockets. Using it to listen can also be interesting.
nc -l 12345

Now in your web browser visit http://localhost:12345/ and in your nc session you should see the browser's GET / HTTP/1.1 request.  At this point you can type something in and press Ctrl-D and it should show up in your browser in plain text (If you want HTML to show up, you have to send it back the proper HTTP protocol response followed by HTML code).
Sometimes, programs which natively speak one protocol like HTTP can connect to other ports that are meant for a different protocol. You typically can't do this in a GUI browser anymore because they have restricted them from connecting to some ports, but if you use a program like curl to connect to port 25 (SMTP for sending mail) you'll probably see a couple of errors about breaking protocol.
$ curl yourispsmtpserverhost.com:25
220 yourispsmtpserverhost.com ESMTP Postfix
221 2.7.0 Error: I can break rules, too. Goodbye.

This happens because curl normally speaks the HTTP protocol, so after it establishes a TCP handshake, it starts sending data like this:
GET / HTTP/1.1
Host: yourispsmtpserverhost.com:25
User-agent: curl

But what the SMTP server is expecting is SMTP, which is more like this:
HELO myhomecomputername.local

At which point the server sends back its identification line:
250 yourispsmtpserverhost.com

So you see that there is nothing that prevents curl from establishing a transport layer connection with the SMTP server, it just can't speak the protocol. But you can speak the protocol yourself with a program like telnet or more preferably nc.


text:
Q: Handwritten signature visualization? With the coming of devices like Samsung Notes, with a pressure sensitive pen (and with supposedly ink like experience), I was thinking it might be possible to use mobile devices as a signature pad. Can someone help me if there exist some open libraries (preferably java) / standard approaches for how to visualize data collected by a pen (xy coordinates, pressure, speed etc.) into an image?
What I mean is, that simply displaying the xy coordiantes won't look good enough. There should be at least some curve smoothing maybe other things to make it look as close to handwritten text as possible. And if there exist some standard ways for how to deal with that, I would like to avoid reinventing the wheel. Note that I am not concerned about OCR or any form of handwritten text recognition, just visualization.

A: I don't know of any libraries, but I would guess that constructing a cubic spline would be sufficient. I would guess that any existing implementations will be more crude for speed - just straight lines between points.
Note that here you don't care about the nature of the shapes, so you could look for pen input smoothing; that got me to Inkscape's smoothing, and you may be able to use its code for your own visualization.


text:
Q: Анимировать появление React - компонента при рендере есть вот такой логичный код React:
function Label(props){
 if(!props.isRedN){
   return Nothing
 }else{
   return <lable style={{ color: 'rgba(52, 52, 52, 0.73)'}} className='field-lable'>It Work!</lable>
 }
}

 class someClass extend React.Component{
   constructor(props){
     super(props);
     this.state = {
     isRedN: false,
     nameInput: ''
   }

  handleChangesName(e){
    this.setState({nameInput: e.target.value});
  }

  isRedFalseN(){ this.setState({isRedN: false}) }

  useClickOnButton(){
    if(this.state.nameInput === ''){
      this.setState({isRedN: true,});
    }
  }

render(){
 return(
 <input type='text' onClick={this.isRedFalseN} value={this.state.nameInput} onChange={this.handleChangesName} required></input>

 <button className='starandbutton-button' onClick={this.useClickOnButton}>Send</button>
 )}
 }

и вот такой CSS код:
.form-form input:focus{
 outline: none;
}

.form-form input:focus ~ label,
.form-form input:valid ~ label{
  transform: translateY(-35px);
  font-size: 12px;

  color: #A8A8A8;
}

.field-lable{
  position: absolute;
  padding-bottom: 10px;
  padding-right: 4px;

  font-family: 'Prata';
  font-style: normal;
  font-weight: 400;
  font-size: 20px;
  /* identical to box height */

  text-align: right;
  pointer-events: none;
  color: #343434;

  transition: all 0.3s ease;
}

Проблема: всё работает прекрасно(как не странно), но проблема заключается в анимации, а именно в том, что когда React перерендывает компонент  при, например, default значении isRedN={false}, а потом перерендер при значении true, а потом наоборот, это происходит грубо и резко(без анимации), хотя в CSS как можно увидеть есть строка про transition, так вот вопрос: есть какие то способы отрендерить React компонент плавно и с значениями как для CSS transition: all 0.3s ease

A:

import React, { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [isShowBox, setIsShowBox] = useState(false);

  useEffect(() => {
    setTimeout(() => setIsShowBox(true));
  }, []);

  return (

      <div className={`block ${isShowBox ? "block-show" : ""}`} />

  );
}
.block {
  width: 50px;
  height: 50px;
  background-color: black;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.block-show {
  opacity: 1;
}


text:
Q: Linux linear to physical address mapping Linux initialises kernel code, kernel data, user code and user data to same 0x00000000(base) and 0xffffffff(limit). They span the same linear space. How does the paging unit differentiates between linear space of different segments. Does every segment have different page table.

A: The ELF standard (Executable and Linkable Format) has been developed for that reason (organizing the different pieces of data into one binary). Among others, it has a header that specifies which segments are valid.
If your question is where, in terms of physical address, these segments are mapped, then the answer is that linker decides. There are many articles and e-books that describe the linker's functionality.
I reccommend Advanced C and C++ Compiling book to get the full picture.


text:
Q: cx_Oracle connection issue from python Hi I am getting below error when trying to connect to Oracle from python.
 Traceback (most recent call last):
  File "C:\Python34\Scripts\OraConnect.py", line 1, in <module>
    import cx_Oracle
ImportError: No module named 'cx_Oracle'


text:
Q: Recursive descent parser implementation I am looking to write some pseudo-code of a recursive descent parser. Now, I have no experience with this type of coding. I have read some examples online but they only work on grammar that uses mathematical expressions. Here is the grammar I am basing the parser on.
S -> if E then S | if E then S else S | begin S L | print E

L -> end | ; S L

E -> i

I must write methods S(), L() and E() and return some error messages, but the tutorials I have found online have not helped a lot. Can anyone point me in the right direction and give me some examples?.
I would like to write it in C# or Java syntax, since it is easier for me to relate.

Update
public void S() {
    if (currentToken == "if") {
        getNextToken();
        E();

        if (currentToken == "then") {
            getNextToken();
            S();

            if (currentToken == "else") {
                getNextToken();
                S();
                Return;
            }
        } else {
            throw new IllegalTokenException("Procedure S() expected a 'then' token " + "but received: " + currentToken);
        } else if (currentToken == "begin") {
            getNextToken();
            S();
            L();
            return;
        } else if (currentToken == "print") {
            getNextToken();
            E();
            return;
        } else {
            throw new IllegalTokenException("Procedure S() expected an 'if' or 'then' or else or begin or print  token " + "but received: " + currentToken);
        }
    }
}

public void L() {
    if (currentToken == "end") {
        getNextToken();
        return;
    } else if (currentToken == ";") {
        getNextToken();
        S();
        L();
        return;
    } else {
        throw new IllegalTokenException("Procedure L() expected an 'end' or ';' token " + "but received: " + currentToken);
    }
}

public void E() {
    if (currentToken == "i") {
        getNextToken();
        return;
    } else {
        throw new IllegalTokenException("Procedure E() expected an 'i' token " + "but received: " + currentToken);
    }
}

A: This is not the easiest grammar to start with because you have an unlimited amount of lookahead on your first production rule:
S -> if E then S | if E then S else S |  begin S L | print E

consider
if 5 then begin begin begin begin ...

When do we determine this stupid else?
also, consider
if 5 then if 4 then if 3 then if 2 then print 2 else ...

Now, was that else supposed to bind to the if 5 then fragment? If not, that's actually cool, but be explicit.
You can rewrite your grammar (possibly, depending on else rule) equivalently as:
S -> if E then S (else S)? | begin S L | print E
L -> end | ; S L
E -> i

Which may or may not be what you want. But the pseudocode sort of jumps out from this.
define S() {
  if (peek()=="if") {
    consume("if")
    E()
    consume("then")
    S()
    if (peek()=="else") {
      consume("else")
      S()
    }
  } else if (peek()=="begin") {
    consume("begin")
    S()
    L()
  } else if (peek()=="print") {
    consume("print")
    E()
  } else {
    throw error()
  }
}

define L() {
  if (peek()=="end") {
    consume("end")
  } else if (peek==";")
    consume(";")
    S()
    L()
  } else {
    throw error()
  }
}

define E() {
  consume_token_i()
}

For each alternate, I created an if statement that looked at the unique prefix. The final else on any match attempt is always an error. I consume keywords and call the functions corresponding to production rules as I encounter them.
Translating from pseudocode to real code isn't too complicated, but it isn't trivial. Those peeks and consumes probably don't actually operate on strings. It's far easier to operate on tokens. And simply walking a sentence and consuming it isn't quite the same as parsing it. You'll want to do something as you consume the pieces, possibly building up a parse tree (which means these functions probably return something). And throwing an error might be correct at a high level, but you'd want to put some meaningful information into the error. Also, things get more complex if you do require lookahead.
I would recommend Language Implementation Patterns by Terence Parr (the guy who wrote antlr, a recursive descent parser generator) when looking at these kinds of problems. The Dragon Book (Aho, et al, recommended in a comment) is good, too (it is still probably the dominant textbook in compiler courses).

A: I taught (really just, helped) the parsing section of a PL class last semester.  I really recommend looking at the parsing slides from our page: here.  Basically, for recursive descent parsing, you ask yourself the following question:

I've parsed a little bit of a nonterminal, now I'm at a point where I can make a choice as to what I'm supposed to parse next.  What I see next will make decisions as to what nonterminal I'm in.

Your grammar -- by the way -- exhibits a very common ambiguity called the "dangling else," which has been around since the Algol days.  In shift reduce parsers (typically produced by parser generators) this generates a shift / reduce conflict, where you typically choose to arbitrarily shift instead of reduce, giving you the common "maximal much" principal.  (So, if you see "if (b) then if (b2) S1 else S2" you read it as "if (b) then { if (b2) { s1; } else { s2; } }")
Let's throw this out of your grammar, and work with a slightly simpler grammar:
T -> A + T
 |   A - T
 |   A
A -> NUM * A
   | NUM / A
   | NUM

we're also going to assume that NUM is something you get from the lexer (i.e., it's just a token).  This grammar is LL(1), that is, you can parse it with a recursive descent parser implemented using a naive algorithm.  The algorithm works like this:
parse_T() {
  a = parse_A();
  if (next_token() == '+') {
    next_token();  // advance to the next token in the stream
    t = parse_T();
    return T_node_plus_constructor(a, t);
  }
  else if (next_token() == '-') {
    next_token();  // advance to the next token in the stream
    t = parse_T();
    return T_node_minus_constructor(a, t);
  } else {
    return T_node_a_constructor(a);
  }
}
parse_A() {
  num = token(); // gets the current token from the token stream
  next_token();  // advance to the next token in the stream
  assert(token_type(a) == NUM);
  if (next_token() == '*') {
    a = parse_A();
    return A_node_times_constructor(num, a);
  }
  else if (next_token() == '/') {
    a = parse_A();
    return A_node_div_constructor(num, a);
  } else {
    return A_node_num_constructor(num);
  }
}

Do you see the pattern here:

for each nonterminal in your grammar: parse the first thing, then see what you have to look at to decide what you should parse next.  Continue this until you're done!

Also, please note that this type of parsing typically won't produce what you want for arithmetic.  Recursive descent parsers (unless you use a little trick with tail recursion?) won't produce leftmost derivations.  In particular, you can't write left recursive rules like "a -> a - a" where the leftmost associativity is really necessary!  This is why people typically use fancier parser generator tools.  But the recursive descent trick is still worth knowing about and playing around with.

A: Basically in recursive descent parsing each non-terminal in the grammar is translated into a procedure, then inside each procedure you check to see if the current token you are looking at matches what you would expect to see on the right hand side of the non-terminal symbol corresponding to the procedure, if it does then continue applying the production, if it doesn't then you have encountered an error and must take some action.
So in your case as you mentioned above you will have procedures: S(), L(), and E(), I will give an example of how L() could be implemented and then you can try and do S() and E() on your own.
It is also important to note that you will need some other program to tokenize the input for you, then you can just ask that program for the next token from your input.
/**
 * This procedure corresponds to the L non-terminal
 * L -> 'end'
 * L -> ';' S L
 */
public void L()
{
   if(currentToken == 'end')
   {
      //we found an 'end' token, get the next token in the input stream
      //Notice, there are no other non-terminals or terminals after
      //'end' in this production so all we do now is return
      //Note: that here we return to the procedure that called L()
      getNextToken();
      return;
   }
   else if(currentToken == ';')
   {
      //we found an ';', get the next token in the input stream
      getNextToken();
      //Notice that there are two more non-terminal symbols after ';'
      //in this production, S and L; all we have to do is call those
      //procedures in the order they appear in the production, then return
      S();
      L();
      return;
   }
   else
   {
      //The currentToken is not either an 'end' token or a ';' token
      //This is an error, raise some exception
      throw new IllegalTokenException(
          "Procedure L() expected an 'end' or ';' token "+
          "but received: " + currentToken);
   }
}

Now you try S() and E(),  and post back.
Also as Kristopher points out your grammar has something called a dangling else, meaing that you have a production that starts with the same thing up to a point:
S -> if E then S
S -> if E then S else S

So this begs the question if your parser sees an 'if' token, which production should it choose to process the input? The answer is it has no idea which one to choose because unlike humans the compiler can't look ahead into the input stream to search for an 'else' token. This is a simple problem to fix by applying a rule known as Left-Factoring, very similar to how you would factor an algebra problem.
All you have to do is create a new non-terminal symbol S' (S-prime) whose right hand side will hold the pieces of the productions that aren't common, so your S productions no becomes:
S  -> if E then S S'
S' -> else S
S' -> e
(e is used here to denote the empty string, which basically means there is no
 input seen)


text:
Q: ¿Cómo valido que si una fecha es mayor a la actual, se realize un update? tengo la siguiente consulta .
Quiero hacer un update a todas las actividades que su fecha de fin, sea menor a la actual, y que su estado pase a ser 'Finalizado',Tengo realizado esto :

¿Que es lo que está mal? Cuando ejecuto la consulta, no se realizan cambios.


text:
Q: How do I create a List of classes? I am trying to create a List of classes, like this:
abstract class Animal {
    def name = this.getClass.getName
    def say: String
}
class Dog extends Animal {
    def say = "Woof"
}
class Cat extends Animal {
    def say = "Meow"
}
val animalClasses = List(Dog, Cat)

This falls over on the last line, with the error message:
Zoo.scala:18: error: not found: value Dog

Note that I could create a List of instances of classes easily with List(new Dog(), new Cat()), but that's not what I want.

A: There you go:
scala> List(classOf[Dog],classOf[Cat])
res1: List[Class[_ >: Cat with Dog <: Animal]] = List(class Dog, class Cat)

As per this:

The predefined function classOf[T] returns a runtime representation of the Scala class type T.


text:
Q: Replacing certain values in Python List I have created a list for displaying a black/white (binary) image with its pixel values. However for the calculations  I am running I can not work with 0s represented by the black pixels. I have been trying to convert the 0s to 1s with the following code but it  does not work despite producing no errors:
from PIL import Image

img = Image.open('C:/Users/binary.png', 'r')
WIDTH, HEIGHT = img.size

data = list(img.getdata())  # convert image data to a list of integers
data = [data[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]

for (i, item) in enumerate(data):
    if item == 0:
        data[i] = 1

for row in data:
    print(' '.join('{:3}'.format(value) for value in row))

It might be noteworthy that when I try "item = 255" I get the following error:
"TypeError: '<' not supported between instances of 'list' and 'int'"
However this error doesn't make sense to me as when I do type(data) I get list output

A: data is a list of lists, you need nested loops.
for row in data:
    for i, value in enumerate(row):
        if value == 0:
            row[i] = 1


text:
Q: jqassistant how to skip some of the plugins I want to use jqassistant to create a dependency matrix of the application.
Currently all the plugins are executed by default.
This results in lot of unwanted data.
Is it possible to configure the plugins which I want to execute.
For eg: If I want to capture only the class level dependencies using jqassistant, Can I perform a scan only to get the class level informations (Any options in the scan command)?

A: This is not yet possible but has already been discussed as a potential feature request. There would be two options:

*

*Allow skipping whole plugins which are deployed during scan using a configuration property, e.g. "plugin.java.skip=true". This could be solved in a generic way for all plugins.

*Make specific plugins configurable to allow specifying their "depth" of scanning. There could be again two options:

*

*using something like profiles, e.g. "java.plugin.profile=full" or "java.plugin.profile=dependencies"

*specifying the label and relation types, e.g. "java.plugin.label.include=Type,Field,Method", "java.plugin.relation.include=DEPENDS_ON,EXTENDS,IMPLEMENTS"

What do you think?


text:
Q: parse google geocode with xstream I'm using Java and XStream to parse a google geocode request over http.  My idea is to have an Address class with all the geocode attr's (ie. lat/long, city, provice/state etc) but I'm having problems parsing the xml with xstream.
The google response is similar to this:
<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="http://earth.google.com/kml/2.0"><Response>
  <name>98 St. Patrick St, Toronto</name>
  <Status>
    200
    <request>geocode</request>
  </Status>
  <Placemark id="p1">
    <address>98 St Patrick St, Toronto, ON, Canada</address>
    <AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"> <Country><CountryNameCode>CA</CountryNameCode><CountryName>Canada</CountryName><AdministrativeArea><AdministrativeAreaName>ON</AdministrativeAreaName><Locality><LocalityName>Toronto</LocalityName><Thoroughfare><ThoroughfareName>98 St Patrick St</ThoroughfareName></Thoroughfare><PostalCode><PostalCodeNumber>M5T</PostalCodeNumber></PostalCode></Locality></AdministrativeArea></Country></AddressDetails>
    <ExtendedData>
      <LatLonBox north="43.6560378" south="43.6497426" east="-79.3864912" west="-79.3927864" />
    </ExtendedData>
    <Point><coordinates>-79.3896388,43.6528902,0</coordinates></Point>
  </Placemark>
</Response></kml>

That doesn't show up very well, but the meat of the code is in the AddressDetails tag.
Anyway, I'm new to Java and  XStream so the API terminology is a bit confusing for me.  I just need to be able to write some mapper that maps all these tags (ie. CountryName) to an attribute within my Address object, (ie. address.country = blah)  The address object will be pretty simple, mainly just strings for country name etc and floats for lat/long.
The docs and example just show straight mapping where each xml tag maps directly to the attribute of the same name of the object.  In my case however, the tags are named different than the object attr's.  A quick point in the right direction is all I'm looking for really.

A: I've used XStream in several projects.  Unfortunately, your problem isn't really what XStream is designed to solve.  You might be able to use its converter mechanism to achieve your immediate goal, but you'll run into limitations.  In a nutshell, XStream isn't designed to do conversion of Tree Structure A into Tree Structure B -- it's purpose is to convert from a Java domain model into some reasonable XML.  XStream is a great tool when you don't care much about the details of the XML produced.  If you care more about the XML than the Java objects, look at XMLBeans -- the Java is ugly, but it's incredibly schema-compliant.
For your project, I'd run the Google XML schema through XML beans, generate some Java that will give you a more literate way of hand-coding a converter.  You could use a raw DOM tree, but you'd have code like myAddress.setStreet(root.getFirstChild().getAttribute("addr1"))).  With XML beans, you say things like myAddress.setStreet(googleResult.getAddress().getStreetName();
I'd ignore JAXB as it's attempt to separate interface from implementation adds needless complexity.  Castor might be a good tool to consider as well, but I haven't used it in years.
In a nutshell, there aren't a lot of good Object-to-Object or XML-to-Object converters that handle structure conversion well.  Of those I've seen that attempt declarative solutions, all of them seemed much more complicated (and no more maintainable) than using XStream/XmlBeans along with hand-coded structure conversions.

A: Would it be possible to define a separate class specifically for dealing with XStream's mapping? You could then simply populate your AddressDetails object by querying values out of this other object.

A: I've ended up just using xpath and populating my own address object manually.  Seems to work fine.

A: Have you tried with json format? It should be the same but you'll need to set a com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver as the driver for XStream

A: You could use EclipseLink JAXB (MOXy) to do this:
package com.example;

import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="kml")
public class Address {

    private String country;

    @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:CountryName/text()")
    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}

and
@javax.xml.bind.annotation.XmlSchema(
   namespace = "http://earth.google.com/kml/2.0",
   xmlns = {
      @javax.xml.bind.annotation.XmlNs(
         prefix = "ns", namespaceURI ="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0")
   },
   elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.example;

A full example is available here:

*

*http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html


text:
Q: Best practices to have a test base class - .NET I'm starting to write tests for an app, something like:
namespace API.Test
{
    public class HealthCheckTests : IClassFixture<WebApplicationFactory<Startup>>
    {
        private readonly HttpClient _httpClient;

        public HealthCheckTests(WebApplicationFactory<Startup> factory)
        {
            _httpClient = factory.CreateDefaultClient(new Uri("http://localhost/healthcheck"));
        }

        [Fact]
        public async Task HealthCheck_ReturnsOk()
        {
            var response = await _httpClient.GetAsync("");

            response.EnsureSuccessStatusCode();
        }
    }
}

Of course, I got more controllers so I want to "reuse" the client for example. What do you think it's a better approach.

*

*Abstract class initializing constructor

*Class and instantiate in constructor like composition.

*Other

A: Other. What you actually do depends on what you test, what you want to configure and your personal preferences. In this case though the only thing that could be abstracted is the call to CreateClient or CreateDefaultClient which isn't much. There may not be any need to cache that instance either.
Many tests create a separate Application class that inherits from WebApplicationFactory<> allowing you to override the configuration or add extra members that may be useful.
In these tests for example, a PlaygroundApplication class is used that sets the environment and replaces the configured DbContext with one that uses in-memory SQLite. That repo demonstrates .NET 6 minimal APIs so it uses Program instead of Startup but that doesn't affect the tests at all:
internal class PlaygroundApplication : WebApplicationFactory<Program>
{
    private readonly string _environment;

    public PlaygroundApplication(string environment = "Development")
    {
        _environment = environment;
    }

    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.UseEnvironment(_environment);

        // Add mock/test services to the builder here
        builder.ConfigureServices(services =>
        {
            services.AddScoped(sp =>
            {
                // Replace SQLite with in-memory database for tests
                return new DbContextOptionsBuilder<TodoDb>()
                    .UseInMemoryDatabase("Tests")
                    .UseApplicationServiceProvider(sp)
                    .Options;
            });
        });

        return base.CreateHost(builder);
    }
}

This class is used in tests directly. It's not even used as a class fixture :
[Fact]
public async Task GET_Root_Responds_OK()
{
    await using var application = new PlaygroundApplication();

    using var client = application.CreateClient();
    using var response = await client.GetAsync("/");

    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    Assert.Equal("Hello World!", await response.Content.ReadAsStringAsync());
}

After that, it's a matter of style and convenience. You can have:

*

*Multiple such classes with separate configurations. Useful if the configurations are complex and/or repeating, eg for different scenarios, and you don't want to litter the tests with the config.

*A single one that's parameterized through constructor options. Useful if there are few options. If there are too many options, it's probably time to split it into separate classes. Configuring an ultra-flexible class can be a bigger hassle than creating a few different specialzed types

*A base TestApplication class with common configuration and specialized derived classes for multiple scenarios.

All options can be used as fixtures. You can combine any of these options with a Theory to run the same test using different configurations.


text:
Q: ColdFusion escape JSON string I currently have a JSON string, which is constructed manually, that I can't alter. I am searching for a function to escape non valid characters within specific fields that are posted. For example:
{"customer_notes" : "please deliver to 13/a test rd, nsw Australia."}
While I could do a simple find and replace for the special characters, I'm hoping there might be an easier way, like a function or regex pattern.
I know I could use serializeJson() but from what I understand it needs to be performed on an entire object. If this isn't the case, I hope someone can correct me.

A: You can use stringEscapeUtils class of java like this:
<cfset jsonStruct = deSerializeJson('{"customer_notes" : "please deliver to 13/a test rd, nsw Australia."}')>
<cfset objEscapeUtils = createObject("java", "org.apache.commons.lang.StringEscapeUtils")>

<!--- Loop over struct and escape each key value --->
<cfloop collection="#jsonStruct#" item="key">
    <cfset jsonStruct[key] = objEscapeUtils.escapeJavaScript(jsonStruct[key])>
</cfloop>

<!--- Convert to JSON --->
<cfset jsonData = serializeJson(jsonStruct)>


text:
Q: Advice for Setting Up Rails Sites for Prototyping I'm learning Ruby on Rails and have just signed up with LunarPages as my webhosting company.  To start, I want to write some test applications and get them uploaded and running on my website just to understand how things work.  However, I don't want anyone looking at what I'm working on as I learn.  Does anyone have any advice as to how I should structure my pages and sites in such a way that I can keep them hidden until I'm ready to go live?  Can I easily do something like this?
www.mysite.com  <- everyone can see
www.mysite.com/testapplication1  <- no one can see for now
www.mysite.com/testapplication2  <- no one can see for now
Sorry if this sounds like a stupid question.  I'm just starting out.  By the way, I have heard of Heroku but I've already paid for this webhosting service so I'd like to get my money's worth, at least until my subscription is up.
Thanks!

A: I'm not sure if LunarPages offers the level of configurability that is required to run rails apps from sub-directories. I'd use subdomains (testapp1.mysite.com, testapp2.mysite.com) and then use appropriate access control (could be htaccess, HTTP BASIC AUTH in your app, or something more complex like authlogic)


text:
Q: How do I call some blocking method with a timeout in Obj-C? Is there a standard nice way to call a blocking method with a timeout in Objective C?  I want to be able to do:
// call [something blockingMethod];
// if it hasn't come back within 2 seconds, forget it

Thanks.

A: It is not possible to interrupt a function that is not designed to be interrupted. Doing so would generally cause data corruption and resource leaks.
The standard way to achieve what you're describing is to redesign blockingMethod so that it accepts a timeout or other cancelation mechanism.
If that's not possible, and it is required that you timeout blockingMethod, the standard approach is to fork a child process to run blockingMethod, and kill it (usually by sending SIGTERM) if it doesn't finish by the timeout. This is somewhat complex to implement in ObjC, and you'll need to also implement a mechanism to send the results back to the parent process. Since the operating system manages resources (memory, file handles, etc) at the process level, the only way to forcibly interrupt a function is to create a separate process for it. This still can lead to data corruption depending on what blockingMethod does, but it will work for a much larger set of problems.
Note that it's not generally possible to fork a process from non-Apple code on iOS, so this can't be done there.
As an example of what I mean by "data corruption," consider some simple code like:
[self.cache lock];
[self.cache removeObject: object];
[self.cache decrementCountOfObjects];
[self.cache unlock];

Now imagine that the process were forcibly terminated in the middle of this operation. What should happen? How does the cache get unlocked? How are the cache contents and the count reconciled? It's even possible that the object would be in the middle of being copied; then what? How would the system automatically deal with all of these issues unless blockingMethod were written with cancelation in mind?

A: How about using a semaphore? This can be locked across threads and then you can do something like
dispatch_semaphore_t s = dispatch_semaphore_create ( 0 );

// In a different thread or on some queue,
// fire up some process, when done signal
// the semaphore with
[ fire up thread ... some task, when done
dispatch_semaphore_signal( s );
... ]

// This waits 2 seconds for the semaphore
if ( dispatch_semaphore_wait( s, 2 ) )
{
  // ... it hasn't come back after 2 seconds so 'forget it'
}
else
{
  // ... you now have the semaphore within 2 seconds so 'do it'
}

// This waits forever, just for reference
dispatch_semaphore_wait( s, DISPATCH_TIME_FOREVER );


text:
Q: How do I correctly retrieve, using bash' cut, the first field from a line with only 1 field in a text file? In a text file (accounts.txt) with (financial) accounts the sub-accounts are, and need to be, separated by an underscore, looking like this:
assets
assets_hh
assets_hh_reimbursements
assets_hh_reimbursements_ff

... etc.
Now I want to get specific sub-accounts from specific line numbers, e.g.:
field 3 from line 4:
$ lnr=4; fnr=3
$ cut -d $'\n' -f "$lnr" < accounts.txt | cut -d _ -f "$fnr"
reimbursements
$

But both fnr=1 and fnr=2 give for the first line, which has only 1 field:
$ cut -d $'\n' -f 1 < accounts.txt | cut -d _ -f "fnr"
assets
$

which is undesired behaviour.
Now I can get around this by prefixing an underscore to each account and add 1 to each required field number, but this is not an elegant solution.
Am I doing something wrong and/or can this be changed by issuing a different retrieval command?

A: Using the cut -d $'\n' -f "$lnr" for getting the lnr-th line from the file is somewhat strange. More common approach is using sed, like:
sed -n "${lnr}p" file | cmd ...

However, for this the awk is better - in one invocation could handle the lnr and fnr too.
file=accounts.txt
lnr=1
fnr=2
awk -F_ -v l=$lnr -v f=$fnr 'NR==l{print $f}' "$file"

The above for the all combinations lnr/fnr produces:
line                          field1   field2   field3           field4
------------------------------------------------------------------------
assets                        assets
assets_hh                     assets   hh
assets_hh_reimbursements      assets   hh       reimbursements
assets_hh_reimbursements_ff   assets   hh       reimbursements   ff

A: Check below solution -
cat f
assets
assets_hh
assets_hh_reimbursements
assets_hh_reimbursements_ff

Based on your comment try below commands -
$ lnr=1; fnr=2
$ echo $lnr $fnr
1 2
$ awk -v lnr=$lnr -v fnr=$fnr  -F'_' 'NR==lnr  {print $fnr}' f
             ###Output is nothing as line 1 column 2 is blank when FS="_"
$ lnr=4;fnr=1
$ echo $lnr $fnr
4 1
$ awk -v lnr=$lnr -v fnr=$fnr  -F'_' 'NR==lnr  {print $fnr}' f
assets
$ lnr=4;fnr=3
$ echo $lnr $fnr
4 3
$ awk -v lnr=$lnr -v fnr=$fnr  -F'_' 'NR==lnr  {print $fnr}' f
reimbursements

A: One solution is to head|tail and read into an array so it's easier to work with the items:
lnr=4
fnr=2
IFS=_ read -r -a arr < <(head -n "$lnr" accounts.txt | tail -n 1)
#note that the array is 0-indexed, so the fieldnumber has to fit that
echo "${arr[$fnr]}"

Then you could expand the idea into a more usable function:
get_field_from_file() {
    local fname="$1"
    local lnr="$2"
    local fnr="$3"
    IFS=_ read -r -a arr < <(head -n "$lnr" "$fname" | tail -n 1)
    if (( $fnr > ${#arr[@]} )); then
        return 1
    else
        echo "${arr[$fnr]}"
    fi
}

field=$(get_field_from_file "accounts.txt" "4" "2") || echo "no such line or field"
[[ -n $field ]] && echo "field: $field"


text:
Q: IoC Castle Windsor in MVC routing problem I've set up castle windsor in my mvc app. everything works great except it also catches routes that are of type link or image. The problem is that right before exiting from the controller and generating the view "GetControllerInstance" is executed with 'null' type. This happends anytime there a link on a page like:
<link rel="stylesheet" type="text/css" href="non-existing.css"/>

Or a link to an image that does not exist. Why is this happening?
My windows class:
    public class WindsorControllerFactory : DefaultControllerFactory
{
    #region Constants and Fields

    /// <summary>
    /// The container.
    /// </summary>
    private readonly WindsorContainer container;

    #endregion

    // The constructor:
    // 1. Sets up a new IoC container
    // 2. Registers all components specified in web.config
    // 3. Registers all controller types as components
    #region Constructors and Destructors

    /// <summary>
    /// Initializes a new instance of the <see cref="WindsorControllerFactory"/> class.
    /// </summary>
    public WindsorControllerFactory()
    {
        // Instantiate a container, taking configuration from web.config
        this.container = InversionOfControl.Container;

        // Also register all the controller types as transient
        IEnumerable<Type> controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                            where typeof(IController).IsAssignableFrom(t)
                                            select t;
        foreach (Type t in controllerTypes)
        {
            this.container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);
        }
    }

    #endregion

    #region Methods

    /// <summary>
    /// The get controller instance.
    /// </summary>
    /// <param name="requestContext">
    /// The request context.
    /// </param>
    /// <param name="controllerType">
    /// The controller type.
    /// </param>
    /// <returns>
    /// Resolved controller instance.
    /// </returns>
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            controllerType = typeof(HomeController);
        }

        return (IController)this.container.Resolve(controllerType);
    }

    #endregion
}

A: This is only natural. The non-existing image or css cannot find the controller but you are defaulting it to the HomeController  while this controller cannot handle static content.
I do not think you need an override here. Let the default controller handle what it does and resource will get a 404 error if it cannot be found instead you forcing it to be served by that controller.

As I said, it is only natural for the type to be null if it cannot be found.
Change it to this:
   if (controllerType == null)
    {
        return base.GetControllerInstance(requestContext, controllerType);

    }

A: I found that I had to return null when the controllerType was null. Handing it on to the base class resulted in an exception. Below is the working code that I am using.
public class DependencyControllerFactory : DefaultControllerFactory, IDisposable
{
    protected readonly WindsorContainer _container;

    public DependencyControllerFactory()
    {
        _container = new WindsorContainer();

        _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel));
        _container.Install(FromAssembly.This());
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            return null;
        }
        else
        {
            return (IController)_container.Resolve(controllerType);
        }
    }

    public override void ReleaseController(IController controller)
    {
        _container.Release(controller);
    }

    public void Dispose()
    {
        _container.Dispose();
    }
}


text:
Q: Is it possible to test if buffer data was successfully loaded onto the GPU without fully defined shaders? (C++, OpenGL 4.4, GLFW) I am brand new to OpenGL programming, and I know that graphics APIs are notoriously difficult to debug. My question is, I have a txt file with 3D vertex data. After I create the vertex and index buffers, is there some way to see if the data was loaded correctly? As of now, the only way I can think of is to create a shader to display the points, but to do that would involve a lot of math, and I want to make sure that the data is at least loaded correctly before I try to debug it, that way, if there is a problem, I will know whether or not the problem is in my math in my shader, or I didn't initialize the buffers properly.
Edit:
In case you're confused as to what I'm asking, I'm asking if there is some sort of function you can use that will display the buffer data on the GPU?

A: You can use glGetBufferSubData() to read back the current buffer content.
Another option is glMapBufferRange(), which allows you to obtain a pointer to the buffer content.
If you don't know the current size of the buffer, which you will need for the calls above, you can get it with glGetBufferParameteriv(). For example, for the currently bound array buffer:
GLint bufSize = 0;
glGetBufferParamteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, bufSize);


text:
Q: loading con ajax en codeigniter mientras se ejecuta job SQL Server Les cuento, llevo ya un tiempo desarrollando una plataforma en PHP con codeigniter en su versión 3.0, estoy conectado a una base de datos local SQL Server, en la cual tengo un job llamado Automático. Este job es ejecutado mediante la función del modelo "ejecutar_job":
CONTROLADOR
public function ejecutar() // Enfocado a UCF - Consolidar BBDD
{
    $this->load->model('modelo');
    $this->modelo->ejecutar_job();
}

MODELO
 function ejecutar_job()
    {
            try
            {
                    $query = $this->db->simple_query("EXEC msdb.dbo.sp_start_job 'Automatico';");
                    return 1;
            }

            catch(Exception $e)
            {
                    echo $e;
                    return 0;
            }

    }

hasta ahí todo bien, pero como es un job que tarda más menos 2 min. necesito una forma de que la plataforma distinga cuando ha terminado su proceso. Para ello pensé en AJAX, implementando el siguiente código:
AJAX en VISTA

Este código debería poner una imagen.gif mientras se ejecuta la acción y cuando esta halla terminado, saltaría a la función de ".done" redireccionando hacia la página de descarga del archivo.
El problema es: la ejecución del job si se realiza, y también redirecciona hacia la página de descargas, pero no puedo lograr que se mantenga la imagen "cargando" todo el tiempo de ejecución. Más bien apenas intento accionar el AJAX salta hacia '.done' sin que halla terminado el tiempo de ejecución, lo que provoca que el documento de descarga no esté listo.
Puede que sea un error o problema muy simple, pero no logro resolverlo. Si me hechan una ayuda sería genial...
Saludos!

A: Ya lo he solucionado, descubrí que cuando se trabaja con JOBS en SQL Server, como no tienes ningún tipo de retorno del JOB (a menos que lo parametrices), no puede esperar a que se realice... finalmente hice una consulta para determinar si el job termina, y otra para conocer su status final. Cuando llamo al JOB, llamo a estas consultas y todo resuelto (Desconocía que existían ciertas tablas que controlaban las acciones de los jobs)... si alguien tiene el mismo problema, mi solución fue:
CONTROLADOR :
public function ejecutar() // Consolidado de documentos del servicio
    {
        if($this->session->userdata('username')){
            $this->load->helper('url');
            $this->load->model('modelo');
            $valor=$this->modelo->ejecutar_job();
            $aux_termino['valor'] = 5;
            $aux_status['valor'] = 10;
            while($aux_termino['valor'] == 5){                          //5 = no ha terminado, 1 = ha terminado
                $termino=$this->modelo->comprobar_termino_job1();
                $aux_termino=json_decode(json_encode($termino),true);   //pasar desde objecto json a array[]
                sleep(4);                                               //para no saturar el servidor
            }
            $status=$this->modelo->comprobar_termino_status_job1();
            $aux_status = json_decode(json_encode($status),true);
            if($aux_status['valor'] == 1  || $aux_status['valor'] == '1'  ){
                redirect('welcome/descargar_consolidado');
            }
            else{
                redirect('welcome/error_ejecucion');
            }
        }
        else{
            redirect('login');
        }
    }

MODELO
 function ejecutar_job() // CONSOLIDACIÓN DE BASES DE DATOS DEL SERVICIO
        {
            $t = 2;
                try
                {
                        $query = $this->db->simple_query("EXEC msdb.dbo.sp_start_job 'Automatico';");
                        sleep($t);
                        return 1;
                }

                catch(Exception $e)
                {
                        echo $e;
                        return 0;
                }

        }

  function comprobar_termino_job1(){
        $consulta= "SELECT valor =
                    CASE when
                    (select
                    tabla1.last_executed_step_id
                    from  msdb.dbo.sysjobactivity tabla1
                    left outer join
                    msdb.dbo.sysjobs_view tabla2
                    on
                    tabla1.job_id = tabla2.job_id
                    where
                    tabla2.name = 'Automatico'
                    and tabla1.start_execution_date =
                        (select MAX(tabla1.start_execution_date)
                        from msdb.dbo.sysjobactivity tabla1
                        left outer join
                        msdb.dbo.sysjobs_view tabla2
                        on
                        tabla1.job_id = tabla2.job_id
                        where tabla2.name='Automatico')) is null
                        then 5 else 1
                        end ";
                    $query = $this->db->query($consulta);
                    return $query->row();
}

function comprobar_termino_status_job1(){
    $consulta="SELECT run_status as valor
                from
                msdb..sysjobhistory tabla_historial
                inner join
                msdb..sysjobs tabla_jobs
                on
                tabla_historial.job_id = tabla_jobs.job_id
                where tabla_jobs.name='Automatico'
                and
                tabla_historial.instance_id =
                (select max(instance_id) from msdb.dbo.sysjobhistory
                where step_name='Automatico')";
                $query = $this->db->query($consulta);
                return $query->row();
}

y la vista:

                        Subida exitosa

                        La carga de archivos ha sido exitosa, para continuar presione el botón "Consolidar"

                        <form action="<?php echo base_url('index.php/welcome/ejecutar'); ?>" method="post" id="formulario">
                            <input type="submit" value="Consolidar" class="btn btn-danger">
                        </form>


text:
Q: Prove that complex modulus has no primitive After having done a (small) course on complex analysis from a "physics point of view", I'm now doing a larger course on it from a mathematical perspective. However, early on in my lecture notes, it was casually remarked that |z|, the complex modulus, had no primitive function. However, I don't exactly see why this has to be the case.
It's very easy to find a primitive for the real modulus (absolute value), by writing |f| = sign(f)*f, but of course this doesn't work in complex numbers. Is there some theorem I can use to prove this, or use some fact about path-(in)dependency of complex integrals?
Thanks.

A: Only analytic functions can have a primitive (in the complex sense).
Assume that $F' = f$. By assumption $F$ is  analytic, since $F'$ exists, but this will force $f$ to be analytic as well, since the derivative of an analytic function is analytic.
(You can also argue more or less like you did: If $f$ has a primitive, then the integral of $f$ over any closed curve is $0$. Try to find a closed curve $C$ such that $\int_C |z|\,dz \neq 0$.)


text:
Q: How do we take advantage of automatically adjusted inset if the ViewController is created programatically? In IOS 7, Apple automatically adjust inset to the viewController.
This works if we specify the viewController in XIB.
What about if we create the viewController programatically?
How would we specify that the scrollView is the one where we want the inset to be adjusted?
In fact, how do we adjust the inset ourself?
This is the code:
- (void)viewDidLoad
{
    [super viewDidLoad];

    UICollectionView * cv = (UICollectionView *)self.view; //The collection view is self.view
    cv.backgroundColor = [UIColor clBackGroundColor];
    [cv registerClass:[BGCollectionViewCellImage class] forCellWithReuseIdentifier:[BGCollectionViewCellImage reuseIdentifier]];
    BOOL autoInset = self.automaticallyAdjustsScrollViewInsets;//auto inset is yes
    while(false);
    // Do any additional setup after loading the view.
}

Actually I wonder how automaticallyAdjustScrollViewInsets doesn't work on that one given that the scrollVIew is self.view and clearly self.automaticallyAdjustsScrollViewInsets is YES


text:
Q: Looking for a method to hook windows loadlibrary function I want to hook all loadlibrary calls.
I know it is dirty but it is for a testing purpose.
What i want to do is replace on the fly one Dll by one other.
I have managed to hook with classical technics. The problem is the hook is set after target process startup. So i miss loadlibrary calls


text:
Q: Why the reusable props is not working and show undefined I had to use the boolean hook expression i.e isMainPage. The logic is if isMainPage is true then the className is mainPageActive if not then it should be mainPage, But the main problem is the props that I had put in the main component are showing me undefined. Please tell me if I m doing it wrong.
const WebHeader = () => {

  const [threeDots, setThreeDots] = useState(false);

  console.log(threeDots);

  return (
        <>
          <Sidebar isSideBarShown={threeDots} />

            <button
              class="menu"
              aria-label="Main Menu"
              onClick={() => setThreeDots(!threeDots)}
            >
              <svg width="30" height="30" viewBox="0 0 100 100">
                <path
                  className={threeDots ? "openedline1 line" : "line line1"}
                  d="M 20,29.000046 H 80.000231 C 80.000231,29.000046 94.498839,28.817352 94.532987,66.711331 94.543142,77.980673 90.966081,81.670246 85.259173,81.668997 79.552261,81.667751 75.000211,74.999942 75.000211,74.999942 L 25.000021,25.000058"
                />
                <path
                  className={threeDots ? "openedline2 line" : "line line2"}
                  d="M 20,50 H 80"
                />
                <path
                  className={threeDots ? "openedline3 line " : "line line3"}
                  d="M 20,70.999954 H 80.000231 C 80.000231,70.999954 94.498839,71.182648 94.532987,33.288669 94.543142,22.019327 90.966081,18.329754 85.259173,18.331003 79.552261,18.332249 75.000211,25.000058 75.000211,25.000058 L 25.000021,74.999942"
                />
              </svg>
            </button>

    </>
  );
};

export default WebHeader;

Here is the Main Component
const Main = (props, { isMainShown }) => {
  console.log(isMainShown);
  useEffect(() => {
    props.ImportForamttedFile();
  }, []);
  return (
    <>

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route exact path="/GrossProfitView">
            <GrossProfitView Sheet={props.Sheet} />
          </Route>
          <Route exact path="/data/augest-21/reports">
            <Report Sheet={props.Sheet} />
          </Route>
          <Route exact path="/Scorecard">
            <ScoreCard Sheet={props.Sheet} />
          </Route>
          <Route exact path="/Commisionview">
            <CommisionView />
          </Route>
          <Route exact path="/Activationview">
            <ActivationView />
          </Route>
          <Route exact path="/Accessoriesview">
            <Accessoriesview />
          </Route>
          <Route exact path="/TotalMobileProtection(TMP)View">
            <TotalMobileProtectionView />
          </Route>
          <Route exact path="/Notification/AllNotifications">
            <AllNotification />
          </Route>
        </Switch>

    </>
  );
};

const mapStatetoProps = (state) => {
  return {
    Sheet: Object.values(state.Sheet),
  };
};

export default connect(mapStatetoProps, { ImportForamttedFile })(Main);

A: You can access props this way.
const Main = (props) => {
 const { isMainShown } = props;
}


text:
Q: How can I increase the size of /tmp directory without affecting RAM or anything else? (Redhat 8.2) I'm new at Linux and I will get use of your help guys on this..
I want to increase the size of /tmp directory without affecting RAM or anything else on Red Hat 8.2 .. any suggestions to do that?
Thanks!

A: /tmp can be either on RAM (tepfs) or on disk. You can find out where it is by using the mount command. Something like the below.
tmpfs on /dev/shm type tmpfs (rw)

tmpfs indicates that it is on Virtual Memory (RAM)
It is possible to mount a disk (a partition) on /tmp, you can change its size without using more RAM. Please note that this can slow down applications that rely on a fast /tmp
If you decide to proceed.
You will have to create or have an empty disk partition.
Change the entry for /tmp from tmpfs to your partition on /etc/fstab
Here is an article debating this


text:
Q: How to get the url name from a django url path? In my view i export the main_url_patterns from my app and i want to process this list to get two parts in a different lists:

*

*URL path

*URL name

So in my view i do something like that:
def siteurls_view(request):

    path_list=urls.main_urlpatterns

    url_list=[]

    for p in path_list:
        print(p, type(p),p[0])

Where urls.main_urlpatterns is:
path('consumptions_points/send/', views.send_consumptions_points_view, name='send_consumptions_points'),
    path('consumptions/', views.consumptions_view, name='consumptions'),
    path('consumptions/new/', views.consumptions_new_view, name='consumptions_new'),
    path('consumptions/get_tx/', views.get_tx_consumption_view, name='get_tx_consumption'),
    path('consumptions/send/', views.send_consumptions_view, name='send_consumptions')

So i would like to get for example all names from the path and insert them into a new list.
urls.main_urls_patterns is type of: <class 'django.urls.resolvers.URLPattern'>
Many thanks

A: There is a script made by @Cesar Canassa and it goes like this:
from django.conf import settings
from django.urls import URLPattern, URLResolver

urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [''])

def list_urls(lis, acc=None):
    if acc is None:
        acc = []
    if not lis:
        return
    l = lis[0]
    if isinstance(l, URLPattern):
        yield acc + [str(l.pattern)]
    elif isinstance(l, URLResolver):
        yield from list_urls(l.url_patterns, acc + [str(l.pattern)])
    yield from list_urls(lis[1:], acc)

for p in list_urls(urlconf.urlpatterns):
    print(''.join(p))

This code prints all URLs, unlike some other solutions it will print the full path and not only the last node. In case you want to add names you change
yield acc + [str(l.pattern)]
print(''.join(p))

with:
yield acc + [str(l.pattern)], l.callback
print(''.join(p[0]))

but keep in mind that this prints out the view's function name and not a name


text:
Q: How to get list of all routes in Magento 2? Is it possible to get the list of all routes in a Magento 2 environment? I am looking some command-line tool, if there is any?
Note: I had a bin/rails routes command to list all the routes in rails framework, and I am looking something similar to this.

A: Yes, using n98:

n98-magerun.phar config:dump frontend/routers


text:
Q: Billing Client subscription with different currencies I implemented google payments for subscription with introductory period but there is an UI issue that I don't have any clue how to resolve.
So, the SkuDetails json looks like:
{"type": "subs", "price": "$ 28.88", "price_amount_micros": 28884077, "price_currency_code": "$", "subscriptionPeriod": "P1M", "introductoryPriceAmountMicros": 790000, "introductoryPricePeriod": "P1M", "introductoryPrice": "£0.79", "introductoryPriceCycles": 1.}
As you can see, the introductoryPrice has different currency than price_currency_code. Any thoughts?
Thank you.


text:
Q: How to recover a deleted file that is still open? How can one restore a file that has been deleted but is still open by a process?
The blog post "Restoring files from /proc" explains how to do this on Linux:

*

*Use lsof (e.g., lsof -c name) to find all files currently open for the given process (whose name starts with name). From the output, you learn the process's pid and the file descriptor (fd) of the file you are looking for.

*Use cp /proc/<pid>/fd/<fd> /tmp/restored-file` to make a copy.

The first step works one-to-one on OS X, too. However, step 2 seems more complicated. Is there a similar feature on OS X?
(I tried /dev/fd but in my case, it did not contain the PID/FD of my process/file.)

A: I couldn't find an OSX equivalent, but answering anyway since this may be urgent.
If the file is really important to recover and you have to shut the system down, remount the filesystem the file was on read-only and image the partition with a tool such as CloneZilla, - this will preserve your ability to use various recovery tools in case the space the file was using gets reallocated to another file.
Depending on what type of file you need to recover, PhotoRec might be able to find it. Also, the free version of Disk Drill may be useful, and depending on what filesystem is in use, there's a small chance TestDisk may be of help (doesn't fully support Mac filesystems, even though it runs on OSX).


text:
Q: while loop does not seem to work when I delete System.out.println So this while loop pretty much do nothing until I change the value of bgmPlaying. It works fine. However, if I delete the parts that says //testing above it(without any line breaks), it does not work.
This block of code actually keeps checking whether a music is on or off.
Any idea why it stops working when I delete the System.out.println() parts???
Here is my code:
import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;

/**
 * This class simply plays a background music in a seperate thread
 * @author Mohammad Nafis
 * @version 1.0
 * @since 04-03-2018
 *
 */
public class AudioPlayer implements Runnable{

    /**
     * this boolean indicates whether the background music is playing
     */
    private boolean bgmPlaying = true;

    public void stopBGM() {
        bgmPlaying = false;
    }

    public void playBGM() {
        bgmPlaying = true;
    }

    /**
     * this is an overridden method from Runnable interface that executes when a thread starts
     */
    @Override
    public void run() {

        try {
            File soundFile = new File("sounds/epic_battle_music.wav");
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
            AudioFormat format = ais.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip)AudioSystem.getLine(info);
            clip.open(ais);
            clip.loop(Clip.LOOP_CONTINUOUSLY);

            //controlling the volume
            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
            gainControl.setValue(-20);
                clip.start();

                while(true) {

                    if(bgmPlaying) {
                        gainControl.setValue(-20);
                    } else {
                        gainControl.setValue(-80);
                    }

                    while(bgmPlaying) {

                        //testing
                        System.out.println("BGM is on: ");

                        if(bgmPlaying == false) {
                            gainControl.setValue(-80);

                            break;
                        }
                    }

                    while(!bgmPlaying) {

                        //testing
                        System.out.println("BGM is off: ");

                        if(bgmPlaying == true) {
                            gainControl.setValue(-20);

                            break;
                        }
                    }
                }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

This code is in my Controller class that calls the stop and play methods.
//adding action listener
    window.getpausebutton().addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            new Thread(new SoundEffect("sounds/clickSound.wav")).start();
            bgm.stopBGM();
        }
    });
    window.getplaybutton().addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            new Thread(new SoundEffect("sounds/clickSound.wav")).start();
            bgm.playBGM();
        }
    });

A: Using volatile and Thread.sleep is really a work around for the problem, although it should work. But the larger problem is that the code is busy-waiting for the state of the variable to change, and depending on shared state between the two threads. With volatile or synchronized you can manage these problems, but there is a better way.
In the java.util.concurrent package there are power tools for dealing with concurrency. Threads, volatile, sleep (and also wait and notify) are like primitive hand tools by comparison. One of the power tools in there is the BlockingQueue and its various implementations, which would let you implement something like the Actor Model in Java.
In the Actor Model, actors send messages to one another to act on, but they never share memory. You could define some simple messages, like PLAY, MUTE, and STOP, and send these messages from your control thread to your player thread. If you use a BlockingQueue, there will be no problem with the player seeing the messages, and it won't have to busy-wait for a message to arrive. It can simply try to take a message from the queue, and if there's no message waiting, it blocks until a message becomes available.
Here's how you could implement that in your code:
public enum Command {
    PLAY, STOP, MUTE;
}

import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;

import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * This class simply plays a background music in a separate thread
 *
 * @author Mohammad Nafis
 * @version 1.0
 * @since 04-03-2018
 */
public class AudioPlayer implements Runnable {
    private final String filename;
    private final BlockingQueue<Command> commandQueue =
            new LinkedBlockingQueue<>();

    public final static int LOUD = -20;
    public final static int QUIET = -80;

    public AudioPlayer(String filename) {
        this.filename = Objects.requireNonNull(filename);
    }

    public void perform(Command command) throws InterruptedException {
        commandQueue.put(Objects.requireNonNull(command));
    }

    @Override
    public void run() {
        try {
            File soundFile = new File(filename);
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
            AudioFormat format = ais.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip)AudioSystem.getLine(info);
            clip.open(ais);
            clip.loop(Clip.LOOP_CONTINUOUSLY);

            //controlling the volume
            FloatControl gainControl = (FloatControl)
                    clip.getControl(FloatControl.Type.MASTER_GAIN);
            gainControl.setValue(LOUD);
            clip.start();

            forever: while (true) {
                switch (commandQueue.take()) {
                    case PLAY:
                        gainControl.setValue(LOUD);
                        break;
                    case MUTE:
                        gainControl.setValue(QUIET);
                        break;
                    case STOP:
                        break forever;
                }
            }

            clip.stop();
            clip.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AudioPlayer player = new AudioPlayer(args[0]);
        Thread thread = new Thread(player);
        thread.start();

        Scanner in = new Scanner(System.in);
        String cmd = "";
        System.out.println("Type mute or play. Or stop to exit.");
        do {
            System.out.print(": ");
            System.out.flush();
            cmd = in.nextLine();
            if ("play".equals(cmd)) player.perform(Command.PLAY);
            else if ("mute".equals(cmd)) player.perform(Command.MUTE);
            else if ("stop".equals(cmd)) player.perform(Command.STOP);
            else System.out.println("I didn't understand that, sorry.");
        } while (!"stop".equals(cmd));

        player.perform(Command.STOP);
        thread.join();
        System.out.println("Be seeing you.");
    }
}

A few notes:

*

*I've added calls to clip.stop() and clip.close() after the player is stopped so that the audio system doesn't keep a background thread running that prevents the program from exiting.

*The perform(Command) method, while it is within the AudioPlayer class, will execute on the control thread that calls it, but that's okay. Because the queue is designed for concurrency, commands that are enqueued on the control thread will be immediately visible on the player thread. No need for Thread.sleep.

*I added constants for the two different gain levels.

*I made the name of the audio file a command-line parameter, since I don't have your epic battle music.

*Both the AudioPlayer constructor and the perform method will throw if you try to pass in null.


text:
Q: How do I check a previous row's value, (OHLC Stock Data)? I'm trying to do data-mine a stock data frame where the signal generated is in this format:
Signal = (stratdf['High'].shift() > (stratdf['Open'].shift()))

How do I code to check the previous row's value and compare it to the corresponding rows value (example: 1 bar ago > 10 bars ago) with the Signal being executed the next day (or row) after the logic is true?

A: >>> import pandas as pd
>>> df = pd.DataFrame([[4, 5, 9, 7, 10], [5, 4, 11, 8, 9]]).T
>>> df.columns = ['High', 'Open']
>>> df
   High  Open
0     4     5
1     5     4
2     9    11
3     7     8
4    10     9
>>> df['pre_high'] = df['High'].shift(1)
>>> df
   High  Open  pre_high
0     4     5       NaN
1     5     4       4.0
2     9    11       5.0
3     7     8       9.0
4    10     9       7.0

Now if you want to check where the pre_high is greater than the current open, then you can do the following:
>>> df['Signal'] = df['High'].shift(1) > df['Open']
>>> df
   High  Open  pre_high  Signal
0     4     5       NaN   False
1     5     4       4.0   False
2     9    11       5.0   False
3     7     8       9.0    True
4    10     9       7.0   False


text:
Q: Number of conjugacy classes of $sl_2(\mathbb{F}_q)$ Looking at the group $sl_2(\mathbb{F}_q) $, consisting of $2 \times 2$ matrices with determinant 1 and coefficents in a finite field $\mathbb{F}_q$ with $q$ elements, I am wondering if there are any general results of the number of conjugacy classes of the group for some $q$?
I've found that, for instance, $sl_2(\mathbb{F}_4)$ has 5 conjugacy classes, using the orbit-stabilizer theorem and the characteristic polynomial, $p_A(\lambda) = \lambda^2 - Tr(A) \lambda + det(A)$, and the results for irreducibility etc, but I have not found a way to generalize this.


text:
Q: Set up a public web page for free Is there a reliable website which allows you to publish a web page of mainly static text content?
I just need to put up a page for others to see it, even if it is temporary (e.g. URL expires after 15 days). To others, the page should be read-only.
The closest I can think of is Google Docs. Is there any other alternative?

A: Wordpress.com would let you create a blog style page which and is free without any time limit. http://wordpress.com/

A: You can using dropbox service for that. Put your html files in public folder and give your friends the link. http://lifehacker.com/5528104/use-dropbox-to-share-and-host-your-web-site


text:
Q: Time spent in initializing all elements of an array to zero in c++ I am initializing all the elements of an array to zero many times in my program.
I am using this code:
int a[100000]={};

Is the code above faster than this code:
for(int i=0; i<100000; i++)
{
    a[i]=0;
}

Or is there any other way to do it which is faster than both of them?

A: Usually compilers for definitions like this (when the array has automatic storage duration)
int a[100000]={};

generate object code that equivalent to
memset( a, 0, sizeof( a ) );

For example AFAIK in IBM Mainframe this function is implemented with one mashine instruction.

A: Just to mention, how you can self evaluate time of anything (synch executed) you want.
Pseudo:
DateTime begin = DateTime.Now;

// Your operations (for example 1 000 000 of them ... )

DateTime end = DateTime.Now;
TimeSpan operationsTakeOver = end - begin;

And then you don't have to ask here performance questions. Of course in most of the cases.


text:
Q: Can't connect react.js login to SpringBoot app I am trying to call REST endpoints on one application (spring-boot) from another (reactjs). The applications are running on the following hosts and ports.

*

*REST application, using spring boot, http://localhost:8080

*HTML application, using reactjs, http://localhost:9000
I am trying to send the login info from reactjs to spring-boot but without success.
Reactjs:
import React from 'react';

export default class Login extends React.Component {
constructor() {
    super();
    this.state = {
        login:"",
        password:""
    };

    this.handleChange = this.handleChange.bind(this);

}

handleChange() {
    this.setState({login: this.state.login});
}

render() {

    return (
        <form role="form">
            <div>
                <input type="text" name="login" onChange={this.handleChange} />
                <input type="password" name="password"/>
            </div>
            <button onClick={this.login.bind(this)}>Login</button>
        </form>
    );
}

login () {

    var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
    var url = "http://localhost:8080/test/login"
    xmlhttp.open("POST", url );
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.send(JSON.stringify({login: this.state.login}));
}
}

and Spring-boot:
@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping(value = "/test/login")
public Boolean testLogin(@RequestParam String login) {
    if ( login.equals ("ajt"))

    return true;
    else {
        return false;
    }
}

I can see that the two apps are connecting for even though reactjs gives me error 400, when I submit, the console of the Spring-boot app tells me:
 Resolved exception caused by Handler execution: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'login' is not present

I can only assume that from the Spring-boot side, it cannot translate what ever is sent via react.js.
ps: bear with me, I have been coding for about 6 months.

A: I knew this looked familiar.  Sorry my last answer didn't fix all your issues.
Your current problem is here;
public Boolean testLogin(@RequestParam String login) {

Should be
public Boolean testLogin(@RequestBody String login) {

EDIT::  Second problem.
Your handleChange function isn't taking in any values! It should look more like this;
handleChange(value) {
    this.setState({login: value});
}

When your input field calls this function, it needs to pass a value from the input into the state.  Your current code is essentially the same as this;
this.state.login = this.state.login;

Which obviously isn't going to get you anywhere.
Try that change.  If it still does not work, be sure you open your dev-tools in your browser and step through the code line by line to be sure it is executing and storing the values you want it to.


text:
Q: Randomized organic warp of adjacent polygons that preserves topology and fixed nodes I'm looking for algoritms to modify a set of polygons to make them appear more organic. They still need to maintain their topology and furthermore some of the nodes might be fixed. Please see the example image below where the left hexagons needs be transformed to something like shown on the right.

Note the red fixed nodes, those are not to be moved.
I do know how to "randomize" a line, but not how to take topology and bounds into account as its likely the polygons will intersect if not careful. Any ideas on how to achieve this? I would love to know the names of good algorithms to use, or even better Python libraries or example code.


text:
Q: Creating a main document with links to other documents I'm writing a paper, which has 5 sections. My supervisor wants to edit these sections individually, however rather than have them in a single file like they are in the current format. I've been asked to create

*

*A main file, e.g. named main.tex which is to include all commands and packages etc and title.

*This main file has input commands , e.g.,
\input{intro.tex}
\input{section1.tex}
\input{section2.tex}

The idea then is to have each section is in a separate .tex file in the same folder with one single PDF file as output. I've been told the main advantage is that this allows a token to be taken for each section.
Now I have absolutely no idea what any of this means or how it is to be done and have been told to work it out myself. I'd really really appreciate some assistance in how to do this.

A: There are essentially two ways to split files up with LaTex: using \include and using \input.
Let's start with \input. When LaTeX is reading blah.tex and comes across \input{blurb.tex}, it just pauses processing blah.tex and starts slurping up blurb.tex -- and when it's done it goes back to blah again, until it finishes. So basically you can quite simply "carve out" anything that you would put in your "main" file, and stick it into a sub-file, which is then "read in" with \input{}. That gives you one form of modularity. Its key issue is that every time it processes a document, LaTeX goes through this "reading in" process: so although your files are modular, the typesetting process really isn't: LaTeX goes through everything, every time.
Now of course that may make you think: suppose I split my document like this:
\documentclass{book}
\begin{document}
\input{chapter1.tex}
\input{chapter2.tex}
\end{document}

Now if I comment out one of those input lines, I can have a nice little copy of just Chapter 1, or just Chapter 2.
The trouble is that those chapters will often include things like cross-reference labels, or table of contents entries, or figure numbers, that you need to refer to in other places. That is where the slightly "cleverer" system of \include{filename} comes in: it allows you to save and use bits of the scaffolding that these sub-files have generated without actually typesetting them, using \includeonly{} to tell LaTeX which files to typeset. It's in some ways more limited though, and for present purposes assume that it's really only wanted in a very long document (we're talking book- or thesis-length not article length) where you not only want to work on editing only part of the files at a time, but you also want to control what gets typeset on any run.
So what your adviser is suggesting is actually a very accurate description of what you want. In a simplish project, you are probably best sticking with \input rather than using \include. A main .tex file (you can call it anything you want) is going to set up the "common parts" like a preamble that will specify the packages you want, the title, the table of contents (if you have one), perhaps the bibliography. But then the substance of each section is going to be in a separate file. Your main file will have an \input{} each of the sub-files at the place you need them to go. To typeset this, you will pdflatex main, and as LaTeX chomps through it will pause as necessary and slurp in the stuff from your sub-files.
So a minimum example would look something like:
main.tex
\documentclass{article}
\usepackage{lipsum}% and/or whatever
\title{Modular Papering}
\author{Mo Module}
\begin{document}
\maketitle
\input{sectiona.tex}
\input{sectionb.tex}
\end{document}

sectiona.tex
%NOTE: NO preamble or documentclass -- this is just being "read in"
\section{Section A}
\lipsum % Will work because I loaded the package in the preamble

sectionb.tex
%NOTE: NO preamble or documentclass -- this is just being "read in"
\section{Section B}
\lipsum

And just pdflatex main to get the complete document, with a title and two sections. All the real editing work will probably be done on those sub-files.
As has been pointed out in the comments, there are some good resources you can find by searching online. Two, pointed out in the comments, that give particularly clear explanations are https://en.wikibooks.org/wiki/LaTeX/Modular_Documents and When should I use \input vs. \include?
EDITED TO ADD: I've no idea what the "tokens" you are being told about are, but my guess is they are like "tokens" for a railway train on a single track line -- one person can edit one section while another edits another, without risk of collision! Maybe a slightly rudimentary approach to version control! But certainly one advantage of splitting things into reasonably small files is that it keeps versioning neat.