问:
RecyclerView, different divider dependently on type of row
So I have a ListView with different types of rows. I would like to disable divider for the first row and have another style of a divider for the second one.

What's the best practice to do that?

I'm adding dividers currently by:

```<code>    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL);
    dividerItemDecoration.setDrawable(getDrawable(R.drawable.divider));
    recyclerView.addItemDecoration(dividerItemDecoration);
</code>```

答:
I have done this in the following way.

Note: In my solution, the divider is part of the Item view, you can set a background instead or draw a line, or add a bottom margin and let the space show the background hence creating a divider etc. I recommend looking at the ItemDecoration api. I'm just showing you how to determine in ItemDecoration what you want to do.

First, in your adapter:

```<code>@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ...
    if (mData.get(postion) instanceof ObjectA)
        holder.itemView.setTag(R.id.noSpaceAfter, Boolean.TRUE);
    else
        holder.itemView.setTag(R.id.noSpaceAfter, Boolean.FALSE);
    ...
}
</code>```

Then in your RecyclerView, declare an ItemDecoration

```<code>mRecyclerView.addItemDecoration(new MyDividerItemDecoration());
</code>```

Finally, define your MyDividerItemDecorator

```<code>public class MyDividerItemDecoration extends RecyclerView.ItemDecoration {
    public MyDividerItemDecoration () {
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        Boolean noSpace = (Boolean) view.getTag(R.id.noSpaceAfter);
        View v = view.findViewById(R.id.view_sep);
        if (v != null) {
            if (noSpace == null || !noSpace) {
                v.setVisibility(View.VISIBLE);
            } else {
                v.setVisibility(View.INVISIBLE);
            }
        }
    }
}
</code>```

With this in mind, you can just copy the source for DividerItemDecoration and then in it's drawVertical method, when you fetch the views in the loop, check to see if R.id.noSpaceAfter is true or false and skip drawing accordingly.

Body:
So I have a ListView with different types of rows. I would like to disable divider for the first row and have another style of a divider for the second one.

What's the best practice to do that?

I'm adding dividers currently by:

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL);
    dividerItemDecoration.setDrawable(getDrawable(R.drawable.divider));
    recyclerView.addItemDecoration(dividerItemDecoration);

Body:
I have done this in the following way.

Note: In my solution, the divider is part of the Item view, you can set a background instead or draw a line, or add a bottom margin and let the space show the background hence creating a divider etc. I recommend looking at the ItemDecoration api. I'm just showing you how to determine in ItemDecoration what you want to do.

First, in your adapter:

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ...
    if (mData.get(postion) instanceof ObjectA)
        holder.itemView.setTag(R.id.noSpaceAfter, Boolean.TRUE);
    else
        holder.itemView.setTag(R.id.noSpaceAfter, Boolean.FALSE);
    ...
}

Then in your RecyclerView, declare an ItemDecoration

mRecyclerView.addItemDecoration(new MyDividerItemDecoration());

Finally, define your MyDividerItemDecorator

public class MyDividerItemDecoration extends RecyclerView.ItemDecoration {
    public MyDividerItemDecoration () {
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        Boolean noSpace = (Boolean) view.getTag(R.id.noSpaceAfter);
        View v = view.findViewById(R.id.view_sep);
        if (v != null) {
            if (noSpace == null || !noSpace) {
                v.setVisibility(View.VISIBLE);
            } else {
                v.setVisibility(View.INVISIBLE);
            }
        }
    }
}

With this in mind, you can just copy the source for DividerItemDecoration and then in it's drawVertical method, when you fetch the views in the loop, check to see if R.id.noSpaceAfter is true or false and skip drawing accordingly.


来源: stackexchange

问:
function pointer equal to another pointer within the function, why need to add *
please take look at Node *newNode(), i dont understand why i must add * for p=x
i made an Node named x(with data & next), and created a new memory space *p by using malloc,
then let p = x, but by i must add * for p=x?</p>

```<code>#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    Node *next;
};

Node *newNode(int data, Node *next){
    Node x = {data, next};
    Node *p = (Node *)malloc(sizeof(Node));
    *p = x; //i dont understand why an * need to be added here
    return p;
}

showNode(const struct Node *p){
    printf("%d\n", p->data);
}

int main(){
    Node *pHead = NULL;
    for(int i=4; i>=0; i--) {
        pHead = newNode(i,pHead);
    }
    printf("%d\n", pHead->next->next->next->data);

    Node* p = pHead;
    while(p != NULL){
        showNode(p);
        p = p-> next;
    }

    p = pHead;
    while(p != NULL){
        Node *pTemp = p;
        p = p->next;
        free(pTemp);
    }
}
</code>```

答: *p has two meanings. 1) at the time declaration... Like you write int *p. It means you have declared a pointer to an integer. 2) Not at the time of declaration. *p will now simply mean the data stored in the memory address that p is pointing to. </p>

ContentLicense: CC BY-SA 3.0

Body:
please take look at Node *newNode(), i dont understand why i must add * for p=x
i made an Node named x(with data & next), and created a new memory space *p by using malloc,
then let p = x, but by i must add * for p=x?

#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    Node *next;
};

Node *newNode(int data, Node *next){
    Node x = {data, next};
    Node *p = (Node *)malloc(sizeof(Node));
    *p = x; //i dont understand why an * need to be added here
    return p;
}

showNode(const struct Node *p){
    printf("%d\n", p->data);
}

int main(){
    Node *pHead = NULL;
    for(int i=4; i>=0; i--) {
        pHead = newNode(i,pHead);
    }
    printf("%d\n", pHead->next->next->next->data);

    Node* p = pHead;
    while(p != NULL){
        showNode(p);
        p = p-> next;
    }

    p = pHead;
    while(p != NULL){
        Node *pTemp = p;
        p = p->next;
        free(pTemp);
    }
}


问:
How to use the apache HttpClient without manager?
Although the normal usage for HttpClient works fine, I'm having difficulty wrapping my head around the connection manager part.
Neither the BasicHttpClientConnectionManager nor the PoolingHttpClientConnectionManager seem to fulfil my use case. I am running in a JEE application server and use HttpClient for consuming rest services.

From the documentation:

BasicHttpClientConnectionManager is a simple connection manager that maintains only one connection at a time. [...]
  This connection manager implementation should be used inside an EJB container.

But I would like to do some pooling, and preferably my own pooling (e.g. JCA adapter). I would like to simply create an HttpClient and have my own separate pool with HttpClients without the connection manager.
Any suggestions or solutions?

答:
You cannot really do that with HttpClient but you can with HttpCore, the transport toolkit HttpClient is based on

```<code>public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create()
        .add(new RequestContent())
        .add(new RequestTargetHost())
        .add(new RequestConnControl())
        .add(new RequestUserAgent("Test/1.1"))
        .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("localhost", 8080);
    coreContext.setTargetHost(host);

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        String[] targets = {
                "/",
                "/servlets-examples/servlet/RequestInfoExample",
                "/somewhere%20in%20pampa"};

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
</code>```

The sample code is taken from here

Body:
You cannot really do that with HttpClient but you can with HttpCore, the transport toolkit HttpClient is based on

public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create()
        .add(new RequestContent())
        .add(new RequestTargetHost())
        .add(new RequestConnControl())
        .add(new RequestUserAgent("Test/1.1"))
        .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("localhost", 8080);
    coreContext.setTargetHost(host);

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        String[] targets = {
                "/",
                "/servlets-examples/servlet/RequestInfoExample",
                "/somewhere%20in%20pampa"};

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }

The sample code is taken from here


问:
Using pattern to find all words between. What if my boundaries contain characters other than letters?
```<code>Pattern p = Pattern.compile("(\\bSTARTTEXTHERE\\b)(.*?)(\\bENDTEXTHERE\\b)");
</code>```

Hey guys I am having trouble. I am using a crude work around for bascially learning purposes to get all website data using URLConnection and InputStream. converting all that to a string using this

```<code>  BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null)
        {
            website += line;
        }
</code>```

and then wanting to do a simple pattern / matcher task to find all words (tweets in this case) between label-part="0"> and

I have found that all tweets on a page are always contained between these quotes and nothing else on the page has these quotes so in theory I should return the string which is the tweet. example : lang="en" data-aria-label-part="0">this is a test tweet
  However this code does not work

```<code> Pattern p = Pattern.compile("(\\bdata-aria-label-part="0">\\b)(.*?)(\\b</p></div>\\b)");
</code>```

The "0" is what is throwing the error. I have tried brackets and quotes and tried to make a string which that line of text but it only accepts words to my knowledge. Is this a limitation of the matcher class? I have tired to do some research here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html However I am quite new to coding and am finding it difficult to figure it out. I feel there has to be some way to take what you put in those areas as almost a string of characters

Any help would be appreciated. Cheers

Edit
I actually tried escaped quotes straight after posting the question however that didn't work. I have tried normal words and they work.

答:
SOLVED</p>

```<code> Pattern p = Pattern.compile("data-aria-label-part=\"0\">(.*?)</p></div>");
        Matcher m = p.matcher(website);
        ArrayList<String> matches = new ArrayList<String>();
        while (m.find()) {
            matches.add(m.group(1));
            System.out.println(matches);
            matches.remove(m.group(1));
        }
</code>```

Body:
Pattern p = Pattern.compile("(\\bSTARTTEXTHERE\\b)(.*?)(\\bENDTEXTHERE\\b)");

Hey guys I am having trouble. I am using a crude work around for bascially learning purposes to get all website data using URLConnection and InputStream. converting all that to a string using this

  BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null)
        {
            website += line;
        }

