问:
perl false values are not printed
when I print false values in perl I get nothing printed. Probably this is a very simple question, but I searched google without finding an answer.

Code:

```<code>print "2 == 2 :", 2 == 2, "\n";
print "2 != 2 :", 2 != 2, "\n";
print "2 == 3 :", 2 == 3, "\n";
print "2 != 3 :", 2 != 3", "\n";
</code>```

This is the output:

```<code>2 == 2:1
2 != 2 :
2 == 3 :
2 != 3 :1
</code>```

why the false value is not being printed?

答:
You shouldn't expect to be able to print Boolean values. All that you should expect to be able to do with Boolean values is to ask them if they are true or false.

As it happens, you often can print Perl's Boolean values and get a useful result. Most Perl Boolean operations will give you 1 for true and an empty string for false. [Update: Strictly speaking, what you're getting is a dualvar with the values '' and 0.] That's what you're seeing here. The false value is being printed, but it's an empty string.

If you want to see something specific to indicate your false value, then you need to implement that yourself.

```<code>print "2 == 3 :", (2 == 3 ? 'true' : 'false'), "\n";
</code>```

But really, Boolean values aren't intended for displaying.

Title: perl false values are not printed

Body:
when I print false values in perl I get nothing printed. Probably this is a very simple question, but I searched google without finding an answer.

Code:

print "2 == 2 :", 2 == 2, "\n";
print "2 != 2 :", 2 != 2, "\n";
print "2 == 3 :", 2 == 3, "\n";
print "2 != 3 :", 2 != 3", "\n";

This is the output:

2 == 2:1
2 != 2 :
2 == 3 :
2 != 3 :1

why the false value is not being printed?

Body:
You shouldn't expect to be able to print Boolean values. All that you should expect to be able to do with Boolean values is to ask them if they are true or false.

As it happens, you often can print Perl's Boolean values and get a useful result. Most Perl Boolean operations will give you 1 for true and an empty string for false. [Update: Strictly speaking, what you're getting is a dualvar with the values '' and 0.] That's what you're seeing here. The false value is being printed, but it's an empty string.

If you want to see something specific to indicate your false value, then you need to implement that yourself.

print "2 == 3 :", (2 == 3 ? 'true' : 'false'), "\n";

But really, Boolean values aren't intended for displaying.


来源: stackexchange

问:
Why call method of window object explicitly, performance will be lower than inexplicitly
In web environment think this code:

```<code>window.alert('foo'); //code1
alert('foo');        //code2
</code>```

Why code2 is higher than code1 in performance? Why does this happened?

答:
First, remember that many globals (including all of the traditional predefined globals) are properties of the global object, and that on browsers that global object is the window object. window isn't special, it's just a predefined global that refers to the global object. alert is also a predefined global.

window.alert(...) is slower than alert(...) because in window.alert(...) the JavaScript engine first has to:

Go look up the identifier window, which it ultimately finds as a property of the global object, then

Look up alert in that object's properties, then

Call the function it found

In alert(...), it only has to:

Go look up the identifier alert, which it ultimately finds as a property of the global object, then

Call the function it found

So instead of looking for two things, it only has to look for one.

Less work = faster performance.

Having said that, two observations:

The speed with which you show an alert is...not usually important. :-) alert does, after all, seize up the JavaScript engine until the user dismisses it.

Even with something that doesn't seize up the JavaScript engine, the difference between window.xyz(...) and xyz(...) will be trivially small in most cases. Typically you see window.xyz(...) for other reasons (such as some other xyz being in scope when you want to access the global one). (I'm not saying they're good reasons; typically you can avoid that, and of course one tries to avoid globals wherever possible anyway...)

If performance calling a global function matters (by definition, this means you're calling it a lot), you probably don't want to use the global reference to it anyway; grab a local reference to it in your inner scope (var f = theGlobalFunction;) and then use f(); to call it repeatedly. This avoids both lexical environment traversal and lookup on the global object. And again: Only matters in very rare cases; don't do it until/unless you've identified an observable performance problem and narrowed it down to the global function call. :-)

The time for that first lookup (the global) depends on how deeply nested the code is (and thus how many lexical environment objects need searching before the global one is reached) and how many properties the global object has. The second part, looking up the property, is only dependent on the second one. A truly hideously massive mass of globals (such as is created if you use ids on lots of elements, since those get added as automatic globals) can conceivably slow down global lookup time.

ContentLicense: CC BY-SA 3.0

Body:
In web environment think this code:

window.alert('foo'); //code1
alert('foo');        //code2

Why code2 is higher than code1 in performance? Why does this happened?


问:
Sed how to add variable with vertical bar to the end of first line
i want to append variable with string to the first line of my_file

sed -i "1 s/$/   $my_variable/" ~/my_file

Now i have this:

42 192.168.1.1   string_from_my_variable

It works. But the task become harder, now i need to add delimiter before string_from_my_variable

I tried to sed -i "1 s#$#   \|\$my_variable#" ~/my_file, of course it does not help. I need to have this:

42 192.168.1.1   | string_from_my_variable

How can i do this ? Thanks for your attention.

答:
i have found:

sed -i "1 s/$/   \|$my_variable/" ~/my_file


问:
AWS RDS Storage didnt decrease after housekeeping database
Im Currently using AWS RDS on my system, and my storage is too big.
And then i house keeping them and delete about 200 TB.
But in my billing the storage didnt decrease at all.
How can i decrease my storage on AWS RDS ?</p>

答: You can't decrease storage as you provision upfront. The only way to decrease storage is dump your database to disk on another (EC2?) server and create a new RDS instance with less diskspace.</p>


问:
Weird graph in Linear regression using pyplot
I am plotting a Linear Regression model using pyplot. Below is my code.

```<code>plt.scatter(X_train, y_train, color ='red')
plt.show()
</code>```

When I plot using the above code, the plot is as shown below:

I then plotted the line graph using the code below:

```<code>plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.show()
</code>```

It shows a line as expected.

But when I try to plot both of them together, the graph is getting messed up as shown below:

```<code>plt.scatter(X_train, y_train, color ='red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.show()
</code>```

Please let me know if I have to do any extra coding to plot a Linear regression graph properly.

答:
Pyplot connects the dots between points in the order of their occurrence in X_train, but there's usually nothing known about the ordering of that. It's rarely sorted. You're going to need to sort your array before plotting it.

```<code>sorted_indices = numpy.argsort(X_train)
sorted_X = X_train[sorted_indices]
plt.plot(sorted_X, regressor.predict(sorted_X), color = 'blue')
</code>```

Body:
I am plotting a Linear Regression model using pyplot. Below is my code.

plt.scatter(X_train, y_train, color ='red')
plt.show()

When I plot using the above code, the plot is as shown below:

I then plotted the line graph using the code below:

plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.show()

It shows a line as expected.

But when I try to plot both of them together, the graph is getting messed up as shown below:

plt.scatter(X_train, y_train, color ='red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.show()

Please let me know if I have to do any extra coding to plot a Linear regression graph properly.

Body:
Pyplot connects the dots between points in the order of their occurrence in X_train, but there's usually nothing known about the ordering of that. It's rarely sorted. You're going to need to sort your array before plotting it.

sorted_indices = numpy.argsort(X_train)
sorted_X = X_train[sorted_indices]
plt.plot(sorted_X, regressor.predict(sorted_X), color = 'blue')


问:
How to whereHas when use belongsToMany relation
I got a problem, When try to use whereHas in this case

Table users.

```<code>----------------
| id | name    |
----------------
| 1  | AAA     |
| 2  | BBB     |
| 3  | CCC     |
----------------
</code>```

Table subjects.

```<code>------------------
| id | title     |
------------------
| 1  | Subject 1 |
| 2  | Subject 2 |
------------------
</code>```

Table subject_user.

```<code>------------------------
| user_id | subject_id |
------------------------
| 1       | 1          |
| 2       | 1          |
| 1       | 2          |
| 3       | 2          |
------------------------
</code>```

in Subject Model

```<code>...

public function User()
{
    return $this->belongsToMany(User::class, 'subject_user');
}

...
</code>```

When I want to find subject by user_id with this query.

In this case Auth::id() == 1 and $request->user_id == 3

```<code>$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->whereIn('user_id', [Auth::id(), $request->user_id]);
})->get();
</code>```

With this query, I got subjects 1 and 2. That was a wrong result. That must got only subject 2.

Then I try this.

```<code>$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->where('user_id', Auth::id())->where('user_id', $request->user_id);
})->get();
</code>```

It would not get any subjects.

What query do I use in this case to get only subject 2.

答:
@Lloople from your answer, I got an idea.</p>

```<code>$subject = Auth::user()->Subject()->whereHas('User', function ($query) use ($request) {
    $query->where('user_id', $request->id);
})->first();
</code>```

Body:
I got a problem, When try to use whereHas in this case

Table users.

----------------
| id | name    |
----------------
| 1  | AAA     |
| 2  | BBB     |
| 3  | CCC     |
----------------

Table subjects.

------------------
| id | title     |
------------------
| 1  | Subject 1 |
| 2  | Subject 2 |
------------------

Table subject_user.

------------------------
| user_id | subject_id |
------------------------
| 1       | 1          |
| 2       | 1          |
| 1       | 2          |
| 3       | 2          |
------------------------

in Subject Model

...

public function User()
{
    return $this->belongsToMany(User::class, 'subject_user');
}

...

When I want to find subject by user_id with this query.

In this case Auth::id() == 1 and $request->user_id == 3

$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->whereIn('user_id', [Auth::id(), $request->user_id]);
})->get();