and then wanting to do a simple pattern / matcher task to find all words (tweets in this case) between label-part="0"> and

I have found that all tweets on a page are always contained between these quotes and nothing else on the page has these quotes so in theory I should return the string which is the tweet. example : lang="en" data-aria-label-part="0">this is a test tweet
  However this code does not work

 Pattern p = Pattern.compile("(\\bdata-aria-label-part="0">\\b)(.*?)(\\b

\\b)");

The "0" is what is throwing the error. I have tried brackets and quotes and tried to make a string which that line of text but it only accepts words to my knowledge. Is this a limitation of the matcher class? I have tired to do some research here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html However I am quite new to coding and am finding it difficult to figure it out. I feel there has to be some way to take what you put in those areas as almost a string of characters

Any help would be appreciated. Cheers

Edit
I actually tried escaped quotes straight after posting the question however that didn't work. I have tried normal words and they work.

Body:
SOLVED

 Pattern p = Pattern.compile("data-aria-label-part=\"0\">(.*?)</p></div>");
        Matcher m = p.matcher(website);
        ArrayList<String> matches = new ArrayList<String>();
        while (m.find()) {
            matches.add(m.group(1));
            System.out.println(matches);
            matches.remove(m.group(1));
        }


问:
Scrolling while message box is running
I have the following macro to show a message box to the user:

```<code>Sub Messageboxtest()
Test = MsgBox("Do you want to continue", vbYesNo)
If Answer = vbYes Then
Sheets(1).Range("A2").Value = 1
Else
End If
End Sub
</code>```

The macro itself works perfectly. However, once the message box is shown on the excel screen the user cannot scroll down in the Excel File anymore.

For an input box I know there is the function Application.InputBox but is there also something like Application.MessageBox?

答: There is not a application.MessageBox function just the MsgBox, but you can create a form that looks like a MsgBox and set the ShowModal property to False</p>

Title: Scrolling while message box is running

Body:
I have the following macro to show a message box to the user:

Sub Messageboxtest()
Test = MsgBox("Do you want to continue", vbYesNo)
If Answer = vbYes Then
Sheets(1).Range("A2").Value = 1
Else
End If
End Sub

The macro itself works perfectly. However, once the message box is shown on the excel screen the user cannot scroll down in the Excel File anymore.

For an input box I know there is the function Application.InputBox but is there also something like Application.MessageBox?


问:
jQuery: Pause function on mousemove or click
I've created a function that autoscrolls up and down the page on repeat, I'm now looking to extend this slightly as I want to have to ability to pause the autoscrolling when the user moves the mouse.

Basically the idea is that the page will autoscroll if the user isn't moving their mouse, as soon as they do this function will pause and they'll take over the interaction...until they stop again.

I have a jsFiddle.
This scrolls up and down as it should but now I need to pause as soon as an interaction is made, or pause and restart the animation upon clicking the .start and .stop respectively. My markup as follows:

```<code>//run instantly and then goes after (setTimeout interval)
function autoScroll() {

    $("html, body").animate({
        scrollTop: $(document).height()
    }, 4000);
    setTimeout(function() {
        $('html, body').animate({
            scrollTop: 0
        }, 4000);
    }, 4000);
    setInterval(function() {
        // 4000 - it will take 4 secound in total from the top of the page to the bottom
        $("html, body").animate({
            scrollTop: $(document).height()
        }, 4000);
        setTimeout(function() {
            $('html, body').animate({
                scrollTop: 0
            }, 4000);
        }, 4000);

    }, 8000);

}

autoScroll();
</code>```

Any suggestions on this would be greatly appreciated!

答:
The below method will "pause" a function (more like the code within it) by checking if a mouseIsMoving flag is set or not, as long as the mouse is moving:

var mouseIsMoving,
    // time (ms) after mouse stoped moving to set the flag back to false;
    mouseMoveTime = 500;

window.addEventListener('mousemove', ()=>{
  clearTimeout(mouseIsMoving);
  mouseIsMoving = setTimeout(()=>{ mouseIsMoving = false }, mouseMoveTime);
});

/////////////////////////////////////////////////////
// fire some function every 500ms

setInterval(someFunc, 500);

function someFunc(){
  // do whatever ONLY when the mouse is not moving
  if( !mouseIsMoving )
    console.log( new Date().toLocaleTimeString() )
}```

Body:
I've created a function that autoscrolls up and down the page on repeat, I'm now looking to extend this slightly as I want to have to ability to pause the autoscrolling when the user moves the mouse.

Basically the idea is that the page will autoscroll if the user isn't moving their mouse, as soon as they do this function will pause and they'll take over the interaction...until they stop again.

I have a jsFiddle.
This scrolls up and down as it should but now I need to pause as soon as an interaction is made, or pause and restart the animation upon clicking the .start and .stop respectively. My markup as follows:

//run instantly and then goes after (setTimeout interval)
function autoScroll() {

    $("html, body").animate({
        scrollTop: $(document).height()
    }, 4000);
    setTimeout(function() {
        $('html, body').animate({
            scrollTop: 0
        }, 4000);
    }, 4000);
    setInterval(function() {
        // 4000 - it will take 4 secound in total from the top of the page to the bottom
        $("html, body").animate({
            scrollTop: $(document).height()
        }, 4000);
        setTimeout(function() {
            $('html, body').animate({
                scrollTop: 0
            }, 4000);
        }, 4000);

    }, 8000);

}

autoScroll();

Any suggestions on this would be greatly appreciated!


问:
How to redirect a URL to open in puffin browser instead of safari browser in ios app?
As like we use this to open URL in facebook app. I want to open URL in puffin browser.</p>

```<code>if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]) {
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"fb://profile/355356557838717"]];
}
else {
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.facebook.com/DanielStormApps"]];
}
</code>```

答:
Add infoplist file

```<code><key>LSApplicationQueriesSchemes</key>
<array>
    <string>fb</string>
</array>
</code>```

You are open that type url :[NSURL URLWithString:@"fb://profile/355356557838717"]

Body:
As like we use this to open URL in facebook app. I want to open URL in puffin browser.

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]) {
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"fb://profile/355356557838717"]];
}
else {
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.facebook.com/DanielStormApps"]];
}

Body:
Add infoplist file

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fb</string>
</array>

You are open that type url :[NSURL URLWithString:@"fb://profile/355356557838717"]


问:
createWriteStream and createReadStream not working properly with Socket
```<code>let filesend = fs.createReadStream('./flex1.zip', 'utf8')
//let filesend = fs.createReadStream('./flex1.zip')
let fileget = fs.createWriteStream('./test/flex1.zip', 'utf8')
//let fileget = fs.createWriteStream('./test/flex1.zip')
fileget.on('finish', function() {
    console.log('getover')
})

net.createServer(function(socket) {
    socket.pipe(fileget)
    socket.on('error', function(err) {
        console.log(err.message);
    });
}).listen('18800', function() {
    console.log('server_open')
});

let client = new net.Socket();
client.connect('18800', '127.0.0.1', function() {
    filesend.pipe(client);
});
</code>```

when I call CreateReadStream and createWriteStream and set the encoding with 'utf8', I couldn't get the proper file,however if I didn't set the encoding ,I can get proper file.
All above situations happened while only using Socket

答:
If createReadStream and createWriteStream work fine for you with utf8, then it makes no difference weather you use socket or http.

The problem is only with your content to be read/written, what you are changing in case of socket. I can see filesend.pipe(client);

If you can console/print your client and can see it is what you want then just write it without utf8 because you do not need. Also if your client object is fine =>(its properties have no infinite recursion), an encoding like utf8 would have no problem as well

Body:
let filesend = fs.createReadStream('./flex1.zip', 'utf8')
//let filesend = fs.createReadStream('./flex1.zip')
let fileget = fs.createWriteStream('./test/flex1.zip', 'utf8')
//let fileget = fs.createWriteStream('./test/flex1.zip')
fileget.on('finish', function() {
    console.log('getover')
})

net.createServer(function(socket) {
    socket.pipe(fileget)
    socket.on('error', function(err) {
        console.log(err.message);
    });
}).listen('18800', function() {
    console.log('server_open')
});

let client = new net.Socket();
client.connect('18800', '127.0.0.1', function() {
    filesend.pipe(client);
});

when I call CreateReadStream and createWriteStream and set the encoding with 'utf8', I couldn't get the proper file,however if I didn't set the encoding ,I can get proper file.
All above situations happened while only using Socket


问:
Alignment using Constraints
I am using constraints Space between the green-view and blue-view changed depend upon the screen size. I am using Vertical Spacing between green-view and blue-view space is equal for all screens. but I exactly displayed Space between green-view and blue-view changes depends upon the screen sizes using constraints.

How Can i fix the problem?

答: From what i could understand from your problem, i am giving you below 4 screenshots containing constraints to all 3 views respectively. Last screenshot contains constraints on 1st view's proportional width.

Title: Alignment using Constraints


问:
How to Use Scanner to do Different Things with the Tokens
```<code>    String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    Scanner l = new Scanner (line);
    int index = line.lastIndexOf(" ");

    while (l.hasNext())
    {
        String name = l.next();
        char ch = name.charAt(0);
        System.out.print(ch);
    }
    System.out.print(" " + line.substring(index + 1));
</code>```

Example:

User enters the following - Fred John Samuel Smith

The output should be - FJS SMITH

The code doesn't work because the output is this:

FJSS SMITH

How do I split the first 3 words from the last word?

答:
try my approach I have provided the details in the comments </p>

```<code>public static void main(String args[])
            {
                //get the first Three Letter acronym and the last name
                StringBuilder sb = new StringBuilder("");
                String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();
                sb.append(line.charAt(0));
                int spaces=0;
                //get the actual spaces
                for(int i=0;i<line.length();++i)
                {
                    if(line.charAt(i)==' ')
                        ++spaces;
                }

                for(int i=1;i<line.length();++i)
                {
                    //compare each character of inputted String to space
                    if(line.charAt(i)==' '&&spaces>1)
                    {
                        sb.append(line.charAt(i+1));
                        --spaces;
                    }
                    //if space is now equal to one
                    else if(line.charAt(i)==' '&&spaces==1)
                    {
                        //it will consume all the remaining letter using this loop including the space character
                        while(i<line.length())
                        {
                            sb.append(line.charAt(i));
                            ++i;
                        }
                    }

                }
                //print test of StringBuilder sb
                System.out.println(sb.toString());

            }
</code>```

Body:
    String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    Scanner l = new Scanner (line);
    int index = line.lastIndexOf(" ");

    while (l.hasNext())
    {
        String name = l.next();
        char ch = name.charAt(0);
        System.out.print(ch);
    }
    System.out.print(" " + line.substring(index + 1));

Example:

User enters the following - Fred John Samuel Smith

The output should be - FJS SMITH

The code doesn't work because the output is this:

FJSS SMITH

How do I split the first 3 words from the last word?

Body:
try my approach I have provided the details in the comments

public static void main(String args[])
            {
                //get the first Three Letter acronym and the last name
                StringBuilder sb = new StringBuilder("");
                String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();
                sb.append(line.charAt(0));
                int spaces=0;
                //get the actual spaces
                for(int i=0;i<line.length();++i)
                {
                    if(line.charAt(i)==' ')
                        ++spaces;
                }

                for(int i=1;i<line.length();++i)
                {
                    //compare each character of inputted String to space
                    if(line.charAt(i)==' '&&spaces>1)
                    {
                        sb.append(line.charAt(i+1));
                        --spaces;
                    }
                    //if space is now equal to one
                    else if(line.charAt(i)==' '&&spaces==1)
                    {
                        //it will consume all the remaining letter using this loop including the space character
                        while(i<line.length())
                        {
                            sb.append(line.charAt(i));
                            ++i;
                        }
                    }

                }
                //print test of StringBuilder sb
                System.out.println(sb.toString());

            }


问:
Best video format for HTML5?
I've got a set of videos that are going to be posted on a new site I'm developing, using our new html5 player. I know Firefox only supports .ogg format, whereas most others (including eventually IE9) support h264.

I'm looking to tap into the experience of the crowd here: has anyone had any luck with a single video format across browsers? Or am I doomed to double-encode everything? It just seems a shame to waste space on having two copies of each video because we can't standardize our codecs.

Thanks in advance!

PS (Flash player isn't really an option as a fallback, partly on principle and partly because of a rather large mobile userbase.)

答:
From my personal experience with HTML5 Video, I create mp4, ogg, and flv file formats, and use the following implementation:

```<code><video id="movie" width="" height="" preload controls>
   <source id="srcMp4" src="video.mp4" />
   <source id="srcOgg" src="video.ogg" />
   <object id="flowplayer" name="flowplayer" width="480" height="352" data="http://releases.flowplayer.org/swf/flowplayer-3.2.5.swf"
            type="application/x-shockwave-flash">
      <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.5.swf" />
      <param name="allowfullscreen" value="true" />
      <param name="flashvars"
    value='config={"clip":"http://domain.com/video.flv"}' />
   </object>
</video>
</code>```

The MP4 format is provided first, due to a previous bug in iPad which only sees the first source listed.

If the browser can't play the MP4 version, it tries to load the Ogg version.  If that fails, it uses Flowplayer (flash) as a fallback.

I know you're looking for a solution without flash as a fallback, but in my opinion, we're just not there yet.  People are still using IE6 for crying out loud!

HTML5 Video is still in the making, and until it's completely stable across all browsers and platforms, you'll need to provide a "workaround" for different scenarios.

For mobile, perhaps you can detect the User-Agent and go from there...

Hope this helps

ContentLicense: CC BY-SA 2.5

Title: Best video format for HTML5?

Body:
From my personal experience with HTML5 Video, I create mp4, ogg, and flv file formats, and use the following implementation:

<video id="movie" width="" height="" preload controls>
   <source id="srcMp4" src="video.mp4" />
   <source id="srcOgg" src="video.ogg" />
   <object id="flowplayer" name="flowplayer" width="480" height="352" data="http://releases.flowplayer.org/swf/flowplayer-3.2.5.swf"
            type="application/x-shockwave-flash">
      <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.5.swf" />
      <param name="allowfullscreen" value="true" />
      <param name="flashvars"
    value='config={"clip":"http://domain.com/video.flv"}' />
   </object>
</video>

The MP4 format is provided first, due to a previous bug in iPad which only sees the first source listed.

If the browser can't play the MP4 version, it tries to load the Ogg version.  If that fails, it uses Flowplayer (flash) as a fallback.

I know you're looking for a solution without flash as a fallback, but in my opinion, we're just not there yet.  People are still using IE6 for crying out loud!

HTML5 Video is still in the making, and until it's completely stable across all browsers and platforms, you'll need to provide a "workaround" for different scenarios.

For mobile, perhaps you can detect the User-Agent and go from there...

Hope this helps


问:
Copy image to resources Xamarin
I have a Xamarin Forms project in which I need the user to be able to "load" an image. I can already press a button and search for a file using FilePicker like this:

```<code>async void OnUpload(object sender, EventArgs e)
        {
            try
            {
                FileData filedata = await CrossFilePicker.Current.PickFile();
                // the dataarray of the file will be found in filedata.DataArray
                // file name will be found in filedata.FileName;
                //etc etc.
            }
            catch (Exception ex)
            {
            }
        }
</code>```

What I would need now is to copy that "filedata" (the image) to the resource folder of the project in order to access to the file easily. I have tried:

```<code>await CrossFilePicker.Current.SaveFile(filedata.FileName);
</code>```

but it doesn't save any file into the project folder.
Moreover, I only need it to work on UWP and Android.

答:
The SaveFile method saves it in a very specific folder.

If you want to save it somewhere of your choosing you have to implement it with the DependencyService. IO operations are very specific to the OS, so are the filepaths. I will give you a simple example for you to build on.

Start with defining an interface in your shared code, like so:

```<code>public interface IFileManager
{
    void SaveFile(Stream stream);
}
</code>```

Of course, it can have other methods as well, or extra parameters if you would like to specify things like filename, that is up to you. You would also probably like some kind of return value to know what happened.

Now, per platform implement this interface. For example for Android, it could look like this:

```<code>[assembly: Xamarin.Forms.Dependency (typeof (FileManager_Android))]

public class FileManager_Android : IFileManager
{
    public void SaveFile(Stream stream)
    {
        var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);

        string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
        string filePath = System.IO.Path.Combine(dir, name);