With this query, I got subjects 1 and 2. That was a wrong result. That must got only subject 2.

Then I try this.

$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->where('user_id', Auth::id())->where('user_id', $request->user_id);
})->get();

It would not get any subjects.

What query do I use in this case to get only subject 2.

Body:
@Lloople from your answer, I got an idea.

$subject = Auth::user()->Subject()->whereHas('User', function ($query) use ($request) {
    $query->where('user_id', $request->id);
})->first();


问:
displaying ajax results in textbox
From my code, it displays the hall input type tag inside the textbox.

I want only the value to be displayed.

ajax function:

```<code>function load_data(query)
 {
  $.ajax({
   url:"php_action/newfetchorder.php",
   method:"POST",
   data:{query:query},
   success:function(data)
   {

     $('#firstName').val(data);

   }

  });
 }
</code>```

html:

```<code><input  type="text" id="firstName" name="firstName"  />
</code>```

php:

```<code>if(isset($_POST["query"])) {
    $search = mysqli_real_escape_string($connect, $_POST["query"]);
    $query = "
    SELECT * FROM product
    WHERE Barcode LIKE '%".$search."%'
     ";

     $result1 = mysqli_query($connect, $query);
if(mysqli_num_rows($result1) > 0) {

  while($row = mysqli_fetch_array($result1)) {
     $output1 .= '<input type="text" name="item_name" value="'.$row["product_name"].'">';
     // $output2 .= '<input type="text" name="item_price" value="'.$row["Retail_price"].'">';
  }
  echo $output1;

}
else {
 echo 'Data Not Found';
}
}
</code>```

output:

expected output:

答:
write $output1 .=$row["product_name"] instead of $output1 .= '<input type="text" name="item_name" value="'.$row["product_name"].'">';

simple store value to $output1 variable and echo it no need to assign textbox here

Title: displaying ajax results in textbox

Body:
From my code, it displays the hall input type tag inside the textbox.

I want only the value to be displayed.

ajax function:

function load_data(query)
 {
  $.ajax({
   url:"php_action/newfetchorder.php",
   method:"POST",
   data:{query:query},
   success:function(data)
   {

     $('#firstName').val(data);

   }

  });
 }

html:

<input  type="text" id="firstName" name="firstName"  />

php:

if(isset($_POST["query"])) {
    $search = mysqli_real_escape_string($connect, $_POST["query"]);
    $query = "
    SELECT * FROM product
    WHERE Barcode LIKE '%".$search."%'
     ";

     $result1 = mysqli_query($connect, $query);
if(mysqli_num_rows($result1) > 0) {

  while($row = mysqli_fetch_array($result1)) {
     $output1 .= '<input type="text" name="item_name" value="'.$row["product_name"].'">';
     // $output2 .= '<input type="text" name="item_price" value="'.$row["Retail_price"].'">';
  }
  echo $output1;

}
else {
 echo 'Data Not Found';
}
}

output:

expected output:


问:
JAXB2 Mtom attachment broken by BOM
I'm using JAXB2 to to do OXM in a Spring-WS. The XSD I've specified requires a large XML file to be attached to the soap message so I'm using MTOM to transfer the file and have enabled MTOM on my JAXB2Marshaller.

When JAXB2 marshalls an MTOM attachment which has an expected mime type of text/xml it delivers that element as a javax.xml.transform.Source object. After some searching I was able to find out how I can send that Source object to a file.

```<code>final Source source = request.getSource();
StreamSource streamSource = (StreamSource) source;
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
File file = new File ("/tempxmlfile.xml");
try{
    transformer.transform(streamSource, new StreamResult(file));
    LOG.info("File saved in "+file.getAbsolutePath());
    }
catch(Exception ex){
        ex.getMessage();
    }
</code>```

The problem I am having is that when I send a UTF-8 encoded file as the attachment I get the following error:

```<code>[Fatal Error] :1:1: Content is not allowed in prolog.
ERROR:  'Content is not allowed in prolog.'
</code>```

This is being caused by a Byte Order Mark in front of the encoded text in the file, although this BOM is not required in a UTF-8 encoded file it is allowed by the Unicode standard, Java does not support BOMs in UTF-8 encoded streams.

I can solve this problem by sending a file without the BOM but this is not really feasible as it will cause problems with most Microsoft products which do insert the BOM.

There are lots of workarounds for Sun/Oracle's refusal to fix this issue with the Streams but they all require you to have access to the Stream, the Source Object provided by JAXB2 does not have an InputStream it only has a Reader object. Is there a way for me to solve this problem, either by wrapping the Sources Reader object with a reader which knows how to ignore a BOM in UTF-8 encoding or to change the way JAXB2 reads the attachment into the source so that it can ignore the BOM in UTF-8 encoding.

Thanks in advance,
Craig

答:
The trick is to "mark" the Reader.  If your reader does not support marking you can wrap it in a BufferedReader which does:

http://download.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#markSupported%28%29

OPTION #1 - Check for BOM and Remove It

I believe my original code was writing the BOM incorrectly.  The source code below makes more sense:

```<code>import java.io.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    private static char[] UTF32BE = {0x00, 0x00, 0xFE, 0xFF};
    private static char[] UTF32LE = {0xFF, 0xFE, 0x00, 0x00};
    private static char[] UTF16BE = {0xFE, 0xFF};
    private static char[] UTF16LE = {0xFF, 0xFE};
    private static char[] UTF8 = {0xEF, 0xBB, 0xBF};

    public static void main(String[] args) throws Exception {
        // Create an XML document with a BOM
        FileOutputStream fos = new FileOutputStream("bom.xml");
        writeBOM(fos, UTF16LE);

        OutputStreamWriter oswUTF8 = new OutputStreamWriter(fos, "UTF-8");
        oswUTF8.write("<root/>");
        oswUTF8.close();

        // Create a Source based on a Reader to simulate source.getRequest()
        StreamSource attachment = new StreamSource(new FileReader(new File("bom.xml")));

        // Wrap reader in BufferedReader so it will support marking
        Reader reader = new BufferedReader(attachment.getReader());

        // Remove the BOM
        removeBOM(reader);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new StreamSource(reader), new StreamResult(System.out));
    }

    private static void writeBOM(OutputStream os, char[] bom) throws Exception {
        for(int x=0; x<bom.length; x++) {
            os.write((byte) bom[x]);
        }
    }

    private static void removeBOM(Reader reader) throws Exception {
        if(removeBOM(reader, UTF32BE)) {
            return;
        }
        if(removeBOM(reader, UTF32LE)) {
            return;
        }
        if(removeBOM(reader, UTF16BE)) {
            return;
        }
        if(removeBOM(reader, UTF16LE)) {
            return;
        }
        if(removeBOM(reader, UTF8)) {
            return;
        }
    }

    private static boolean removeBOM(Reader reader, char[] bom) throws Exception {
        int bomLength = bom.length;
        reader.mark(bomLength);
        char[] possibleBOM = new char[bomLength];
        reader.read(possibleBOM);
        for(int x=0; x<bomLength; x++) {
            if(bom[x] != possibleBOM[x]) {
                reader.reset();
                return false;
            }
        }
        return true;
    }

}
</code>```

OPTION #2 - Find '<' and Advance Reader to that Point

Read until you hit the '<' leveraging mark/reset:

```<code>import java.io.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Demo2 {

    private static char[] UTF32BE = {0x00, 0x00, 0xFE, 0xFF};
    private static char[] UTF32LE = {0xFF, 0xFE, 0x00, 0x00};
    private static char[] UTF16BE = {0xFE, 0xFF};
    private static char[] UTF16LE = {0xFF, 0xFE};
    private static char[] UTF8 = {0xEF, 0xBB, 0xBF};

    public static void main(String[] args) throws Exception {
        // Create an XML document with a BOM
        FileOutputStream fos = new FileOutputStream("bom.xml");
        writeBOM(fos, UTF16BE);

        OutputStreamWriter oswUTF8 = new OutputStreamWriter(fos, "UTF-8");
        oswUTF8.write("<root/>");
        oswUTF8.close();

        // Create a Source based on a Reader to simulate source.getRequest()
        StreamSource attachment = new StreamSource(new FileReader(new File("bom.xml")));

        // Wrap reader in BufferedReader so it will support marking
        Reader reader = new BufferedReader(attachment.getReader());

        // Remove the BOM
        removeBOM(reader);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new StreamSource(reader), new StreamResult(System.out));
    }

    private static void writeBOM(OutputStream os, char[] bom) throws Exception {
        for(int x=0; x<bom.length; x++) {
            os.write((byte) bom[x]);
        }
    }

    private static Reader removeBOM(Reader reader) throws Exception {
        reader.mark(1);
        char[] potentialStart = new char[1];
        reader.read(potentialStart);
        if('<' == potentialStart[0]) {
            reader.reset();
            return reader;
        } else {
            return removeBOM(reader);
        }
    }

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: JAXB2 Mtom attachment broken by BOM

Body:
I'm using JAXB2 to to do OXM in a Spring-WS. The XSD I've specified requires a large XML file to be attached to the soap message so I'm using MTOM to transfer the file and have enabled MTOM on my JAXB2Marshaller.

When JAXB2 marshalls an MTOM attachment which has an expected mime type of text/xml it delivers that element as a javax.xml.transform.Source object. After some searching I was able to find out how I can send that Source object to a file.

final Source source = request.getSource();
StreamSource streamSource = (StreamSource) source;
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
File file = new File ("/tempxmlfile.xml");
try{
    transformer.transform(streamSource, new StreamResult(file));
    LOG.info("File saved in "+file.getAbsolutePath());
    }
catch(Exception ex){
        ex.getMessage();
    }

The problem I am having is that when I send a UTF-8 encoded file as the attachment I get the following error:

[Fatal Error] :1:1: Content is not allowed in prolog.
ERROR:  'Content is not allowed in prolog.'

This is being caused by a Byte Order Mark in front of the encoded text in the file, although this BOM is not required in a UTF-8 encoded file it is allowed by the Unicode standard, Java does not support BOMs in UTF-8 encoded streams.

I can solve this problem by sending a file without the BOM but this is not really feasible as it will cause problems with most Microsoft products which do insert the BOM.

There are lots of workarounds for Sun/Oracle's refusal to fix this issue with the Streams but they all require you to have access to the Stream, the Source Object provided by JAXB2 does not have an InputStream it only has a Reader object. Is there a way for me to solve this problem, either by wrapping the Sources Reader object with a reader which knows how to ignore a BOM in UTF-8 encoding or to change the way JAXB2 reads the attachment into the source so that it can ignore the BOM in UTF-8 encoding.

Thanks in advance,
Craig

Body:
The trick is to "mark" the Reader.  If your reader does not support marking you can wrap it in a BufferedReader which does:

http://download.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#markSupported%28%29

OPTION #1 - Check for BOM and Remove It

I believe my original code was writing the BOM incorrectly.  The source code below makes more sense:

import java.io.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    private static char[] UTF32BE = {0x00, 0x00, 0xFE, 0xFF};
    private static char[] UTF32LE = {0xFF, 0xFE, 0x00, 0x00};
    private static char[] UTF16BE = {0xFE, 0xFF};
    private static char[] UTF16LE = {0xFF, 0xFE};
    private static char[] UTF8 = {0xEF, 0xBB, 0xBF};

    public static void main(String[] args) throws Exception {
        // Create an XML document with a BOM
        FileOutputStream fos = new FileOutputStream("bom.xml");
        writeBOM(fos, UTF16LE);

        OutputStreamWriter oswUTF8 = new OutputStreamWriter(fos, "UTF-8");
        oswUTF8.write("<root/>");
        oswUTF8.close();

        // Create a Source based on a Reader to simulate source.getRequest()
        StreamSource attachment = new StreamSource(new FileReader(new File("bom.xml")));

        // Wrap reader in BufferedReader so it will support marking
        Reader reader = new BufferedReader(attachment.getReader());

        // Remove the BOM
        removeBOM(reader);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new StreamSource(reader), new StreamResult(System.out));
    }

    private static void writeBOM(OutputStream os, char[] bom) throws Exception {
        for(int x=0; x<bom.length; x++) {
            os.write((byte) bom[x]);
        }
    }

    private static void removeBOM(Reader reader) throws Exception {
        if(removeBOM(reader, UTF32BE)) {
            return;
        }
        if(removeBOM(reader, UTF32LE)) {
            return;
        }
        if(removeBOM(reader, UTF16BE)) {
            return;
        }
        if(removeBOM(reader, UTF16LE)) {
            return;
        }
        if(removeBOM(reader, UTF8)) {
            return;
        }
    }

    private static boolean removeBOM(Reader reader, char[] bom) throws Exception {
        int bomLength = bom.length;
        reader.mark(bomLength);
        char[] possibleBOM = new char[bomLength];
        reader.read(possibleBOM);
        for(int x=0; x<bomLength; x++) {
            if(bom[x] != possibleBOM[x]) {
                reader.reset();
                return false;
            }
        }
        return true;
    }

}

OPTION #2 - Find '<' and Advance Reader to that Point

Read until you hit the '<' leveraging mark/reset:

import java.io.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Demo2 {

    private static char[] UTF32BE = {0x00, 0x00, 0xFE, 0xFF};
    private static char[] UTF32LE = {0xFF, 0xFE, 0x00, 0x00};
    private static char[] UTF16BE = {0xFE, 0xFF};
    private static char[] UTF16LE = {0xFF, 0xFE};
    private static char[] UTF8 = {0xEF, 0xBB, 0xBF};

    public static void main(String[] args) throws Exception {
        // Create an XML document with a BOM
        FileOutputStream fos = new FileOutputStream("bom.xml");
        writeBOM(fos, UTF16BE);

        OutputStreamWriter oswUTF8 = new OutputStreamWriter(fos, "UTF-8");
        oswUTF8.write("<root/>");
        oswUTF8.close();

        // Create a Source based on a Reader to simulate source.getRequest()
        StreamSource attachment = new StreamSource(new FileReader(new File("bom.xml")));

        // Wrap reader in BufferedReader so it will support marking
        Reader reader = new BufferedReader(attachment.getReader());

        // Remove the BOM
        removeBOM(reader);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new StreamSource(reader), new StreamResult(System.out));
    }

    private static void writeBOM(OutputStream os, char[] bom) throws Exception {
        for(int x=0; x<bom.length; x++) {
            os.write((byte) bom[x]);
        }
    }

    private static Reader removeBOM(Reader reader) throws Exception {
        reader.mark(1);
        char[] potentialStart = new char[1];
        reader.read(potentialStart);
        if('<' == potentialStart[0]) {
            reader.reset();
            return reader;
        } else {
            return removeBOM(reader);
        }
    }

}


问:
How to add new user to Spring Security at runtime
I save users in a DB table via Hibernate and I am using Spring Security to authenticate:

```<code>import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}
</code>```

And this works perfectly, but there is a point - user is loaded during server start. I need to write method RegisterUser(User user) that add new user to Spring Security in runtime. This method should focus only on this task. I dont know how to start to implement this feature so thanks for any advices! ;)

Ofc User have fields like login, password, role string etc etc...

Please do not post solutions with Spring MVC. This system is RESTful app using Spring Web Boost and Spring Security Boost in version 4.0.x

答:
use this code to add authority to current user:</p>

```<code>List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_NEWUSERROLE');
    SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(
            SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
            SecurityContextHolder.getContext().getAuthentication().getCredentials(),
            authorities)
        );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I save users in a DB table via Hibernate and I am using Spring Security to authenticate:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

And this works perfectly, but there is a point - user is loaded during server start. I need to write method RegisterUser(User user) that add new user to Spring Security in runtime. This method should focus only on this task. I dont know how to start to implement this feature so thanks for any advices! ;)

Ofc User have fields like login, password, role string etc etc...

Please do not post solutions with Spring MVC. This system is RESTful app using Spring Web Boost and Spring Security Boost in version 4.0.x

Body:
use this code to add authority to current user:

List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_NEWUSERROLE');
    SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(
            SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
            SecurityContextHolder.getContext().getAuthentication().getCredentials(),
            authorities)
        );


问:
svn: getting rid of the P flag from a checkout
If I run svnversion on the working copy of one of my projects, I get a P suffix (partial working copy, from a sparse checkout, according to svnversion --help). I've tried to get rid of the P suffix but can't seem to do it, despite doing svn update or svn cleanup.

Besides blowing away the whole working copy, how can I? I'd like to have a clean checkout.

答:
Try this:

```<code>svn update --set-depth=infinity path/to/folder/with/P/suffix
</code>```

The important part is the --set-depth=infinity

Body:
Try this:

svn update --set-depth=infinity path/to/folder/with/P/suffix

The important part is the --set-depth=infinity


问:
mobile number validation using regex javascript
I want mobile number in format
+91(or any other country code)-9999999999(10 digit mobile number).

I have tried /^\+[0-9]{2,3}+[0-9]\d{10}, but its not working please help

Thanks in advance

答:
You can simply write the following:</p>

```<code>var pattern=/^(0|[+91]{3})?[7-9][0-9]{9}$/;
</code>```

Body:
You can simply write the following:

var pattern=/^(0|[+91]{3})?[7-9][0-9]{9}$/;


问:
Table layout in HTML
I'm trying to make a table in HTML and i need help.
Here's a rough drawing:

Drawing

Can it be done?

答:
td {border:1px solid black}
table {border:1px solid black}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table ><tr><td>foo</td><td rowspan=2>picture</td></tr><tr><td>bar</td></tr></table></code>```

Title: Table layout in HTML

Body:
td {border:1px solid black}
table {border:1px solid black}

<table ><tr><td>foo</td><td rowspan=2>picture</td></tr><tr><td>bar</td></tr></table>


问:
How to make link, phone number clickable (Same behaviour as in textview) in a custom view where i draw text?
I made a view and draw text on it and i want that if any text contains link(Hyperlink) or Phone Number It would be clickable (Same Behaviour As in Text View) So how to Achieve it   ?

Code For View In which i am Drawing Text :-

```<code>class DrawRectCellView: UIView {

    var text: NSAttributedString?

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Only override drawRect: if you perform custom drawing.

    override func draw(_ rect: CGRect)
    {
        UIColor.white.setFill()
        UIGraphicsGetCurrentContext()?.fill(rect)

        // Drawing code

        if let attributedText = text {
            attributedText.draw(in: rect)
        }
    }

}
</code>```

Code For TableCell :-

```<code>class DrawRectCell: UITableViewCell {

    var cellView: DrawRectCellView?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // Initialization code
        cellView = DrawRectCellView(frame: self.frame)

        if let cell = cellView {
            cell.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
            cell.contentMode = UIViewContentMode.redraw
        }

        self.contentView.addSubview(cellView!)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setTextString(_ text: NSAttributedString) {
        if let view = cellView {
            view.text = text
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
</code>```

i am Setting Text like = www.google.com or any phone number its showing as normal text only (Not Showing Like In textview (it makes it clickable))

答: You can add UITapGestureRecognizer on DrawRectCellView and set the IndexPath as tag. In the selector method of UITapGestureRecognizer you can get the subviews info of the tapped contentView containing text.</p>

Body:
I made a view and draw text on it and i want that if any text contains link(Hyperlink) or Phone Number It would be clickable (Same Behaviour As in Text View) So how to Achieve it   ?

Code For View In which i am Drawing Text :-

class DrawRectCellView: UIView {

    var text: NSAttributedString?

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Only override drawRect: if you perform custom drawing.

    override func draw(_ rect: CGRect)
    {
        UIColor.white.setFill()
        UIGraphicsGetCurrentContext()?.fill(rect)

        // Drawing code

        if let attributedText = text {
            attributedText.draw(in: rect)
        }
    }

}

Code For TableCell :-

class DrawRectCell: UITableViewCell {

    var cellView: DrawRectCellView?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // Initialization code
        cellView = DrawRectCellView(frame: self.frame)

        if let cell = cellView {
            cell.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
            cell.contentMode = UIViewContentMode.redraw
        }

        self.contentView.addSubview(cellView!)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setTextString(_ text: NSAttributedString) {
        if let view = cellView {
            view.text = text
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

i am Setting Text like = www.google.com or any phone number its showing as normal text only (Not Showing Like In textview (it makes it clickable))


问:
My bubble sorting algorithm in Java never stops sorting and doesnt return anything
I'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running</p>

```<code>package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;

public class bubbleSort {

    public static void main(String[] args) {

        int length = getLength();

        List<Integer> randomList = createList(length);

        System.out.println("The list before sorting:\n" + randomList);

        List<Integer> newList = sortList(randomList, length);

        System.out.println("The list after sorting:\n" + newList);

    }

    public static int getLength() {
        System.out.println("Please enter how long you want the array to be");

        Scanner reader = new Scanner(System.in);

        int length = Integer.parseInt(reader.nextLine());

        return length;
    }

    public static List<Integer> createList(int length) {
        Random rand = new Random();

        List<Integer> randomList = new ArrayList<Integer>();

        for(int x = 0 ; x < length ; x++){
            int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
            randomList.add(randomnumber);
        }

        return randomList;
    }

    public static List<Integer> sortList(List<Integer> randomList, int length){
        boolean sorted = false;

        while(sorted == false){
            sorted = true;

            for(int x = 0 ; x < (length - 1) ; x++) {
                if(randomList.get(x) > randomList.get(x + 1)) {
                    sorted = false;
                    int temp = randomList.get(x + 1);
                    randomList.set((x + 1), (x));
                    randomList.set((x + 1), temp);
                }
            }
        }

        return randomList;
    }

}
</code>```

答:
Create a swap method to make it clearer (both for us and yourself):

```<code>private void swap(List<Integer> values, x, y) {
    int temp = values.get(x);
    values.set(x, values.get(y));
    values.set(y, temp);
}
</code>```

Other suggestions:

name your class BubbleSort rather than bubbleSort. Convention for class names is to start with uppercase.

don't pass the length as a second argument to your sort method. It's redundant and might become incorrect if someone sneakily adds an item to the list.

rename randomList to values or numbers or randomNumbers. No need to repeat the type in the variable name.

replace sorted == false with !sorted. This is the common and more readable notation

getLength and createList can be private

Consider using the main method to create an instance of your sorting class, with the list as a field. In that way the methods won't have to pass the list along to each other. Your code will be more readable and more object-oriented.

EDIT: you could take the separation even further and move all the static methods into a separate class called 'Application' or 'Main'. See edited code below:

Here's roughly how the code would look following my suggestions:

```<code>public class BubbleSort {

    // a field
    private List<Integer> numbers;

    public BubbleSort(List<Integer> numbers) {
        this.numbers = numbers;
    }

    public static List<Integer> sort() {
        boolean sorted = false;
        while(!sorted) {
            sorted = true;
            for(int x = 0; x < length - 1; x++) {
                if(numbers.get(x) > numbers.get(x + 1)) {
                    sorted = false;
                    swap(x, x + 1);
                }
            }
        }
        return numbers;
    }

    private void swap(x, y) {
        int temp = numbers.get(x);
        numbers.set(x, numbers.get(y));
        numbers.set(y, temp);
    }

}
</code>```

The Application class. It's purpose is to get the length from the user, create test data and set up and call a BubbleSort instance:

```<code>public class Application {

    public static void main(String[] args) {

        int length = getLength();
        List<Integer> unsorted = createList(length);
        System.out.println("The list before sorting:\n" + unsorted);

        // creating an instance of the BubbleSort class
        BubbleSort bubbleSort = new BubbleSort(unsorted );
        List<Integer> sorted = bubbleSort.sort();

        System.out.println("The list after sorting:\n" + sorted);
    }

    private static int getLength() {
        System.out.println("Please enter how long you want the array to be");
        Scanner reader = new Scanner(System.in);
        return Integer.parseInt(reader.nextLine());
    }

    private static List<Integer> createList(int length) {
        Random rand = new Random();
        List<Integer> numbers = new ArrayList<Integer>();
        for(int x = 0 ; x < length ; x++){
            int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
            numbers.add(randomnumber);
        }
        return numbers;
    }
</code>```

BTW Good job splitting off those methods getLength and createList. That's the right idea.

Body:
I'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running

package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;

public class bubbleSort {

    public static void main(String[] args) {

        int length = getLength();

        List<Integer> randomList = createList(length);

        System.out.println("The list before sorting:\n" + randomList);

        List<Integer> newList = sortList(randomList, length);

        System.out.println("The list after sorting:\n" + newList);

    }

    public static int getLength() {
        System.out.println("Please enter how long you want the array to be");

        Scanner reader = new Scanner(System.in);

        int length = Integer.parseInt(reader.nextLine());

        return length;
    }

    public static List<Integer> createList(int length) {
        Random rand = new Random();

        List<Integer> randomList = new ArrayList<Integer>();

        for(int x = 0 ; x < length ; x++){
            int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
            randomList.add(randomnumber);
        }

        return randomList;
    }

    public static List<Integer> sortList(List<Integer> randomList, int length){
        boolean sorted = false;

        while(sorted == false){
            sorted = true;

            for(int x = 0 ; x < (length - 1) ; x++) {
                if(randomList.get(x) > randomList.get(x + 1)) {
                    sorted = false;
                    int temp = randomList.get(x + 1);
                    randomList.set((x + 1), (x));
                    randomList.set((x + 1), temp);
                }
            }
        }

        return randomList;
    }

}

Body:
Create a swap method to make it clearer (both for us and yourself):

private void swap(List<Integer> values, x, y) {
    int temp = values.get(x);
    values.set(x, values.get(y));
    values.set(y, temp);
}

Other suggestions:

name your class BubbleSort rather than bubbleSort. Convention for class names is to start with uppercase.

don't pass the length as a second argument to your sort method. It's redundant and might become incorrect if someone sneakily adds an item to the list.

rename randomList to values or numbers or randomNumbers. No need to repeat the type in the variable name.

replace sorted == false with !sorted. This is the common and more readable notation

getLength and createList can be private

Consider using the main method to create an instance of your sorting class, with the list as a field. In that way the methods won't have to pass the list along to each other. Your code will be more readable and more object-oriented.

EDIT: you could take the separation even further and move all the static methods into a separate class called 'Application' or 'Main'. See edited code below:

Here's roughly how the code would look following my suggestions:

public class BubbleSort {

    // a field
    private List<Integer> numbers;

    public BubbleSort(List<Integer> numbers) {
        this.numbers = numbers;
    }

    public static List<Integer> sort() {
        boolean sorted = false;
        while(!sorted) {
            sorted = true;
            for(int x = 0; x < length - 1; x++) {
                if(numbers.get(x) > numbers.get(x + 1)) {
                    sorted = false;
                    swap(x, x + 1);
                }
            }
        }
        return numbers;
    }

    private void swap(x, y) {
        int temp = numbers.get(x);
        numbers.set(x, numbers.get(y));
        numbers.set(y, temp);
    }

}

The Application class. It's purpose is to get the length from the user, create test data and set up and call a BubbleSort instance:

public class Application {

    public static void main(String[] args) {

        int length = getLength();
        List<Integer> unsorted = createList(length);
        System.out.println("The list before sorting:\n" + unsorted);

        // creating an instance of the BubbleSort class
        BubbleSort bubbleSort = new BubbleSort(unsorted );
        List<Integer> sorted = bubbleSort.sort();

        System.out.println("The list after sorting:\n" + sorted);
    }

    private static int getLength() {
        System.out.println("Please enter how long you want the array to be");
        Scanner reader = new Scanner(System.in);
        return Integer.parseInt(reader.nextLine());
    }

    private static List<Integer> createList(int length) {
        Random rand = new Random();
        List<Integer> numbers = new ArrayList<Integer>();
        for(int x = 0 ; x < length ; x++){
            int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
            numbers.add(randomnumber);
        }
        return numbers;
    }

BTW Good job splitting off those methods getLength and createList. That's the right idea.


问:
how to format time with jquery/javascript
I have a JSON feed that drupal spits out time in this format:   2010-12-16T04:41:35Z

How do I go about formating it to X minutes/hours ago?

答: Here is a highly relevant Stack Overflow post:  How can I convert string to datetime with format specification in JavaScript?</p>


问:
Create new thread if last thread is finished [Python 2.7]
I am new to Python threads. Basically, I have a QT based application designed in Python. The application has a button "Follow Trajectory", whenever I press this button, the robot starts moving. I noticed that robot is not following the exact trajectory.

The move command is being overwritten and robot receives only a few points. Below is the function, which gets executed when the button is pressed:

```<code>def move_robot(self):
    # points is an array of point
    for point in points:
        start_new_thread(self.robot.move, (point,))
</code>```

Below is the move function from the controller:

```<code>def move(self, point):
    while True:
        self._robot_controller.move(point)
        current_location = self._robot_controller.location()
        if current_location - point < 0.0001:
            break
</code>```

My question is that how to create a new thread only if last thread is finished?

Below is the complete code:

```<code>class RobotControllerWrapper():
    def __init__(self):
        self._robot_controller = RobotController()

    def move(self, point):
        while True:
            self._robot_controller.move(point)
            current_location = self._robot_controller.location()
            if current_location - point < 0.0001:
                break

from thread import start_new_thread
from qt_gui.plugin import Plugin
from python_qt_binding.QtGui import QWidget, QPushButton

class MyPlugin(Plugin):
    def __init__(self, context):

        super(MyPlugin, self).__init__(context)
        self.setObjectName('MyPlugin')

        self._widget = QWidget()
        self._vertical_layout = QVBoxLayout()
        self._move_robot_button = QPushButton('Follow Trajectory')
        self._move_robot_button.clicked.connect(self.move_robot)
        self._vertical_layout.addWidget(self._move_robot_button)
        self._widget.setLayout(self._vertical_layout)
        self._widget.setObjectName('MyPluginUi')

        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number()))
        context.add_widget(self._widget)

        self.robot = RobotControllerWrapper()

    def move_robot(self):
        # points is an array of point
        for point in points:
            start_new_thread(self.robot.move, (point,))
</code>```

Apologize for the long post. Thank you very much.

答:
Based on your comment, you need to create a new thread for move_robot:

```<code>def move_robot(self):
    # points is an array of point
    def move_robot_thread(points):
        for point in points:
            thread = start_new_thread(self.robot.move, (point,))
            thread.join()
    start_new_thread(move_robot_thread, (points,))
</code>```

BTW, I assume start_new_thread returns Thread object.

update

```<code>def move_robot(self):
    from threading import Thread, start_new_thread
    # points is an array of point
    def move_robot_thread(points):
        for point in points:
            thread = Thread(target=self.robot.move, args=(point,))
            thread.start()
            thread.join()
    start_new_thread(move_robot_thread, (points,))
</code>```

This is for you. I haven't tested, but it should work.

Body:
I am new to Python threads. Basically, I have a QT based application designed in Python. The application has a button "Follow Trajectory", whenever I press this button, the robot starts moving. I noticed that robot is not following the exact trajectory.

The move command is being overwritten and robot receives only a few points. Below is the function, which gets executed when the button is pressed:

def move_robot(self):
    # points is an array of point
    for point in points:
        start_new_thread(self.robot.move, (point,))

Below is the move function from the controller:

def move(self, point):
    while True:
        self._robot_controller.move(point)
        current_location = self._robot_controller.location()
        if current_location - point < 0.0001:
            break

My question is that how to create a new thread only if last thread is finished?

Below is the complete code:

class RobotControllerWrapper():
    def __init__(self):
        self._robot_controller = RobotController()

    def move(self, point):
        while True:
            self._robot_controller.move(point)
            current_location = self._robot_controller.location()
            if current_location - point < 0.0001:
                break

from thread import start_new_thread
from qt_gui.plugin import Plugin
from python_qt_binding.QtGui import QWidget, QPushButton

class MyPlugin(Plugin):
    def __init__(self, context):

        super(MyPlugin, self).__init__(context)
        self.setObjectName('MyPlugin')

        self._widget = QWidget()
        self._vertical_layout = QVBoxLayout()
        self._move_robot_button = QPushButton('Follow Trajectory')
        self._move_robot_button.clicked.connect(self.move_robot)
        self._vertical_layout.addWidget(self._move_robot_button)
        self._widget.setLayout(self._vertical_layout)
        self._widget.setObjectName('MyPluginUi')

        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number()))
        context.add_widget(self._widget)

        self.robot = RobotControllerWrapper()

    def move_robot(self):
        # points is an array of point
        for point in points:
            start_new_thread(self.robot.move, (point,))

Apologize for the long post. Thank you very much.

Body:
Based on your comment, you need to create a new thread for move_robot:

def move_robot(self):
    # points is an array of point
    def move_robot_thread(points):
        for point in points:
            thread = start_new_thread(self.robot.move, (point,))
            thread.join()
    start_new_thread(move_robot_thread, (points,))

BTW, I assume start_new_thread returns Thread object.

update

def move_robot(self):
    from threading import Thread, start_new_thread
    # points is an array of point
    def move_robot_thread(points):
        for point in points:
            thread = Thread(target=self.robot.move, args=(point,))
            thread.start()
            thread.join()
    start_new_thread(move_robot_thread, (points,))

This is for you. I haven't tested, but it should work.


问:
Prolog recursively count numbers in a list
I need a program to count all the numbers in a list, no matter how DEEPLY NESTED they are. I was able to count numbers in the case where they were not inside another list, but recursing through deeply nested elements is not working out. I have this so far:

```<code>count([],0).
count([H|Tail], N) :-
    count(Tail, N1),
    (  number(H)
    ->N is N1 + 1
    ;   is_list(H)
    -> count(H,N)
    ;   N = N1
    ).
</code>```

So, if I were to call count([a,1,[2,b],3],N), the output should be N=3; however, I only get N=2. Could someone please help me add to my second case test? All available solutions here do not work for deeply nested numerical elements.

Thank you!

答:
Your code is incorrect for the is_list(H) branch: in that case you ignore the value of N1, which is not correct, you want N to be the sum of N1 with the count on H.

Complete code:

```<code>:- use_module(library(clpfd)).

count([], 0).
count([H|T], N) :-
    count(T, N1),
    (   number(H) ->
        N #= N1 + 1
    ;   is_list(H) ->
        N #= N1 + N2,
        count(H, N2)
    ;   N1 = N
    ).
</code>```

Body:
I need a program to count all the numbers in a list, no matter how DEEPLY NESTED they are. I was able to count numbers in the case where they were not inside another list, but recursing through deeply nested elements is not working out. I have this so far:

count([],0).
count([H|Tail], N) :-
    count(Tail, N1),
    (  number(H)
    ->N is N1 + 1
    ;   is_list(H)
    -> count(H,N)
    ;   N = N1
    ).

So, if I were to call count([a,1,[2,b],3],N), the output should be N=3; however, I only get N=2. Could someone please help me add to my second case test? All available solutions here do not work for deeply nested numerical elements.

Thank you!

Body:
Your code is incorrect for the is_list(H) branch: in that case you ignore the value of N1, which is not correct, you want N to be the sum of N1 with the count on H.

Complete code:

:- use_module(library(clpfd)).

count([], 0).
count([H|T], N) :-
    count(T, N1),
    (   number(H) ->
        N #= N1 + 1
    ;   is_list(H) ->
        N #= N1 + N2,
        count(H, N2)
    ;   N1 = N
    ).


问:
Constant live update
Does anybody know of a way to have my application constantly check firstly if there is internet connectivity..and secondly if there is internet connection to call a function...It needs to check for internet coverage say every 10 minutes etc?</p>

答:
Use ConnectivityManager to check for network connectivity.

```<code>ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

if (networkInfo.isConnected())
{
    // do something
}
</code>```

To wake the device every 10 minutes, use the API provided by AlarmManager. I don't have practical experience using the AlarmManager; please refer to this tutorial, which seems fairly comprehensive

Do keep in mind that waking the device this often will have a noticeable effect on battery life.

Title: Constant live update

Body:
Use ConnectivityManager to check for network connectivity.

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

if (networkInfo.isConnected())
{
    // do something
}

To wake the device every 10 minutes, use the API provided by AlarmManager. I don't have practical experience using the AlarmManager; please refer to this tutorial, which seems fairly comprehensive

Do keep in mind that waking the device this often will have a noticeable effect on battery life.


问:
how to perform some action on clear all notification
I want to stop media player on clearing of notifications and also how to open some activity when i click on notification

this is my alarm function

```<code>    public void alarmstart(String idd,int alarmmonth,int alarmyear,int alarmday,int alarmhour,int alarmmin)
        {
            AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

 Intent myIntent;
        PendingIntent pendingIntent;

        myIntent = new Intent(Create.this,AlarmNotificationReceiver.class);
        myIntent.putExtra("title",tii);
        myIntent.putExtra("note",noo);
        myIntent.putExtra("id",id);
        pendingIntent =
        PendingIntent.getBroadcast(this,Integer.valueOf(idd),myIntent,0);

        Calendar cal1=Calendar.getInstance();
        cal1.set(Calendar.MONTH,alarmmonth-1);
        cal1.set(Calendar.YEAR,alarmyear);
        cal1.set(Calendar.DAY_OF_MONTH,alarmday);

        cal1.set(Calendar.HOUR_OF_DAY,alarmhour);
        cal1.set(Calendar.MINUTE,alarmmin);
        cal1.set(Calendar.SECOND,0);

        manager.set(AlarmManager.RTC_WAKEUP,cal1.getTimeInMillis() ,pendingIntent);

    }
</code>```

this is my notification class broadcast receiver

```<code>public class AlarmNotificationReceiver extends BroadcastReceiver {

    static MediaPlayer mMediaPlayer;
    PendingIntent pintent;
    static String id;

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        String ti,no;
        ti=intent.getExtras().getString("title");
        no=intent.getExtras().getString("note");
        id=intent.getExtras().getString("id");

        Intent stopSoundIntent = new Intent(context,
                NotificationActionService.class)
                .setAction("Stop");

        PendingIntent stopSoundPendingIntent = PendingIntent.getService(context, 0,
                stopSoundIntent, PendingIntent.FLAG_ONE_SHOT);

       // builder.setAutoCancel(true)
                builder.setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(ti)
                .setContentText(no)

                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .addAction(new NotificationCompat.Action(R.mipmap.stop,
                        "Stop", stopSoundPendingIntent))

                .setContentInfo("Info");
         mMediaPlayer = MediaPlayer.create(context, R.raw.teri);
         mMediaPlayer.start();

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Integer.valueOf(id),builder.build());

    }

    public static class NotificationActionService extends IntentService {
        public NotificationActionService() {
            super(NotificationActionService.class.getSimpleName());
        }

        @Override
        protected void onHandleIntent(Intent intent) {
            String action = intent.getAction();

            if ("Stop".equals(action)) {
                // TODO: handle action StopSound.
                mMediaPlayer.stop();
                // If you want to cancel the notification:
                NotificationManagerCompat.from(this).cancel(Integer.valueOf(id));
                // NOTIFICATION_ID : you can (set and get) notificationid (to/from) intent
            }

        }

    }
}
</code>```

please can anyone help me on this I am newbie on this almost read the all previous posts related to this topic but not able to do this
I am not able to use deleteintent correctly and also how to open activity upon clicking on notification

答:
To open activity on clicking on notification,

```<code>NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);