        try
        {
            System.IO.File.WriteAllBytes(filePath, imageData);
        }
        catch (Exception ex)
        {
            System.Console.WriteLine(e.ToString());
        }
    }
}
</code>```

(Saving code inspired by this link)

This will take the stream and save it to a path of your choosing.

For UWP you will need to implement it as well, which is quite similar, except for the implementation of SaveFile. As far as I know there is no plugin yet which makes this easier for you. There is PCLStorage, but this plugin only seems to work with text files. You could still look into it for inspiration though.

Title: Copy image to resources Xamarin

Body:
I have a Xamarin Forms project in which I need the user to be able to "load" an image. I can already press a button and search for a file using FilePicker like this:

async void OnUpload(object sender, EventArgs e)
        {
            try
            {
                FileData filedata = await CrossFilePicker.Current.PickFile();
                // the dataarray of the file will be found in filedata.DataArray
                // file name will be found in filedata.FileName;
                //etc etc.
            }
            catch (Exception ex)
            {
            }
        }

What I would need now is to copy that "filedata" (the image) to the resource folder of the project in order to access to the file easily. I have tried:

await CrossFilePicker.Current.SaveFile(filedata.FileName);

but it doesn't save any file into the project folder.
Moreover, I only need it to work on UWP and Android.

Body:
The SaveFile method saves it in a very specific folder.

If you want to save it somewhere of your choosing you have to implement it with the DependencyService. IO operations are very specific to the OS, so are the filepaths. I will give you a simple example for you to build on.

Start with defining an interface in your shared code, like so:

public interface IFileManager
{
    void SaveFile(Stream stream);
}

Of course, it can have other methods as well, or extra parameters if you would like to specify things like filename, that is up to you. You would also probably like some kind of return value to know what happened.

Now, per platform implement this interface. For example for Android, it could look like this:

[assembly: Xamarin.Forms.Dependency (typeof (FileManager_Android))]

public class FileManager_Android : IFileManager
{
    public void SaveFile(Stream stream)
    {
        var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);

        string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
        string filePath = System.IO.Path.Combine(dir, name);

        try
        {
            System.IO.File.WriteAllBytes(filePath, imageData);
        }
        catch (Exception ex)
        {
            System.Console.WriteLine(e.ToString());
        }
    }
}

(Saving code inspired by this link)

This will take the stream and save it to a path of your choosing.

For UWP you will need to implement it as well, which is quite similar, except for the implementation of SaveFile. As far as I know there is no plugin yet which makes this easier for you. There is PCLStorage, but this plugin only seems to work with text files. You could still look into it for inspiration though.


问:
R minus in row name makes name sometimes unaccessible
I have an error I cant recreate with smaller examples so I hope anyone has an idea where to look at.

The problem

As described in the code-comments: rownamesX is not found in the rownames of the matrix (But they are there of course). If I print the not-found names, something like this comes out:

hsaâˆ’miRâˆ’00

It should be

hsa-miR-00

Further, the I tested some different approaches:

Code works if I source the subscript directly in Rstudio in the console (ctrl-shift-s hotkey)

Code works if I call the function in the Console (Ctrl-Enter on the line)

Code does not work if the subscript is sourced in the main script by (Ctrl-Enter on the line)

Code does not work if the whole main.R is sourced (ctrl-shift-s hotkey)

My environment:

The data matrix

~200k elements

rownames in the form of "type-type2-number"

colnames (=samples) : "S1", "S2", ...

The call:

A main script

sources a subscript

sources a function

calls the function with the data matrix as parameter

The function:

```<code>myFunction <- function(rownamesX = c("type-type2-number")
                       ,mat){
    indexes <- which(rownames(mat) %in% rownamesX) # This is empty
    mat.part <- mat[indexes, ] # therefore his is empty
    resp <- mat.part[1, ] - mat.part[2, ] # therefore this yields an error
}
</code>```

答:
The mistake was quite easy:
There are more than one "-":

−

-

These two look even more equal in Rstudio than here. So I looked for the first(larger) one when the second (smaller) one was in the rowname

Body:
I have an error I cant recreate with smaller examples so I hope anyone has an idea where to look at.

The problem

As described in the code-comments: rownamesX is not found in the rownames of the matrix (But they are there of course). If I print the not-found names, something like this comes out:

hsaâˆ’miRâˆ’00

It should be

hsa-miR-00

Further, the I tested some different approaches:

Code works if I source the subscript directly in Rstudio in the console (ctrl-shift-s hotkey)

Code works if I call the function in the Console (Ctrl-Enter on the line)

Code does not work if the subscript is sourced in the main script by (Ctrl-Enter on the line)

Code does not work if the whole main.R is sourced (ctrl-shift-s hotkey)

My environment:

The data matrix

~200k elements

rownames in the form of "type-type2-number"

colnames (=samples) : "S1", "S2", ...

The call:

A main script

sources a subscript

sources a function

calls the function with the data matrix as parameter

The function:

myFunction <- function(rownamesX = c("type-type2-number")
                       ,mat){
    indexes <- which(rownames(mat) %in% rownamesX) # This is empty
    mat.part <- mat[indexes, ] # therefore his is empty
    resp <- mat.part[1, ] - mat.part[2, ] # therefore this yields an error
}


问:
How to get epoch time in Redshift?
In my schema I have a created_on field. I want to assign EPOCH time value to it automatically on insert. How to achieve that?</p>

答:
On PostgreSQL (from with redshift was forked) you would do it like this:

```<code>ALTER TABLE sometable ALTER COLUMN created_on SET DEFAULT EXTRACT(EPOCH FROM now())
</code>```

Maybe it works in redshift as well.

Title: How to get epoch time in Redshift?

Body:
On PostgreSQL (from with redshift was forked) you would do it like this:

ALTER TABLE sometable ALTER COLUMN created_on SET DEFAULT EXTRACT(EPOCH FROM now())

Maybe it works in redshift as well.


问:
Setting probability of getting a random number 1 or 2
Is there a way to set a probability control on getting a random value either 1 or 2? Suppose if I want more than 70% of the time it should be 1 and only 30% should be the chance of getting 2 in rand(1,2). Is it possible?

答:
Generate a number between 1 and 10, then if the number is greater than 7, return 2, else return 1

```<code>x = rand(1, 10);
if(x > 7){
    return 2;
}
else {
    return 1;
}
</code>```

You will have 70% and 30% of chance to get the number you want

Body:
Generate a number between 1 and 10, then if the number is greater than 7, return 2, else return 1

x = rand(1, 10);
if(x > 7){
    return 2;
}
else {
    return 1;
}

You will have 70% and 30% of chance to get the number you want


问:
What Angular 2 Tour-of-Heroes files do I need to deploy to a web server not running node
I have the Angular 2 Tour-of-Heroes tutorial running on my local machine, but I would like to deploy it to a server not running node. I've tried to upload the node_modules folder, but it is huge and the environment won't doesn't allow .json files. Needless to say, it doesn't work.

I'm sure that I don't need to the .ts files in the app folder since those are generated when tsc command is run. I also think I don't need the systemjs.js, tsconfig.json, and tslint.json files.

File Structure is:

```<code>app
  app.component.js
  app.component.ts
  app.module.js
  app.module.ts
  main.ts
  main.js
  hero.js
  hero.ts
  hero-detail.component.js
  hero-detail.component.ts
  app.component.spec.js.map
  app.component.js.map
  app.component.spec.ts
  app.module.js.map
node_modules
index.html
package.json
styles.css
systemjs.config.extras.js
systemjs.config.js
tsconfig.json
tslint.json
</code>```

package.json file:

If I don't want to upload all the node modules files, I have a feeling I have to change this package.json file, but I'm not sure how.

```<code>{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
  "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
  "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
  "lint": "tslint ./app/**/*.ts -t verbose",
  "lite": "lite-server",
  "pree2e": "webdriver-manager update",
  "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
  "test-once": "tsc && karma start karma.conf.js --single-run",
  "tsc": "tsc",
  "tsc:w": "tsc -w"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
  "@angular/common": "~2.4.0",
  "@angular/compiler": "~2.4.0",
  "@angular/core": "~2.4.0",
  "@angular/forms": "~2.4.0",
  "@angular/http": "~2.4.0",
  "@angular/platform-browser": "~2.4.0",
  "@angular/platform-browser-dynamic": "~2.4.0",
  "@angular/router": "~3.4.0",

  "angular-in-memory-web-api": "~0.2.4",
  "systemjs": "0.19.40",
  "core-js": "^2.4.1",
  "rxjs": "5.0.1",
  "zone.js": "^0.7.4"
},
"devDependencies": {
  "concurrently": "^3.1.0",
  "lite-server": "^2.2.2",
  "typescript": "~2.0.10",

  "canonical-path": "0.0.2",
  "http-server": "^0.9.0",
  "tslint": "^3.15.1",
  "lodash": "^4.16.4",
  "jasmine-core": "~2.4.1",
  "karma": "^1.3.0",
  "karma-chrome-launcher": "^2.0.0",
  "karma-cli": "^1.0.1",
  "karma-jasmine": "^1.0.2",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~4.0.14",
  "rimraf": "^2.5.4",

  "@types/node": "^6.0.46",
  "@types/jasmine": "^2.5.36"
},
"repository": {}
}
</code>```

Index.html:

I noticed that I don't have a reference to angular.js file, but the tutorial didn't use it.

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
</html>
</code>```

I am not including all the file details as I don't think that they have an impact, but I'm not sure so if you need more details, I will be happy to provide them.

答: Use Angular CLI to create, manage and build the project. Once you build the project using ng build, copy the output files from dist folder and paste these files into a server and point the index.html file.

Body:
I have the Angular 2 Tour-of-Heroes tutorial running on my local machine, but I would like to deploy it to a server not running node. I've tried to upload the node_modules folder, but it is huge and the environment won't doesn't allow .json files. Needless to say, it doesn't work.

I'm sure that I don't need to the .ts files in the app folder since those are generated when tsc command is run. I also think I don't need the systemjs.js, tsconfig.json, and tslint.json files.

File Structure is:

app
  app.component.js
  app.component.ts
  app.module.js
  app.module.ts
  main.ts
  main.js
  hero.js
  hero.ts
  hero-detail.component.js
  hero-detail.component.ts
  app.component.spec.js.map
  app.component.js.map
  app.component.spec.ts
  app.module.js.map
node_modules
index.html
package.json
styles.css
systemjs.config.extras.js
systemjs.config.js
tsconfig.json
tslint.json

package.json file:

If I don't want to upload all the node modules files, I have a feeling I have to change this package.json file, but I'm not sure how.

{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
  "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
  "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
  "lint": "tslint ./app/**/*.ts -t verbose",
  "lite": "lite-server",
  "pree2e": "webdriver-manager update",
  "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
  "test-once": "tsc && karma start karma.conf.js --single-run",
  "tsc": "tsc",
  "tsc:w": "tsc -w"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
  "@angular/common": "~2.4.0",
  "@angular/compiler": "~2.4.0",
  "@angular/core": "~2.4.0",
  "@angular/forms": "~2.4.0",
  "@angular/http": "~2.4.0",
  "@angular/platform-browser": "~2.4.0",
  "@angular/platform-browser-dynamic": "~2.4.0",
  "@angular/router": "~3.4.0",

  "angular-in-memory-web-api": "~0.2.4",
  "systemjs": "0.19.40",
  "core-js": "^2.4.1",
  "rxjs": "5.0.1",
  "zone.js": "^0.7.4"
},
"devDependencies": {
  "concurrently": "^3.1.0",
  "lite-server": "^2.2.2",
  "typescript": "~2.0.10",

  "canonical-path": "0.0.2",
  "http-server": "^0.9.0",
  "tslint": "^3.15.1",
  "lodash": "^4.16.4",
  "jasmine-core": "~2.4.1",
  "karma": "^1.3.0",
  "karma-chrome-launcher": "^2.0.0",
  "karma-cli": "^1.0.1",
  "karma-jasmine": "^1.0.2",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~4.0.14",
  "rimraf": "^2.5.4",

  "@types/node": "^6.0.46",
  "@types/jasmine": "^2.5.36"
},
"repository": {}
}

Index.html:

I noticed that I don't have a reference to angular.js file, but the tutorial didn't use it.

<!DOCTYPE html>

    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <my-app>Loading AppComponent content here ...</my-app>

I am not including all the file details as I don't think that they have an impact, but I'm not sure so if you need more details, I will be happy to provide them.


问:
How to insert words in 2D array with delimiters? Using BASH script
In my text file I have this:

wordA|wordC

wordB|wordD

I would like to have this array:

```<code>   arr=(wordA|wordC wordB|wordD)
   arr[0]=(wordA wordC)
   arr[0][0]=(wordA)
   arr[0][1]=(wordC)
   arr[1]=(wordB wordD)
   arr[1][0]=(wordB)
   arr[1][1]=(wordD)
</code>```

EDIT: If this is not possible, how can I have this array:

```<code>   arr1=(wordA wordB)
   arr2=(wordC wordD)
</code>```

答:
As already mentioned Bash does not support true 2D arrays, but this can be simulated using associative arrays.

Something like this seems to work ok in my tests:

```<code>a=$'a|c\nb|d'
echo "$a" && echo

declare -A array
IFS=$'\n' read -r -d '' -a arr1 <<<"$a"
#declare -p arr1
for ((i=0;i<"${#arr1[@]}";i++));do
  IFS="|" read -r -a arr2 <<<"${arr1[$i]}"
  for ((k=0;k<"${#arr2[@]}";k++));do
    array[$i,$k]="${arr2[$k]}"
  done
done
declare -p array
</code>```

Output:

```<code>a|c
b|d

declare -A array='([0,0]="a" [0,1]="c" [1,0]="b" [1,1]="d" )'
</code>```

So we have created an associative array with name "array" that can be used in the format:

```<code>echo "${array[1,0]}"
#Output
b
</code>```

You can itterate through all the keys of array either with classic double for loops or simpler with

```<code>for key in "${!array[@]}";do
echo "$key - ${array[$key]}"
done
0,0 - a
0,1 - c
1,0 - b
1,1 - d
</code>```

Body:
In my text file I have this:

wordA|wordC

wordB|wordD

I would like to have this array:

   arr=(wordA|wordC wordB|wordD)
   arr[0]=(wordA wordC)
   arr[0][0]=(wordA)
   arr[0][1]=(wordC)
   arr[1]=(wordB wordD)
   arr[1][0]=(wordB)
   arr[1][1]=(wordD)

EDIT: If this is not possible, how can I have this array:

   arr1=(wordA wordB)
   arr2=(wordC wordD)

Body:
As already mentioned Bash does not support true 2D arrays, but this can be simulated using associative arrays.

Something like this seems to work ok in my tests:

a=$'a|c\nb|d'
echo "$a" && echo

declare -A array
IFS=$'\n' read -r -d '' -a arr1 <<<"$a"
#declare -p arr1
for ((i=0;i<"${#arr1[@]}";i++));do
  IFS="|" read -r -a arr2 <<<"${arr1[$i]}"
  for ((k=0;k<"${#arr2[@]}";k++));do
    array[$i,$k]="${arr2[$k]}"
  done
done
declare -p array

Output:

a|c
b|d

declare -A array='([0,0]="a" [0,1]="c" [1,0]="b" [1,1]="d" )'

So we have created an associative array with name "array" that can be used in the format:

echo "${array[1,0]}"
#Output
b

You can itterate through all the keys of array either with classic double for loops or simpler with

for key in "${!array[@]}";do
echo "$key - ${array[$key]}"
done
0,0 - a
0,1 - c
1,0 - b
1,1 - d


问:
Automating HP Quality Center with Python or Java
We have a project that uses HP Quality Center and one of the regular issues we face is people not updating comments on the defect.

So I was thinkingif we could come up with a small script or tool that could be used to periodically throw up a reminder and force the user to update the comments.

I came across the Open Test Architecture API and was wondering if there are any good Python or java examples for the same that I could see.

Thanks
Hari

答:
You can use a new Test and select type (VPXP_API) which allow script to run.  The good thing there is that you'd have the function definition ready to be dragged from within QC instead of having to heavily rely on doc.
I've done an implementation in Python running some script from within QC still using its API but via a QC test which is handy to retrieve directly the result (Output) etc.. going through some shell command which can then call any script on any server etc...</p>


问:
Implementing Breakpoint Read/Write on PowerPC
How are breakpoint read/write implemented? Note that this is different from breakpoint execute.

The idea is to start off with a data memory address and then find the assembly instruction(s) which read/write from/to that address. In theory, we would have to check the registers and the next instruction being executed (taking into account displacement offsets) in order to find out whether this is true. Let's say the current instruction is a "store word": stw r0, 4 (r31) so it writes to address r31 + 4. We can find out whether this breaks by reading the value in r31, adding 4 and checking if this is equal to the initial data address.

However, this seems infeasible since with C programming you cannot monitor every instruction execution in assembly I believe. How is this being done in general or specific to PowerPC? Are there any special assembly instructions or debug registers which simplify this?

答: Is paging turned on? If yes, you could mark the page with the variable as unwritable, trap the resulting protection fault, check if it's a write to the variable and halt execution if it is. This might be a bit slow when the page contains other frequently used variables, though.</p>


问:
How to extract multiple words from a line using shell script
I need to extract the name of root CN of a website stored inside a file as shown below.

```<code>google.com   CN=Google Internet Authority G2
youtube.com   CN=Google Internet Authority G2
</code>```

I want to extract this portion from the line "Google Internet Authority G2" and count the occurrence in the file.

I tried using this command, but I don't know the proper regex to be used for it. Can somebody help?

```<code>cat RootCertificates | tr -d '*CN='  | sort | uniq -c
</code>```

答:
Maybe grep

```<code>  grep -o 'CN=.*' file | sort | uniq -c
  2 CN=Google Internet Authority G2
</code>```

or if you don't want the CNusing your input

```<code>cut -d "=" -f2 file | sort | uniq -c
2 Google Internet Authority G2
</code>```

Body:
I need to extract the name of root CN of a website stored inside a file as shown below.

google.com   CN=Google Internet Authority G2
youtube.com   CN=Google Internet Authority G2

I want to extract this portion from the line "Google Internet Authority G2" and count the occurrence in the file.

I tried using this command, but I don't know the proper regex to be used for it. Can somebody help?

cat RootCertificates | tr -d '*CN='  | sort | uniq -c

Body:
Maybe grep

  grep -o 'CN=.*' file | sort | uniq -c
  2 CN=Google Internet Authority G2

or if you don't want the CNusing your input

cut -d "=" -f2 file | sort | uniq -c
2 Google Internet Authority G2


问:
Android button not working on click login
This is my code for login page but problem is that login button not working.
When I leave boxes empty the button works and give message enter valid email and password but when I fill boxes and clicked on the button, nothing happening.
Please help me.

```<code>   jlet1 = (EditText) findViewById(R.id.let1);
    jlet2 = (EditText) findViewById(R.id.let2);
    jlb1=(Button)findViewById(R.id.lb1);
    builder = new AlertDialog.Builder(login.this);

    jlb1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            email = jlet1.getText().toString();
            pwd = jlet2.getText().toString();
            if (email.equals("") || pwd.equals("")) {
                builder.setTitle("Oops wrong turn");
                displayAlert("Enter a valid Email and Password");
            }
            else{
            StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray=new JSONArray(response);
                        JSONObject jsonObject=jsonArray.getJSONObject(0);
                        String code=jsonObject.getString("code");
                        if (code.equals("login_failed")){
                            builder.setTitle("Login Error");
                            displayAlert(jsonObject.getString("message"));
                        }
                        else{
                            Intent in= new Intent(login.this,welcome.class);
                            Bundle bundle= new Bundle();
                            bundle.putString("name",jsonObject.getString("name"));
                            in.putExtras(bundle);
                            startActivity(in);

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

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(login.this, "Error Please try again", Toast.LENGTH_SHORT).show();
                    error.printStackTrace();
                }
            })
            {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> params= new HashMap<>();
                    params.put("email_id",email);
                    params.put("password",pwd);
                    return params;
                }
            };
            singleton.getInstance(login.this).addRequest(stringRequest);
            }
        }
    });
}
public void displayAlert(String message){
    builder.setMessage(message);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            jlet1.setText("");
            jlet2.setText("");
        }
    });
    AlertDialog alertDialog= builder.create();
    alertDialog.show();
}
</code>```

my logcat is showing this :

```<code>03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at com.rawat.loginapp.login$1$1.onResponse(login.java:61)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at com.rawat.loginapp.login$1$1.onResponse(login.java:57)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5437)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-29 16:29:46.382 1324-1388/? D/BluetoothManagerService: Message: 300

        <?php
$con=mysql_connect('localhost','root','')or die('connection error');
$db=mysql_select_db('newdb')or die('db error');

    $email_id=$_POST["email_id"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login WHERE email_id='".$email_id."' AND password='".$password."'";
    $chk=mysql_query($sql,$con);
    $response=array();
if(mysql_num_rows($chk)>0){
    $row=mysql_fetch_row($chk);
    $name=$row[0];
    $code="login_success";
    array_push($response,array("code"=>$code,"name"=>$name));
    echo json_encode($response);
}
else{
    $code="login_failed";
    $message="User not found... please try again";
    array_push($response,array("code"=>$code,"message"=>$message));
    echo json_encode($response);
}
    mysql_close($con);
?>
</code>```