Intent notificationIntent = new Intent(context, HomeActivity.class);

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent intent = PendingIntent.getActivity(context, 0,
        notificationIntent, 0);

notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
</code>```

To clear notification onClick,

```<code>notification.flags |= Notification.FLAG_AUTO_CANCEL;
</code>```

After opening of MainActivity you can perform your stuff.

Body:
I want to stop media player on clearing of notifications and also how to open some activity when i click on notification

this is my alarm function

    public void alarmstart(String idd,int alarmmonth,int alarmyear,int alarmday,int alarmhour,int alarmmin)
        {
            AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

 Intent myIntent;
        PendingIntent pendingIntent;

        myIntent = new Intent(Create.this,AlarmNotificationReceiver.class);
        myIntent.putExtra("title",tii);
        myIntent.putExtra("note",noo);
        myIntent.putExtra("id",id);
        pendingIntent =
        PendingIntent.getBroadcast(this,Integer.valueOf(idd),myIntent,0);

        Calendar cal1=Calendar.getInstance();
        cal1.set(Calendar.MONTH,alarmmonth-1);
        cal1.set(Calendar.YEAR,alarmyear);
        cal1.set(Calendar.DAY_OF_MONTH,alarmday);

        cal1.set(Calendar.HOUR_OF_DAY,alarmhour);
        cal1.set(Calendar.MINUTE,alarmmin);
        cal1.set(Calendar.SECOND,0);

        manager.set(AlarmManager.RTC_WAKEUP,cal1.getTimeInMillis() ,pendingIntent);

    }

this is my notification class broadcast receiver

public class AlarmNotificationReceiver extends BroadcastReceiver {

    static MediaPlayer mMediaPlayer;
    PendingIntent pintent;
    static String id;

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        String ti,no;
        ti=intent.getExtras().getString("title");
        no=intent.getExtras().getString("note");
        id=intent.getExtras().getString("id");

        Intent stopSoundIntent = new Intent(context,
                NotificationActionService.class)
                .setAction("Stop");

        PendingIntent stopSoundPendingIntent = PendingIntent.getService(context, 0,
                stopSoundIntent, PendingIntent.FLAG_ONE_SHOT);

       // builder.setAutoCancel(true)
                builder.setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(ti)
                .setContentText(no)

                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .addAction(new NotificationCompat.Action(R.mipmap.stop,
                        "Stop", stopSoundPendingIntent))

                .setContentInfo("Info");
         mMediaPlayer = MediaPlayer.create(context, R.raw.teri);
         mMediaPlayer.start();

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Integer.valueOf(id),builder.build());

    }

    public static class NotificationActionService extends IntentService {
        public NotificationActionService() {
            super(NotificationActionService.class.getSimpleName());
        }

        @Override
        protected void onHandleIntent(Intent intent) {
            String action = intent.getAction();

            if ("Stop".equals(action)) {
                // TODO: handle action StopSound.
                mMediaPlayer.stop();
                // If you want to cancel the notification:
                NotificationManagerCompat.from(this).cancel(Integer.valueOf(id));
                // NOTIFICATION_ID : you can (set and get) notificationid (to/from) intent
            }

        }

    }
}

please can anyone help me on this I am newbie on this almost read the all previous posts related to this topic but not able to do this
I am not able to use deleteintent correctly and also how to open activity upon clicking on notification

Body:
To open activity on clicking on notification,

NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);

Intent notificationIntent = new Intent(context, HomeActivity.class);

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent intent = PendingIntent.getActivity(context, 0,
        notificationIntent, 0);

notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

To clear notification onClick,

notification.flags |= Notification.FLAG_AUTO_CANCEL;

After opening of MainActivity you can perform your stuff.


问:
ignore hidden rows of table on jquery search
i have a table with two columns and each column have a range search

https://jsfiddle.net/8srq89ps/

i want the search to ignore the hidden rows , for example if i search a range on first column , search on the second column ignore the hidden rows from first search.

i managed to do this by tr:not(:hidden)

https://jsfiddle.net/8srq89ps/

the problem is when i empty the search box , hidden rows stay hidden

i don't know what i'm doing wrong

EDIT :

Heres The Code :

```<code>$('#FATMin, #FATMax').keyup(function () {
    var min = parseInt($('#FATMin').val(), 10);
    var max = parseInt($('#FATMax').val(), 10);
    $('#mytable tbody tr:not(:hidden)').each(function () {
        var fat = parseFloat($('td:eq(1)', this).text()) || 0;
        if ((isNaN(min) && isNaN(max)) ||
            (isNaN(min) && fat <= max) ||
            (min <= fat && isNaN(max)) ||
            (min <= fat && fat <= max)) {
            $(this).show();

        } else {
            $(this).hide();
        }
    });
});
</code>```

答:
You should show the filtered rows in a single event handler, which filters row based on different criteria

$('#ICCMin, #ICCMax, #FATMin, #FATMax').keyup(function() {
  var min = parseInt($('#ICCMin').val(), 10),
    max = parseInt($('#ICCMax').val(), 10);

  //Cache rows in a variable
  var rows = $('#mytable tbody tr');

  //Get filtered rows based on first column
  var filtered = rows.filter(function() {
    var icc = parseFloat($('td:eq(0)', this).text()) || 0;
    return ((isNaN(min) && isNaN(max)) ||
      (isNaN(min) && icc <= max) ||
      (min <= icc && isNaN(max)) ||
      (min <= icc && icc <= max));
  });

  min = parseInt($('#FATMin').val(), 10);
  max = parseInt($('#FATMax').val(), 10);

  //Get filtered rows based on second column
  filtered = filtered.filter(function() {
    var fat = parseFloat($('td:eq(1)', this).text()) || 0;
    return (isNaN(min) && isNaN(max)) ||
      (isNaN(min) && fat <= max) ||
      (min <= fat && isNaN(max)) ||
      (min <= fat && fat <= max)
  });

  //Hide all rows
  rows.not(filtered).hide();

  //Show filtered row
  filtered.show()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ICCMin" placeholder="ICCMin">
<input type="text" id="ICCMax" placeholder="ICCMax">
<br/>
<input type="text" id="FATMin" placeholder="FATMin">
<input type="text" id="FATMax" placeholder="FATMax">
<table id="mytable">
  <thead>
    <tr>
      <th>ICC</th>
      <th>FAT</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>106</td>
      <td>16</td>
    </tr>
    <tr>
      <td>112</td>
      <td>18</td>
    </tr>
    <tr>
      <td>120</td>
      <td>22</td>
    </tr>
    <tr>
      <td>128</td>
      <td>26</td>
    </tr>
    <tr>
      <td>136</td>
      <td>32</td>
    </tr>
    <tr>
      <td>138</td>
      <td>36</td>
    </tr>
    <tr>
      <td>145</td>
      <td>39</td>
    </tr>
    <tr>
      <td>156</td>
      <td>45</td>
    </tr>
    <tr>
      <td>168</td>
      <td>53</td>
    </tr>
  </tbody>
</table></code>```