答:
```<code> @Override
 public void onResponse(String response) {
 try {
JSONObject mainJsonObject =new JSONOnject(response); // this is main reason for exception.
 //change below logic as per your json getting as string response
 JSONArray jsonArray=mainJsonObject.getJSONArray("name");
  JSONObject jsonObject=jsonArray.getJSONObject(0);
                    String code=jsonObject.getString("code");
                    if (code.equals("login_failed")){
                        builder.setTitle("Login Error");
                        displayAlert(jsonObject.getString("message"));
                    }
                    else{
                        Intent in= new Intent(login.this,welcome.class);
                        Bundle bundle= new Bundle();
                        bundle.putString("name",jsonObject.getString("name"));
                        in.putExtras(bundle);
                        startActivity(in);

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

            }
</code>```

Body:
This is my code for login page but problem is that login button not working.
When I leave boxes empty the button works and give message enter valid email and password but when I fill boxes and clicked on the button, nothing happening.
Please help me.

   jlet1 = (EditText) findViewById(R.id.let1);
    jlet2 = (EditText) findViewById(R.id.let2);
    jlb1=(Button)findViewById(R.id.lb1);
    builder = new AlertDialog.Builder(login.this);

    jlb1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            email = jlet1.getText().toString();
            pwd = jlet2.getText().toString();
            if (email.equals("") || pwd.equals("")) {
                builder.setTitle("Oops wrong turn");
                displayAlert("Enter a valid Email and Password");
            }
            else{
            StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray=new JSONArray(response);
                        JSONObject jsonObject=jsonArray.getJSONObject(0);
                        String code=jsonObject.getString("code");
                        if (code.equals("login_failed")){
                            builder.setTitle("Login Error");
                            displayAlert(jsonObject.getString("message"));
                        }
                        else{
                            Intent in= new Intent(login.this,welcome.class);
                            Bundle bundle= new Bundle();
                            bundle.putString("name",jsonObject.getString("name"));
                            in.putExtras(bundle);
                            startActivity(in);

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

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(login.this, "Error Please try again", Toast.LENGTH_SHORT).show();
                    error.printStackTrace();
                }
            })
            {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> params= new HashMap<>();
                    params.put("email_id",email);
                    params.put("password",pwd);
                    return params;
                }
            };
            singleton.getInstance(login.this).addRequest(stringRequest);
            }
        }
    });
}
public void displayAlert(String message){
    builder.setMessage(message);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            jlet1.setText("");
            jlet2.setText("");
        }
    });
    AlertDialog alertDialog= builder.create();
    alertDialog.show();
}

my logcat is showing this :

03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at com.rawat.loginapp.login$1$1.onResponse(login.java:61)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at com.rawat.loginapp.login$1$1.onResponse(login.java:57)
03-29 16:29:46.265 6804-6804/com.rawat.loginapp W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5437)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-29 16:29:46.266 6804-6804/com.rawat.loginapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-29 16:29:46.382 1324-1388/? D/BluetoothManagerService: Message: 300

        <?php
$con=mysql_connect('localhost','root','')or die('connection error');
$db=mysql_select_db('newdb')or die('db error');

    $email_id=$_POST["email_id"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login WHERE email_id='".$email_id."' AND password='".$password."'";
    $chk=mysql_query($sql,$con);
    $response=array();
if(mysql_num_rows($chk)>0){
    $row=mysql_fetch_row($chk);
    $name=$row[0];
    $code="login_success";
    array_push($response,array("code"=>$code,"name"=>$name));
    echo json_encode($response);
}
else{
    $code="login_failed";
    $message="User not found... please try again";
    array_push($response,array("code"=>$code,"message"=>$message));
    echo json_encode($response);
}
    mysql_close($con);
?>


问:
How to get current user with Discourse API
I'm accessing the Discourse API from python using urlfetch. The Get a single user by username endpoint requires a GET request such as /users/{username}.json

From a browser, this command returns a json response as expected, however from an API call like:

```<code>from google.appengine.api import urlfetch
result = urlfetch.fetch('{}/users/{}.json'.format(domain, username))
</code>```

it returns a HTML page. I've even tried setting the content type to application/json:

```<code>headers = {'Content-Type': 'application/json'}
result = urlfetch.fetch('{}/users/{}.json'.format(domain, username), headers=headers)
</code>```

What am I doing wrong?

答:
Resolved:

Need to add api_key and api_username to GET request:

```<code>result = urlfetch.fetch('{}/users/{}.json?api_key={}&api_username={}'.format(domain, username, discourse_api_key, discourse_api_username))
</code>```

Body:
I'm accessing the Discourse API from python using urlfetch. The Get a single user by username endpoint requires a GET request such as /users/{username}.json

From a browser, this command returns a json response as expected, however from an API call like:

from google.appengine.api import urlfetch
result = urlfetch.fetch('{}/users/{}.json'.format(domain, username))

it returns a HTML page. I've even tried setting the content type to application/json:

headers = {'Content-Type': 'application/json'}
result = urlfetch.fetch('{}/users/{}.json'.format(domain, username), headers=headers)

What am I doing wrong?

Body:
Resolved:

Need to add api_key and api_username to GET request:

result = urlfetch.fetch('{}/users/{}.json?api_key={}&api_username={}'.format(domain, username, discourse_api_key, discourse_api_username))


问:
couchDB , python and authentication
I have installed couchDB v 0.10.0, and am attempting to talk to it via python from Couch class downloaded from couchDB wiki. Problem is:

```<code>Create database 'mydb': {'error': 'unauthorized', 'reason': 'You are not a server admin.'}
</code>```

I hand edited the local.ini file to include my standard osx login and password. I now have full access via futon but no joy WRT python. Is this an http header issue?

At a a loss - thanks!

答:
Just pass it as part of the URI...python-couchdb will parse the user/pass out and use them:

http://user:pass@localhost:5984

Title: couchDB , python and authentication

Body:
I have installed couchDB v 0.10.0, and am attempting to talk to it via python from Couch class downloaded from couchDB wiki. Problem is:

Create database 'mydb': {'error': 'unauthorized', 'reason': 'You are not a server admin.'}

I hand edited the local.ini file to include my standard osx login and password. I now have full access via futon but no joy WRT python. Is this an http header issue?

At a a loss - thanks!


问:
Some youtube videos not playing in UIWebView. Showing - (An error occurred please try again later)
For playing youtube videos, I'm using

```<code>-(void)playYoutubeVideo:(NSString *)youtubeUrl {
  NSString *videoId =  [self extractYoutubeIdFromLink:youtubeUrl];
  NSLog(@"video Id %@",videoId);
  [self playVideoWithId:videoId];
}

- (NSString *)extractYoutubeIdFromLink:(NSString *)link {
  NSString *regexString = @"((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)";
  NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:regexString
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];
  NSArray *array = [regExp matchesInString:link options:0 range:NSMakeRange(0,link.length)];
  if (array.count > 0) {
    NSTextCheckingResult *result = array.firstObject;
    return [link substringWithRange:result.range];
  }
  return nil;
}

- (void)playVideoWithId:(NSString *)videoId {
  NSString *youTubeVideoHTML = @"<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%f', height:'%f', videoId:'%@', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";
  NSString *html = [NSString stringWithFormat:youTubeVideoHTML,300,200, videoId];
  [webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

}
</code>```

I'm getting youtube video ID from the watch url.

Its working fine for the urls like https://www.youtube.com/watch?v=p9mddDM43wE

But, the below youtube video is not playing in UIWebView

https://www.youtube.com/watch?v=CT-fPP1fjDA

Showing the below error,

What might be problem?

Can anyone please clarify?

答:
Recently I faced the same issue in my iOS application where we are loading a YouTube video link inside UIWebView.

After breaking head for long time, it turned out to be the device "date and time" settings problem.

The device date was set to very old. After we updated the settings, the youtube videos started loading inside web view.

Body:
For playing youtube videos, I'm using

-(void)playYoutubeVideo:(NSString *)youtubeUrl {
  NSString *videoId =  [self extractYoutubeIdFromLink:youtubeUrl];
  NSLog(@"video Id %@",videoId);
  [self playVideoWithId:videoId];
}

- (NSString *)extractYoutubeIdFromLink:(NSString *)link {
  NSString *regexString = @"((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)";
  NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:regexString
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];
  NSArray *array = [regExp matchesInString:link options:0 range:NSMakeRange(0,link.length)];
  if (array.count > 0) {
    NSTextCheckingResult *result = array.firstObject;
    return [link substringWithRange:result.range];
  }
  return nil;
}

- (void)playVideoWithId:(NSString *)videoId {
  NSString *youTubeVideoHTML = @"

   ";
  NSString *html = [NSString stringWithFormat:youTubeVideoHTML,300,200, videoId];
  [webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

}

I'm getting youtube video ID from the watch url.

Its working fine for the urls like https://www.youtube.com/watch?v=p9mddDM43wE

But, the below youtube video is not playing in UIWebView

https://www.youtube.com/watch?v=CT-fPP1fjDA

Showing the below error,

What might be problem?

Can anyone please clarify?


答:
Why don't you generate a uniformly distributed random number and then filter the number with an if?</p>

```<code>int x,r;

r=rand() % 100;         // r in the range 0 to 99
if(r<=70){x=1;}
else{x=2;}
</code>```

Title: Setting probability of getting a random number 1 or 2

Body: Is there a way to set a probability control on getting a random value either 1 or 2? Suppose if I want more than 70% of the time it should be 1 and only 30% should be the chance of getting 2 in rand(1,2). Is it possible?

Body:
Why don't you generate a uniformly distributed random number and then filter the number with an if?

int x,r;

r=rand() % 100;         // r in the range 0 to 99
if(r<=70){x=1;}
else{x=2;}


问:
Use calibrated camera get matched points for 3D reconstruction
I am trying to compute the 3D coordinates from several pair of two view points.

First, I used the matlab function estimateFundamentalMatrix() to get the F of the matched points (Number > 8) which is:

```<code>F1 =[-0.000000221102386   0.000000127212463  -0.003908602702784
     -0.000000703461004  -0.000000008125894  -0.010618266198273
      0.003811584026121   0.012887141181108   0.999845683961494]
</code>```

And my camera - taken these two pictures - was pre-calibrated with the intrinsic matrix:

```<code>K = [12636.6659110566, 0, 2541.60550098958
     0, 12643.3249022486, 1952.06628069233
     0, 0, 1]
</code>```

From this information I then computed the essential matrix using:

```<code>E = K'*F*K
</code>```

With the method of SVD, I finally got the projective transformation matrices:

```<code>P1 = K*[ I | 0 ]
</code>```

and

```<code>P2 = K*[ R | t ]
</code>```

Where R and t are:

```<code>R = [ 0.657061402787646 -0.419110137500056  -0.626591577992727
     -0.352566614260743 -0.905543541110692   0.235982367268031
     -0.666308558758964  0.0658603659069099 -0.742761951588233]

t = [-0.940150699101422
      0.320030970080146
      0.117033504470591]
</code>```

I know there should be 4 possible solutions, however, my computed 3D coordinates seemed to be not correct.

I used the camera to take pictures of a FLAT object with marked points. I matched the points by hand (which means there should not be obvious mistake exists about the raw material). But the result turned out to be a surface with a little bit banding.

I guess this might be due to the reason pictures did not processed with distortions (but actually I remember I did).

I just want to know whether this method to solve the 3D reconstruction issue right?   Especially when we already know the camera intrinsic matrix.

Edit by JCraft at Aug.4: I have redone the process and got some pictures showing the problem, I will write another question with detail then post the link.

Edit by JCraft at Aug.4: I have posted a new question: Calibrated camera get matched points for 3D reconstruction, ideal test failed. And @Schorsch really appreciate your help formatting my question. I will try to learn how to do inputs in SO and also try to improve my gramma. Thanks!

答: Flat objects are critical surfaces, not possible to achive your goal from them. try adding two (or more) points off the plane (see Hartley and Zisserman or other text on the matter if still interested)</p>

Body:
I am trying to compute the 3D coordinates from several pair of two view points.

First, I used the matlab function estimateFundamentalMatrix() to get the F of the matched points (Number > 8) which is:

F1 =[-0.000000221102386   0.000000127212463  -0.003908602702784
     -0.000000703461004  -0.000000008125894  -0.010618266198273
      0.003811584026121   0.012887141181108   0.999845683961494]

And my camera - taken these two pictures - was pre-calibrated with the intrinsic matrix:

K = [12636.6659110566, 0, 2541.60550098958
     0, 12643.3249022486, 1952.06628069233
     0, 0, 1]

From this information I then computed the essential matrix using:

E = K'*F*K

With the method of SVD, I finally got the projective transformation matrices:

P1 = K*[ I | 0 ]

and

P2 = K*[ R | t ]

Where R and t are:

R = [ 0.657061402787646 -0.419110137500056  -0.626591577992727
     -0.352566614260743 -0.905543541110692   0.235982367268031
     -0.666308558758964  0.0658603659069099 -0.742761951588233]

t = [-0.940150699101422
      0.320030970080146
      0.117033504470591]

I know there should be 4 possible solutions, however, my computed 3D coordinates seemed to be not correct.

I used the camera to take pictures of a FLAT object with marked points. I matched the points by hand (which means there should not be obvious mistake exists about the raw material). But the result turned out to be a surface with a little bit banding.

I guess this might be due to the reason pictures did not processed with distortions (but actually I remember I did).

I just want to know whether this method to solve the 3D reconstruction issue right?   Especially when we already know the camera intrinsic matrix.

Edit by JCraft at Aug.4: I have redone the process and got some pictures showing the problem, I will write another question with detail then post the link.

Edit by JCraft at Aug.4: I have posted a new question: Calibrated camera get matched points for 3D reconstruction, ideal test failed. And @Schorsch really appreciate your help formatting my question. I will try to learn how to do inputs in SO and also try to improve my gramma. Thanks!


问:
How to Merge or Combine return data from model in Controller Laravel
I have 3 function, it is a() b() and c()

and then, function a() returned :

```<code>{
    id    =>
    total1 =>
}
</code>```

function b() returned like funcion a() too, but have a different value (total1 and total2)

function c() returned :

```<code>{
    id   => //same value just like function a or b
    name =>
}
</code>```

```<code>$a = $model->a(); // from function a();
$b = $model->b(); // from function b();
$c = $model->c(); // from function c();
</code>```

i want combine that 3 returned values into array like this :

```<code>array = ['id','name', 'total1', 'total2']
</code>```

any idea ? Thanks

答:
You can use array_merge() and array_keys():

```<code>array_keys(array_merge($a, $b, $c));
</code>```

If variables are not arrays, convert them to arrays with toArray() or json_decode() first.

If functions return Laravel collections, you can use merge() and keys() helpers.

Body:
I have 3 function, it is a() b() and c()

and then, function a() returned :

{
    id    =>
    total1 =>
}

function b() returned like funcion a() too, but have a different value (total1 and total2)

function c() returned :

{
    id   => //same value just like function a or b
    name =>
}

$a = $model->a(); // from function a();
$b = $model->b(); // from function b();
$c = $model->c(); // from function c();

i want combine that 3 returned values into array like this :

array = ['id','name', 'total1', 'total2']

any idea ? Thanks

Body:
You can use array_merge() and array_keys():

array_keys(array_merge($a, $b, $c));

If variables are not arrays, convert them to arrays with toArray() or json_decode() first.

If functions return Laravel collections, you can use merge() and keys() helpers.


问:
React - Setting state immediately after an async action
So I have a button. When you click on that button, it takes you to an onSubmit function which looks like this:

```<code>  onSubmit(e) {
      e.preventDefault();
      this.props.nextSentence(); //this is async

      this.setState({ //this is not yet updating with the right values then
          inputField: this.props.activePupil.name
      });
  }
</code>```

However: this.props.nextSentence(); is async, so when I set my state immediately after, there are no changes. Right now I have a second button which refers to a second function which just sets the state again. I would like to have this happen automatic though. How could I do this?

答:
async actions are normally either Promises or functions with callbacks.

In case of a Promise you need to use .then like below

```<code>this.props.nextSentence().then(() => {
  this.setState({...});
})
</code>```

And in case of a function with callback

```<code>this.props.nextSentence(() => {
  this.setState({...})
})
</code>```

However keep in mind than you can get the returned response of your async action and use it to update your state. which is normally the case.

For example

```<code>//here response is a json object returned from server
this.props.nextSentence().then((response) => {
  this.setState({
    data: response.data
  });
})
</code>```

Body:
So I have a button. When you click on that button, it takes you to an onSubmit function which looks like this:

  onSubmit(e) {
      e.preventDefault();
      this.props.nextSentence(); //this is async

      this.setState({ //this is not yet updating with the right values then
          inputField: this.props.activePupil.name
      });
  }

However: this.props.nextSentence(); is async, so when I set my state immediately after, there are no changes. Right now I have a second button which refers to a second function which just sets the state again. I would like to have this happen automatic though. How could I do this?

Body:
async actions are normally either Promises or functions with callbacks.

In case of a Promise you need to use .then like below

this.props.nextSentence().then(() => {
  this.setState({...});
})

And in case of a function with callback

this.props.nextSentence(() => {
  this.setState({...})
})

However keep in mind than you can get the returned response of your async action and use it to update your state. which is normally the case.

For example

//here response is a json object returned from server
this.props.nextSentence().then((response) => {
  this.setState({
    data: response.data
  });
})


问:
Argmax of each row or column in scipy sparse matrix
scipy.sparse.coo_matrix.max returns the maximum value of each row or column, given an axis. I would like to know not the value, but the index of the maximum value of each row or column. I haven't found a way to make this in an efficient manner yet, so I'll gladly accept any help.

答: From scipy version 0.19, both csr_matrix and csc_matrix support argmax() and argmin() methods.


问:
How can i integrate Imagemagick with Meteor/angular2 project
I am attempting to use Imagemagick to manipulate images that are uploaded by a user.I already install Imagemagick package with meteor npm install imagemagick. but what I need now is how i can import this package to use it in my Meteor project

this is my code

```<code>import {Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
import { Meteor } from 'meteor/meteor';

import template from './tpl.dashboard.component.html';

@Component({
  selector: 'traitement_par_lot',
  template
})
export class TPLcomponent implements OnInit {

 constructor() {}

 ngOnInit() {
    var features = Imagemagick.identify('assets/img/unkown-user.jpg');
    console.log(features);
    });
  }
</code>```

for the moment I get error 'Cannot find name 'Imagemagick' '

答:
You cannot use the Imagemagick symbol without importing or declaring it first. You posted your code as a screenshot so I would need to use Photoshop to fix it which is obviously not worth the trouble. Suffice it to say that you need to import every module that you're going to use, no matter if it's Imagemagick or anything else. See those Meteor packages:

https://atmospherejs.com/mrt/imagemagick

https://atmospherejs.com/classcraft/imagemagick

And keep in mind that ImageMagick is something that actually works on the backend, not on the frontend. You can use frontend code to make it run on the backend and that's what you should be doing but you cannot use it on the frontend alone without passing any data between the frontend and backend. If you want to manipulate images just on the frontend then you need to use Canvas or some library that uses Canvas for that.

Body:
I am attempting to use Imagemagick to manipulate images that are uploaded by a user.I already install Imagemagick package with meteor npm install imagemagick. but what I need now is how i can import this package to use it in my Meteor project

this is my code

import {Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
import { Meteor } from 'meteor/meteor';

import template from './tpl.dashboard.component.html';

@Component({
  selector: 'traitement_par_lot',
  template
})
export class TPLcomponent implements OnInit {

 constructor() {}

 ngOnInit() {
    var features = Imagemagick.identify('assets/img/unkown-user.jpg');
    console.log(features);
    });
  }

for the moment I get error 'Cannot find name 'Imagemagick' '


答:
You can cast the results to array

```<code>$a = $model->a()->toArray(); // from function a();
$b = $model->b()->toArray(); // from function b();
$c = $model->c()->toArray(); // from function c();
</code>```

and then

```<code>$data= array_merge($a , $b, $c)
</code>```

Title: How to Merge or Combine return data from model in Controller Laravel

Body:
You can cast the results to array

$a = $model->a()->toArray(); // from function a();
$b = $model->b()->toArray(); // from function b();
$c = $model->c()->toArray(); // from function c();

and then

$data= array_merge($a , $b, $c)


问:
How to put hyperlink in jquery datatables plugin in codeigniter
I am using DataTables to generate a table. There is a column containing username

For example: ...

I need every row in this column to have a hyperlink when anyone clicks on username then it redirects to edit page, For example, the first row would be a hyperlink to view?id=1321755 etc.

What is the simplest way I can do so?

Here is my code of view:

```<code><table id="book-table" class="table table-bordered table-striped table-hover">
     <thead>
     <tr class="">
      <th>Name</th>
      <th>Date</th>
      <th>Work</th>
      <th>Partner</th>
      <th>Director</th>
      <th>Time</th>
      <th>Task</th>
      <th>Status</th>
    </tr>
     </thead>
     <tbody>
     </tbody>
     </table>

<script type="text/javascript">
$(document).ready(function() {
    $('#book-table').DataTable({
        "ajax": {
            url : "<?php echo site_url("digital_admin/hodm/books_page") ?>",
            type : 'GET'
        },
    });
});
</script>
</code>```

Here is my controller code:

```<code>public function books_page()
     {

          // Datatables Variables
          $draw = intval($this->input->get("draw"));
          $start = intval($this->input->get("start"));
          $length = intval($this->input->get("length"));

          $books = $this->pojo->get_books();

          $data = array();

          foreach($books->result() as $r) {

               $data[] = array(
                    $r->user_name,
                    $r->date,
                    $r->t_name,
                    $r->partner,
                    $r->director,
                    $r->duration,
                    $r->task,
                    $r->status
               );
          }

          $output = array(
               "draw" => $draw,
                 "recordsTotal" => $books->num_rows(),
                 "recordsFiltered" => $books->num_rows(),
                 "data" => $data
            );
          echo json_encode($output);
          exit();
     }
</code>```

Kindly help me to find the answer

答:
Easiest way would be to put it directly in the array something like:

```<code>      foreach($books->result() as $r) {

           $data[] = array(
                '<a href="/view?id='.$r->user_id.'" >'. $r->user_name .'</a>',
                $r->date,
                $r->t_name,
                $r->partner,
                $r->director,
                $r->duration,
                $r->task,
                $r->status
           );
      }
</code>```

But be aware that the sorting on such column in DataTables may not apply to the actual username shown, but the whole content string. Replace /view?id='.$r->user_id.' in the above example with the id and url you want to use.

Note that json_encode() escapes some characters, for instance the double quotes, so you might need to do add backslash before them:

```<code>'<a href=\"/view?id='.$r->user_id.'\" >'. $r->user_name .'</a>'
</code>```

Body:
I am using DataTables to generate a table. There is a column containing username

For example: ...

I need every row in this column to have a hyperlink when anyone clicks on username then it redirects to edit page, For example, the first row would be a hyperlink to view?id=1321755 etc.

What is the simplest way I can do so?

Here is my code of view:

      Name
      Date
      Work
      Partner
      Director
      Time
      Task
      Status

Here is my controller code:

public function books_page()
     {

          // Datatables Variables
          $draw = intval($this->input->get("draw"));
          $start = intval($this->input->get("start"));
          $length = intval($this->input->get("length"));

          $books = $this->pojo->get_books();

          $data = array();

          foreach($books->result() as $r) {

               $data[] = array(
                    $r->user_name,
                    $r->date,
                    $r->t_name,
                    $r->partner,
                    $r->director,
                    $r->duration,
                    $r->task,
                    $r->status
               );
          }

          $output = array(
               "draw" => $draw,
                 "recordsTotal" => $books->num_rows(),
                 "recordsFiltered" => $books->num_rows(),
                 "data" => $data
            );
          echo json_encode($output);
          exit();
     }

Kindly help me to find the answer

Body:
Easiest way would be to put it directly in the array something like:

      foreach($books->result() as $r) {

           $data[] = array(
                '<a href="/view?id='.$r->user_id.'" >'. $r->user_name .'</a>',
                $r->date,
                $r->t_name,
                $r->partner,
                $r->director,
                $r->duration,
                $r->task,
                $r->status
           );
      }

But be aware that the sorting on such column in DataTables may not apply to the actual username shown, but the whole content string. Replace /view?id='.$r->user_id.' in the above example with the id and url you want to use.

Note that json_encode() escapes some characters, for instance the double quotes, so you might need to do add backslash before them:

'<a href=\"/view?id='.$r->user_id.'\" >'. $r->user_name .'</a>'


问:
Very basic usage of sitecore search
I am trying to setup a very basic search index, to index all items in a specific folder. I haven't really used much searching, but I'm trying to use out-of-the-box features, because its a very simple search. I just want to index all the fields. The sitecore documentation really doesn't provide much information - I've read a few blogs, and they all seem to suggest that I need the advanced database crawler (http://trac.sitecore.net/AdvancedDatabaseCrawler) - basically, something to the effect of 'it won't work without a custom crawler).

Is this right? I just want to create a simple index, and then start using it. What is the simplest way to do this, without any shared modules or otherwise? I went through the documentation on sitecore, but its not very clear (at least to me). It defines different elements of the index configuration in web.config, but doesn't really explain what they do, and what values are available. Maybe I'm not looking in the right place..

答: Then you can download Lucene Index Viewer extension for Sitecore to view the index or you can download the Lucene Tool to view the indexes. See if you can populate the documents (files in your indexes). These are called 'Documents' in Lucene and technically these documents are content item present under the node that you specified.</p>

Title: Very basic usage of sitecore search


问:
How to Add Static Members in EcmaScript 5
I want to add a static function to a class in EcmaScript 5 JavaScript. My class definition looks as follows:

```<code>var Account = {};

Object.defineProperty(Account, 'id', {
    value : null
});
</code>```

And I would create a new instance like this:

```<code>var theAccount = Object.create(Account);
theAccount.id = 123456;
</code>```

Now I want to add a static function to the Account class. If I had created the Account class using a constructor function and the prototype property like this:

```<code>var Account = function () {
    this.id = null;
};
</code>```

...I could just do:

```<code>Account.instances = {};

Account.createInstance = function () {
    var account = new Account();
    account.id = uuid.v4();
    Account.instances[account.id] = account;
    return account;
};
</code>```

But since I am using Object.defineProperty and not the prototype property to add members, Account.instances and Account.createInstance would also be instantiated when calling Object.create and therefore be properties of the instance.

How do i add a static member to a class when using EcmaScript 5 style object creation?

答:
For ES 5 if you want static methods:

```<code>// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
    alert("I am a Person object ;)");
};

// An instance method;
// All Person objects will have this method
Person.prototype.setName = function(nameIn) {
    this.name = nameIn;
}
</code>```

see @https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

Body:
I want to add a static function to a class in EcmaScript 5 JavaScript. My class definition looks as follows:

var Account = {};

Object.defineProperty(Account, 'id', {
    value : null
});

And I would create a new instance like this:

var theAccount = Object.create(Account);
theAccount.id = 123456;

Now I want to add a static function to the Account class. If I had created the Account class using a constructor function and the prototype property like this:

var Account = function () {
    this.id = null;
};

...I could just do:

Account.instances = {};

Account.createInstance = function () {
    var account = new Account();
    account.id = uuid.v4();
    Account.instances[account.id] = account;
    return account;
};

But since I am using Object.defineProperty and not the prototype property to add members, Account.instances and Account.createInstance would also be instantiated when calling Object.create and therefore be properties of the instance.

How do i add a static member to a class when using EcmaScript 5 style object creation?

Body:
For ES 5 if you want static methods:

// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
    alert("I am a Person object ;)");
};

// An instance method;
// All Person objects will have this method
Person.prototype.setName = function(nameIn) {
    this.name = nameIn;
}

see @https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/