Body:
i have a table with two columns and each column have a range search

https://jsfiddle.net/8srq89ps/

i want the search to ignore the hidden rows , for example if i search a range on first column , search on the second column ignore the hidden rows from first search.

i managed to do this by tr:not(:hidden)

https://jsfiddle.net/8srq89ps/

the problem is when i empty the search box , hidden rows stay hidden

i don't know what i'm doing wrong

EDIT :

Heres The Code :

$('#FATMin, #FATMax').keyup(function () {
    var min = parseInt($('#FATMin').val(), 10);
    var max = parseInt($('#FATMax').val(), 10);
    $('#mytable tbody tr:not(:hidden)').each(function () {
        var fat = parseFloat($('td:eq(1)', this).text()) || 0;
        if ((isNaN(min) && isNaN(max)) ||
            (isNaN(min) && fat <= max) ||
            (min <= fat && isNaN(max)) ||
            (min <= fat && fat <= max)) {
            $(this).show();

        } else {
            $(this).hide();
        }
    });
});

Body:
You should show the filtered rows in a single event handler, which filters row based on different criteria

$('#ICCMin, #ICCMax, #FATMin, #FATMax').keyup(function() {
  var min = parseInt($('#ICCMin').val(), 10),
    max = parseInt($('#ICCMax').val(), 10);

  //Cache rows in a variable
  var rows = $('#mytable tbody tr');

  //Get filtered rows based on first column
  var filtered = rows.filter(function() {
    var icc = parseFloat($('td:eq(0)', this).text()) || 0;
    return ((isNaN(min) && isNaN(max)) ||
      (isNaN(min) && icc <= max) ||
      (min <= icc && isNaN(max)) ||
      (min <= icc && icc <= max));
  });

  min = parseInt($('#FATMin').val(), 10);
  max = parseInt($('#FATMax').val(), 10);

  //Get filtered rows based on second column
  filtered = filtered.filter(function() {
    var fat = parseFloat($('td:eq(1)', this).text()) || 0;
    return (isNaN(min) && isNaN(max)) ||
      (isNaN(min) && fat <= max) ||
      (min <= fat && isNaN(max)) ||
      (min <= fat && fat <= max)
  });

  //Hide all rows
  rows.not(filtered).hide();

  //Show filtered row
  filtered.show()
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ICCMin" placeholder="ICCMin">
<input type="text" id="ICCMax" placeholder="ICCMax">
<br/>
<input type="text" id="FATMin" placeholder="FATMin">
<input type="text" id="FATMax" placeholder="FATMax">
<table id="mytable">
  <thead>
    <tr>
      <th>ICC</th>
      <th>FAT</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>106</td>
      <td>16</td>
    </tr>
    <tr>
      <td>112</td>
      <td>18</td>
    </tr>
    <tr>
      <td>120</td>
      <td>22</td>
    </tr>
    <tr>
      <td>128</td>
      <td>26</td>
    </tr>
    <tr>
      <td>136</td>
      <td>32</td>
    </tr>
    <tr>
      <td>138</td>
      <td>36</td>
    </tr>
    <tr>
      <td>145</td>
      <td>39</td>
    </tr>
    <tr>
      <td>156</td>
      <td>45</td>
    </tr>
    <tr>
      <td>168</td>
      <td>53</td>
    </tr>
  </tbody>
</table>


问:
How to share my localhost on the same network?
I am working on a Java Web project and I am using wildfly 10.1.Final as server. In order test with other computers which are on the same network, I would like to share my localhost. Can anybody help me in this matter?
Thanks...</p>

答:
Run wildfly with command standalone.bat -b 0.0.0.0 (I suppose, you are using Windows). If linux, then ./standalone.sh -b 0.0.0.0

Then disable firewall and your LAN may connect to your IP (port is 8080, not 80)

Actually, you also can share localhost on Linux through ssh tunnel, like

```<code>ssh -L 127.0.0.1:8080:127.0.0.1:8080 root@server -N
</code>```

but I doubt that you need it.

Body:
Run wildfly with command standalone.bat -b 0.0.0.0 (I suppose, you are using Windows). If linux, then ./standalone.sh -b 0.0.0.0

Then disable firewall and your LAN may connect to your IP (port is 8080, not 80)

Actually, you also can share localhost on Linux through ssh tunnel, like

ssh -L 127.0.0.1:8080:127.0.0.1:8080 root@server -N

but I doubt that you need it.


问:
JSON Array request cannot be applied error listener
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

```<code>private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }
</code>```

答:
Remove the first parameter of Request.Method.POST . JsonArrayRequest object  takes three parameter in constructor. URL, Listener , ErrorListener .

```<code>JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
</code>```

Body:
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }

Body:
Remove the first parameter of Request.Method.POST . JsonArrayRequest object  takes three parameter in constructor. URL, Listener , ErrorListener .

JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });


问:
Vertically center parent div on page
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

```<code><body>
 <div>
 My Logo goes here
 <div>
 <div>
  <section id="loginForm"></section>
  <section id="SocialLoginForm"></section>
 </div>
</body>
</code>```

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

答:
You have a few display options:

display:table (ie8 and above)

  html,
body {
  height: 100%;
  width: 100%;
}

body {
  display: table;
  margin: 0;
}

body>div {
  display: table-row;
}

body>div+div {

  display: table-cell;
  height: 100%;
  vertical-align: middle;
  text-align:center;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  My Logo goes here
</div>
<div>
  <section id="loginForm">lg form</section>
  <section id="SocialLoginForm">socl form</section>
</div></code>```

```<code>display:flex;
</code>```

body {
  margin: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

div+div {
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  My Logo goes here
</div>
<div>
  <section id="loginForm">lg form</section>
  <section id="SocialLoginForm">socl form</section>
</div></code>```

```<code>display:grid;
</code>```

body {
  height: 100vh;
  margin:0;
  display: grid;
  grid-template-rows: auto 1fr;
}

div+div {
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  My Logo goes here
</div>
<div>
  <section id="loginForm">lg form</section>
  <section id="SocialLoginForm">socl form</section>
</div></code>```

All display method require a container with an height set.

there can be also method with transform, absolute, inline-block but no need to use tricks nowdays ;)

Title: Vertically center parent div on page

Body:
I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)

I have created a login page for my website.

There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

 My Logo goes here

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...

this is how it looks like, as you see there is a big gap at the bottom.

Body:
You have a few display options:

display:table (ie8 and above)

  html,
body {
  height: 100%;
  width: 100%;
}

body {
  display: table;
  margin: 0;
}

body>div {
  display: table-row;
}

body>div+div {

  display: table-cell;
  height: 100%;
  vertical-align: middle;
  text-align:center;
  }

<div>
  My Logo goes here
</div>
<div>
  <section id="loginForm">lg form</section>
  <section id="SocialLoginForm">socl form</section>
</div>

display:flex;

body {
  margin: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

div+div {
  margin: auto;
}

<div>
  My Logo goes here
</div>
<div>
  <section id="loginForm">lg form</section>
  <section id="SocialLoginForm">socl form</section>
</div>

display:grid;

body {
  height: 100vh;
  margin:0;
  display: grid;
  grid-template-rows: auto 1fr;
}

div+div {
  margin: auto;
}

<div>
  My Logo goes here
</div>
<div>
  <section id="loginForm">lg form</section>
  <section id="SocialLoginForm">socl form</section>
</div>

All display method require a container with an height set.

there can be also method with transform, absolute, inline-block but no need to use tricks nowdays ;)


答:
problems like this can be solved by using colspan or rowspan.
for example you probably need something like:

```<code><table border=1><tr><td>headline 1</td><td rowspan=2>image</td>
<tr><td>headline2</td></tr></table>
</code>```

Seems to work for me.

Title: Table layout in HTML

Body:
I'm trying to make a table in HTML and i need help.
Here's a rough drawing:

Drawing

Can it be done?

Body:
problems like this can be solved by using colspan or rowspan.
for example you probably need something like:

<table border=1><tr><td>headline 1</td><td rowspan=2>image</td>
<tr><td>headline2</td></tr></table>

Seems to work for me.


问:
Speeding up data retrieval from SQL to Pandas for particular values of a column
I am trying to train a attention model on a huge dataset (~150 GB). I have converted the CSV to a SQL database using odo. My current workflow is to select two thousand customers at random and pull their ten records from the database. Each customer has a maximum of ten records.But, pulling the data is taking a lot of time ( 2 minutes on average).
How can I speed up the data fetching process? My current code looks like this:

```<code>ids=# list of customer ids
df=pd.read_sql_query('SELECT * FROM records WHERE cust_id IN(%s) LIMIT 20000' % ",".join(map(str,ids))',con=disk_engine)
</code>```

EDIT:

I created the database using the following code :

```<code>from odo import odo, resource, discover
import sqlite3
from sqlalchemy import create_engine

dshape = discover(resource('original_csv.csv'))

odo('original_csv.csv', 'sqlite:///whole_data.db::records',dshape=dshape,header=True)
</code>```

The CSV file contains cust_id and ~300 other features used for training

答:
Your time issue is not with pandas but with your SQL engine.
If you didn't do it, you can add an index on cust_id field in your table records, this should speed up your query.

Body:
I am trying to train a attention model on a huge dataset (~150 GB). I have converted the CSV to a SQL database using odo. My current workflow is to select two thousand customers at random and pull their ten records from the database. Each customer has a maximum of ten records.But, pulling the data is taking a lot of time ( 2 minutes on average).
How can I speed up the data fetching process? My current code looks like this:

ids=# list of customer ids
df=pd.read_sql_query('SELECT * FROM records WHERE cust_id IN(%s) LIMIT 20000' % ",".join(map(str,ids))',con=disk_engine)

EDIT:

I created the database using the following code :

from odo import odo, resource, discover
import sqlite3
from sqlalchemy import create_engine

dshape = discover(resource('original_csv.csv'))

odo('original_csv.csv', 'sqlite:///whole_data.db::records',dshape=dshape,header=True)

The CSV file contains cust_id and ~300 other features used for training


问:
how to write if else under return react native
hope you are doing well.

I am stuck in little problem is i want to pass a  tag only if my condition goes true.

for ex:

```<code>render(
   return(
     <View>
         {
          if(data==='test')
            {
              <Text>Hello this is Test Execution </Text>
            }
         }
     </View>
   )
)
</code>```

i want to do exactly like above example.

i get some errors i can't understand what to do so please help me.

Thank you

答:
You need to write a function which optionally renders your text. </p>

```<code>  renderText(data) {
      if (data === 'test') {
         return  <Text>Hello this is Test Execution </Text>;
      }
  }
  render() {
      return(
          <View>
              {this.renderText(data)}
          </View>
      );
  }
</code>```

Body:
hope you are doing well.

I am stuck in little problem is i want to pass a  tag only if my condition goes true.

for ex:

render(
   return(
     <View>
         {
          if(data==='test')
            {
              <Text>Hello this is Test Execution </Text>
            }
         }
     </View>
   )
)

i want to do exactly like above example.

i get some errors i can't understand what to do so please help me.

Thank you

Body:
You need to write a function which optionally renders your text.

  renderText(data) {
      if (data === 'test') {
         return  <Text>Hello this is Test Execution </Text>;
      }
  }
  render() {
      return(
          <View>
              {this.renderText(data)}
          </View>
      );
  }


问:
How to put a sub inside a regex in Perl 6?

That's what I'm trying to do.

>  my sub nplus1($n) {$n +1}
> my regex nnplus1 { ^ (\d+) &nplus1($0) $ }
> "123" ~~ &nnplus1
P6opaque: no such attribute '$!pos' in type Match...
```

答:
The <{...}> construct runs Perl 6 code inside a regex, and evaluates the result as a regex:

my sub nplus1($n) {$n +1}
my regex nnplus1 { ^ (\d+) <{ nplus1($0) }> $ }
say so '23' ~~ &nnplus1;    # Output: True
say so '22' ~~ &nnplus1;    # Output: False


问:
Creating thread safe timed queue in C for *nix
One part of my program creates some kind of messages. These messages are then processed in the second part.

I need some kind of timed queue between parts of my program that can keep messages in memory X seconds. X don't change while this timed queue exists.

Ideally this should look like this:

```<code>tqueue_t *tqueue_new(int seconds);
int tqueue_push(tqueue_t *queue, void *msg);
void *tqueue_pop(tqueue_t *queue);
</code>```

tqueue_pop() should block and return when first message was in queue for X seconds.

What is the best way to do this? Maybe there are some already existing solutions?

Language: C

OS: *nix

Also, this queue should work in threaded evironment.

答:
You should be able to build this on top of POSIX Message Queues and let it take care of most of the details.  Something like:

(1) write queue with a time stamp field

(2) In your other thread either block on mq_receive() until a message comes in (or use mq_notify() to signal or create the thread for you).

(3) Read the queue and check the time stamp.

(4) Calculate the time difference for how long you have to wait and use select() or some sleep/timer mechanism.

(5) Process the message.

Body:
One part of my program creates some kind of messages. These messages are then processed in the second part.

I need some kind of timed queue between parts of my program that can keep messages in memory X seconds. X don't change while this timed queue exists.

Ideally this should look like this:

tqueue_t *tqueue_new(int seconds);
int tqueue_push(tqueue_t *queue, void *msg);
void *tqueue_pop(tqueue_t *queue);

tqueue_pop() should block and return when first message was in queue for X seconds.

What is the best way to do this? Maybe there are some already existing solutions?

Language: C

OS: *nix

Also, this queue should work in threaded evironment.


问:
How aut create raw number in column B if relevant cell in column C is empty via VBA?
How Can I create code in VBA, which can do below command:
- Once any info (value or data) entered to the relative cell in column C, automatically create number for that raw in column B.
For example: once user entered request text in column C4,AUT create request number in column B4. I have created below code, however it is not working. Could you please help what is wrong?

```<code>Sub requestnumber()

Dim lRow As Integer
Dim i As Integer
Dim m As Integer

lRow = Cells(Rows.Count, 2).End(xlUp).Row

For i = 1 To i = lRow

m = Range("B1").Offset(i, 0).Activate

If Range("B1").Offset(i, 0) <> "" Then

Range("A1").Offset(i, 0) = lRow

Exit For

End If

Next i

End Sub
</code>```

Thanks!
Shahla H.

答:
I am trying to guess what are you asking for. If you need number of row in column B when cell in column C is filled you don't need VBA. Just type formula in B column:</p>

```<code>=IF(ISBLANK(C1), "", ROW())
</code>```

Body:
How Can I create code in VBA, which can do below command:
- Once any info (value or data) entered to the relative cell in column C, automatically create number for that raw in column B.
For example: once user entered request text in column C4,AUT create request number in column B4. I have created below code, however it is not working. Could you please help what is wrong?

Sub requestnumber()

Dim lRow As Integer
Dim i As Integer
Dim m As Integer

lRow = Cells(Rows.Count, 2).End(xlUp).Row

For i = 1 To i = lRow

m = Range("B1").Offset(i, 0).Activate

If Range("B1").Offset(i, 0) <> "" Then

Range("A1").Offset(i, 0) = lRow

Exit For

End If

Next i

End Sub

Thanks!
Shahla H.

Body:
I am trying to guess what are you asking for. If you need number of row in column B when cell in column C is filled you don't need VBA. Just type formula in B column:

=IF(ISBLANK(C1), "", ROW())


问:
Scrape the
 tag using Python Selenium
I have a requirement to extract the
 tag from the HTML. However I am not able to get it done.
This is the HTML:

        Press "New Word"

```

<p>I tried using the following, but I dont get the text.</p>

<pre class="lang-python prettyprint-override"><code>word = driver.find_element_by_xpath('//*[@id="gennedword"]')
print(word.get_attribute('text'))
print(word.get_attribute('innerHTML'))
</code>```

All it returns was None and for innerHtml I get -

```

答:
I was able to solve the issue.
Added a sleep for 1 sec and the text appeared.

Thanks all for the help

Title: Scrape the <p> tag using Python Selenium

Body:
I have a requirement to extract the
 tag from the HTML. However I am not able to get it done.
This is the HTML:

        Press "New Word"

I tried using the following, but I dont get the text.

word = driver.find_element_by_xpath('//*[@id="gennedword"]')
print(word.get_attribute('text'))
print(word.get_attribute('innerHTML'))

All it returns was None and for innerHtml I get -