问:
Perl Multiple search and replace actions in one large text file
Given a set of replacement strings in a file replacements.txt like

```<code>s/string1/replacement1/g;
s/string2/replacement2/g;
s/string3/replacement3/g;
s/string4/replacement4/g;
s/string5/replacement5/g;
</code>```

I would like to obtain the equivalent of

```<code>sed -f replacements.txt infile.txt
</code>```

my file is so big that sed cant handle it, while I know that perl could do the trick.

Also the replacements are really a lot, and change from time to time. ( I need to run this a dozen of times)

Note that the replacements are fixed strings, so I do not really need those to be regular expressions.

sed has problems only when the regexp  has globs and the input file is a single large line.

答:
The perl equivalent of your sed command is:

```<code>perl -p replacements.txt infile.txt
</code>```

It should work with your sample replacements.txt, given that the s statements are properly ;-terminated (note that sed would recognize the end of the line by itself as the statement terminator).

The real problem, however, is that the entire large file is a single line, so the key to avoiding running out of memory is to:

temporarily break that line into many short lines,

send these short lines through the pipeline and perform the string replacements on them,

and then re-join the modified short lines to form a single line again.

If there's a character in the data that delimits records (units of data), in a away that doesn't interfere with the string replacements, breaking the long line into multiple ones with the help of tr is a viable approach; I'll use } as an example, because Kuzeko states that the data is JSON-like:

If you have GNU sed (Linux; verify with sed --version):

```<code>tr '}' '\0' < infile.txt | sed -z -f replacements.txt | tr '\0' '}'
</code>```

Having tr output NUL-separated "lines" (\0) and sed read them accordingly (-z) is the most robust way to handle the chunking.

Unfortunately, the -z / --null-data option is not POSIX-compliant and the BSD/macOS implementation does not support it.

Otherwise (e.g., on macOS):

```<code>tr '}' '\n' < infile.txt | perl -p replacements.txt infile.txt | tr '\n' '}'
</code>```

Caveat: If the single line in infile.txt has a trailing \n, you'll end up with an extra } char. at the end; to prevent that, add an initial tr stage to the pipeline that deletes the \n:

tr -d '\n' < infile.txt | tr '}' '\n' | ...

perl is still needed, because - unlike BSD/macOS sed - it preserves the trailing-\n-or-not status of the input's last line.

Body:
Given a set of replacement strings in a file replacements.txt like

s/string1/replacement1/g;
s/string2/replacement2/g;
s/string3/replacement3/g;
s/string4/replacement4/g;
s/string5/replacement5/g;

I would like to obtain the equivalent of

sed -f replacements.txt infile.txt

my file is so big that sed cant handle it, while I know that perl could do the trick.

Also the replacements are really a lot, and change from time to time. ( I need to run this a dozen of times)

Note that the replacements are fixed strings, so I do not really need those to be regular expressions.

sed has problems only when the regexp  has globs and the input file is a single large line.

Body:
The perl equivalent of your sed command is:

perl -p replacements.txt infile.txt

It should work with your sample replacements.txt, given that the s statements are properly ;-terminated (note that sed would recognize the end of the line by itself as the statement terminator).

The real problem, however, is that the entire large file is a single line, so the key to avoiding running out of memory is to:

temporarily break that line into many short lines,

send these short lines through the pipeline and perform the string replacements on them,

and then re-join the modified short lines to form a single line again.

If there's a character in the data that delimits records (units of data), in a away that doesn't interfere with the string replacements, breaking the long line into multiple ones with the help of tr is a viable approach; I'll use } as an example, because Kuzeko states that the data is JSON-like:

If you have GNU sed (Linux; verify with sed --version):

tr '}' '\0' < infile.txt | sed -z -f replacements.txt | tr '\0' '}'

Having tr output NUL-separated "lines" (\0) and sed read them accordingly (-z) is the most robust way to handle the chunking.

Unfortunately, the -z / --null-data option is not POSIX-compliant and the BSD/macOS implementation does not support it.

Otherwise (e.g., on macOS):

tr '}' '\n' < infile.txt | perl -p replacements.txt infile.txt | tr '\n' '}'

Caveat: If the single line in infile.txt has a trailing \n, you'll end up with an extra } char. at the end; to prevent that, add an initial tr stage to the pipeline that deletes the \n:

tr -d '\n' < infile.txt | tr '}' '\n' | ...

perl is still needed, because - unlike BSD/macOS sed - it preserves the trailing-\n-or-not status of the input's last line.


来源: stackexchange

问:
Calculate total CPU usage
What is best algorithm for calculating total CPU usage at a particular time during execution of a process.

I am working windows platform in C++.

答: GetProcessTimes for 100-nanosecond resolution. If you want cycle times, use QueryProcessCycleTime in Vista and above.

ContentLicense: CC BY-SA 2.5

Title: Calculate total CPU usage

LastEditorDisplayName: Martin

OwnerDisplayName: MSN

ContentLicense: CC BY-SA 3.0


问:
SEARCH THROUGH ROW FOR SPECIFIC VALUE IN ORACLE
I want to search in Table row with 32 columns, in each of one for specific value and count appearance , is it possible to query entire row without typing every column name in oracle ???</p>

答:
Yes it is possible but the solution is not fast, and require basic knowledge about xquery.

prepare test table

```<code>create table test_objects as select * from user_objects where rownum < 100;

select * from
     xmltable('for $row in ora:view("test_objects")/ROW return count($row/*[contains(text(),$TO_SEARCH)])' passing 'N' as "TO_SEARCH" columns cnt number path '.');
</code>```

Query counts columns which contain  "N" in value.

if you change a bit a query we can see which columns contain searched value

```<code>select * from
     xmltable('for $row in ora:view("test_objects")/ROW return <ROW><CNT>{count($row/*[contains(text(),$TO_SEARCH)])}</CNT><COLUMNS>{string-join($row/*[contains(text(),$TO_SEARCH)]/name(),", " )}</COLUMNS></ROW>' passing 'N' as "TO_SEARCH"
     columns
     cnt number path 'CNT'
     , list_of_column varchar2(4000) path 'COLUMNS'
     );
</code>```

Body:
Yes it is possible but the solution is not fast, and require basic knowledge about xquery.

prepare test table

create table test_objects as select * from user_objects where rownum < 100;

select * from
     xmltable('for $row in ora:view("test_objects")/ROW return count($row/*[contains(text(),$TO_SEARCH)])' passing 'N' as "TO_SEARCH" columns cnt number path '.');

Query counts columns which contain  "N" in value.

if you change a bit a query we can see which columns contain searched value

select * from
     xmltable('for $row in ora:view("test_objects")/ROW return <ROW><CNT>{count($row/*[contains(text(),$TO_SEARCH)])}</CNT><COLUMNS>{string-join($row/*[contains(text(),$TO_SEARCH)]/name(),", " )}</COLUMNS></ROW>' passing 'N' as "TO_SEARCH"
     columns
     cnt number path 'CNT'
     , list_of_column varchar2(4000) path 'COLUMNS'
     );


问:
Convert String to SecureString
How to convert String to SecureString?

答:
The following 2 extensions should do the trick:

For a char array

```<code>public static SecureString ToSecureString(this char[] _self)
{
    SecureString knox = new SecureString();
    foreach (char c in _self)
    {
        knox.AppendChar(c);
    }
    return knox;
}
</code>```

And for string

```<code>public static SecureString ToSecureString(this string _self)
{
    SecureString knox = new SecureString();
    char[] chars = _self.ToCharArray();
    foreach (char c in chars)
    {
        knox.AppendChar(c);
    }
    return knox;
}
</code>```

Thanks to John Dagg for the AppendChar recommendation.

Title: Convert String to SecureString

Body: How to convert String to SecureString?

Body:
The following 2 extensions should do the trick:

For a char array

public static SecureString ToSecureString(this char[] _self)
{
    SecureString knox = new SecureString();
    foreach (char c in _self)
    {
        knox.AppendChar(c);
    }
    return knox;
}

And for string

public static SecureString ToSecureString(this string _self)
{
    SecureString knox = new SecureString();
    char[] chars = _self.ToCharArray();
    foreach (char c in chars)
    {
        knox.AppendChar(c);
    }
    return knox;
}

Thanks to John Dagg for the AppendChar recommendation.


问:
Passing a variable to a function (which alters said variable) repeatedly
I'm having a play with Rust and, probably biting off far more than I can chew, am trying to write a module that will encapsulate my database traffic for the rest of the application. The code I'm struggling with is the following:

```<code>pub fn create_statement(cypher: &str, params: &HashMap<&str, &str>) -> rusted_cypher::Statement {
    let mut statement = rusted_cypher::Statement::new(cypher);
    for (field, value) in params.iter() {
        statement.with_param(field.to_owned(), value.to_owned());
    }
    return statement;
}
</code>```

This gives the following error: error[E0382]: use of moved value: statement. My searching has, I think, lead me to what this means (the Statement struct is not copyable, thus gets moved and is then ... effectively no longer accessible, I guess?), but I'm not sure how to get around it. Can anyone point me in the direction of a solution?

答:
I haven't used this API before but, according to its documentation:

This method consumes self and returns it with the parameter added, so the binding does not need to be mutable.

It isn't, as you say, that the struct is "not copyable", it's that the with_param method is intentionally written in such a way that it moves the value and takes ownership - we can also say that it consumes it. Consuming the value is a common thing to do in a builder-style API because it prevents you from having accidental half-built objects lying around. Each builder method will consume the object, during which time nothing else can access it, and then return it when it's finished so you can continue using it. From the documentation:

```<code>let statement = Statement::new("MATCH n RETURN n")
    .with_param("param1", "value1")?
    .with_param("param2", 2)?
    .with_param("param3", 3.0)?;
</code>```

Each call to with_param consumes statement and then returns it so you can call with_param again.

Where this gets a bit tricky is that the result of the with_param is not a Statement, but a Result<Statement, JsonError>. Apparently adding a parameter could cause an error so the result is wrapped up to accommodate that possibility. That's what the ?s are for - they unwrap that result into the underlying value, or else propagate the error if that can't be done.

As one of the other answers already suggested, a better fix is to just use the set_parameters method, which will set them all in one go.

Another way to do it would be to use the return value of each call to with_param:

```<code>pub fn create_statement(cypher: &str, params: &HashMap<&str, &str>) -> rusted_cypher::Statement {
  let mut statement = rusted_cypher::Statement::new(cypher);
  for (field, value) in params.iter() {
      statement = statement.with_param(field.to_owned(), value.to_owned()).unwrap();
  }
  statement
}
</code>```

When you use the return value, you have access to the value again, so you can keep on using it.

Notice that I used unwrap() to get the value from the Result. This is not good practice because it will cause a panic if the result is an error. I have done this here to focus on explaining move semantics without a digression into error handling, which is a topic by itself.

Body:
I'm having a play with Rust and, probably biting off far more than I can chew, am trying to write a module that will encapsulate my database traffic for the rest of the application. The code I'm struggling with is the following:

pub fn create_statement(cypher: &str, params: &HashMap<&str, &str>) -> rusted_cypher::Statement {
    let mut statement = rusted_cypher::Statement::new(cypher);
    for (field, value) in params.iter() {
        statement.with_param(field.to_owned(), value.to_owned());
    }
    return statement;
}

This gives the following error: error[E0382]: use of moved value: statement. My searching has, I think, lead me to what this means (the Statement struct is not copyable, thus gets moved and is then ... effectively no longer accessible, I guess?), but I'm not sure how to get around it. Can anyone point me in the direction of a solution?

Body:
I haven't used this API before but, according to its documentation:

This method consumes self and returns it with the parameter added, so the binding does not need to be mutable.

It isn't, as you say, that the struct is "not copyable", it's that the with_param method is intentionally written in such a way that it moves the value and takes ownership - we can also say that it consumes it. Consuming the value is a common thing to do in a builder-style API because it prevents you from having accidental half-built objects lying around. Each builder method will consume the object, during which time nothing else can access it, and then return it when it's finished so you can continue using it. From the documentation:

let statement = Statement::new("MATCH n RETURN n")
    .with_param("param1", "value1")?
    .with_param("param2", 2)?
    .with_param("param3", 3.0)?;

Each call to with_param consumes statement and then returns it so you can call with_param again.

Where this gets a bit tricky is that the result of the with_param is not a Statement, but a Result<Statement, JsonError>. Apparently adding a parameter could cause an error so the result is wrapped up to accommodate that possibility. That's what the ?s are for - they unwrap that result into the underlying value, or else propagate the error if that can't be done.

As one of the other answers already suggested, a better fix is to just use the set_parameters method, which will set them all in one go.

Another way to do it would be to use the return value of each call to with_param:

pub fn create_statement(cypher: &str, params: &HashMap<&str, &str>) -> rusted_cypher::Statement {
  let mut statement = rusted_cypher::Statement::new(cypher);
  for (field, value) in params.iter() {
      statement = statement.with_param(field.to_owned(), value.to_owned()).unwrap();
  }
  statement
}

When you use the return value, you have access to the value again, so you can keep on using it.

Notice that I used unwrap() to get the value from the Result. This is not good practice because it will cause a panic if the result is an error. I have done this here to focus on explaining move semantics without a digression into error handling, which is a topic by itself.


问:
how to reset <input type = "file">
I am developing a metro app with VS2012 and Javascript

I want to reset the contents of my file input:

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />
```

How should I do that?

答:
Another solution (without selecting HTML DOM elements )

If you added 'change' event listener on that input, then in javascript code you can call (for some specified conditions):

```<code>event.target.value = '';
</code>```

For example in HTML:

```<code><input type="file" onChange="onChangeFunction(event)">
</code>```

And in javascript:

```<code>onChangeFunction(event) {
  let fileList = event.target.files;
  let file = fileList[0];
  let extension = file.name.match(/(?<=\.)\w+$/g)[0].toLowerCase(); // assuming that this file has any extension

  if (extension === 'jpg') {
    alert('Good file extension!');
  }
  else {
    event.target.value = '';
    alert('Wrong file extension! File input is cleared.');
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to reset <input type = "file">

Body:
I am developing a metro app with VS2012 and Javascript

I want to reset the contents of my file input:

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />

How should I do that?

Body:
Another solution (without selecting HTML DOM elements )

If you added 'change' event listener on that input, then in javascript code you can call (for some specified conditions):

event.target.value = '';

For example in HTML:

<input type="file" onChange="onChangeFunction(event)">

And in javascript:

onChangeFunction(event) {
  let fileList = event.target.files;
  let file = fileList[0];
  let extension = file.name.match(/(?<=\.)\w+$/g)[0].toLowerCase(); // assuming that this file has any extension

  if (extension === 'jpg') {
    alert('Good file extension!');
  }
  else {
    event.target.value = '';
    alert('Wrong file extension! File input is cleared.');
  }


问:
convert elements after xml to array
I have an XML with products and I converted it to Array from XML using this function http://www.bin-co.com/php/scripts/xml2array/
I have a problem when I have only one attribute in XML file and I'm trying to convert first array into multidimensional.

```<code>[attributes] => Array
    (
        [attribute] => Array
            (
                [name] => 44
                [quantity] => 1
                [availability] => 1
            )

    )
</code>```

to

```<code>    [attributes] => Array
        (
            [attribute] => Array
                (
                    [0] => Array
                        (
                            [name] => 40
                            [quantity] => 1
                            [availability] => 1
                        )
                )
        )
</code>```

I need a multidimensional array for a loop

```<code>foreach($products["attributes"]["attribute"] as $attr) {
    echo $attr["name"]
}
</code>```

XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <id>1006</id>
        <sku>360116 05</sku>
        <attributes>
            <attribute>
                <name>44</name>
                <quantity>1</quantity>
                <availability>1</availability>
            </attribute>
        </attributes>
    </product>
    <product>
        <id>2501</id>
        <sku>AQ4040</sku>
        <attributes>
            <attribute>
                <name>42.5</name>
                <quantity>13</quantity>
                <availability>2</availability>
            </attribute>
            <attribute>
                <name>44</name>
                <quantity>18</quantity>
                <availability>2</availability>
            </attribute>
        </attributes>
    </product>
</products>
</code>```

答:
If you need to get at the items in this sort of structure, it could be simpler to use SimpleXML.  The following code access the data very simply.

```<code><?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$xmlText = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <id>1006</id>
        <sku>360116 05</sku>
        <attributes>
            <attribute>
                <name>44</name>
                <quantity>1</quantity>
                <availability>1</availability>
            </attribute>
        </attributes>
    </product>
    <product>
        <id>2501</id>
        <sku>AQ4040</sku>
        <attributes>
            <attribute>
                <name>42.5</name>
                <quantity>13</quantity>
                <availability>2</availability>
            </attribute>
            <attribute>
                <name>44</name>
                <quantity>18</quantity>
                <availability>2</availability>
            </attribute>
        </attributes>
    </product>
</products>
XML;

$doc = simplexml_load_string($xmlText);

foreach ( $doc->product as $product)   {
   echo "Product id=".$product->id.",";
   foreach ( $product->attributes->attribute as $attribute){
       echo "name:".$attribute->name.",";
   }
   echo "\n";
}

echo "Complete";
</code>```

The output of which is...

```<code>Product id=1006,name:44,
Product id=2501,name:42.5,name:44,
Complete
</code>```

When loaded using simple_xml_ you can then access sub-elements as though they are attributes of the element above, so $product->attributes->attribute uses each product and then picks out the attributes element and then each attribute element within that.
To load from a file, use simplexml_load_file().

Title: convert elements after xml to array

Body:
I have an XML with products and I converted it to Array from XML using this function http://www.bin-co.com/php/scripts/xml2array/
I have a problem when I have only one attribute in XML file and I'm trying to convert first array into multidimensional.

[attributes] => Array
    (
        [attribute] => Array
            (
                [name] => 44
                [quantity] => 1
                [availability] => 1
            )

    )

to

    [attributes] => Array
        (
            [attribute] => Array
                (
                    [0] => Array
                        (
                            [name] => 40
                            [quantity] => 1
                            [availability] => 1
                        )
                )
        )

I need a multidimensional array for a loop

foreach($products["attributes"]["attribute"] as $attr) {
    echo $attr["name"]
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <id>1006</id>
        <sku>360116 05</sku>
        <attributes>
            <attribute>
                <name>44</name>
                <quantity>1</quantity>
                <availability>1</availability>
            </attribute>
        </attributes>
    </product>
    <product>
        <id>2501</id>
        <sku>AQ4040</sku>
        <attributes>
            <attribute>
                <name>42.5</name>
                <quantity>13</quantity>
                <availability>2</availability>
            </attribute>
            <attribute>
                <name>44</name>
                <quantity>18</quantity>
                <availability>2</availability>
            </attribute>
        </attributes>
    </product>
</products>

Body:
If you need to get at the items in this sort of structure, it could be simpler to use SimpleXML.  The following code access the data very simply.

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$xmlText = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <id>1006</id>
        <sku>360116 05</sku>
        <attributes>
            <attribute>
                <name>44</name>
                <quantity>1</quantity>
                <availability>1</availability>
            </attribute>
        </attributes>
    </product>
    <product>
        <id>2501</id>
        <sku>AQ4040</sku>
        <attributes>
            <attribute>
                <name>42.5</name>
                <quantity>13</quantity>
                <availability>2</availability>
            </attribute>
            <attribute>
                <name>44</name>
                <quantity>18</quantity>
                <availability>2</availability>
            </attribute>
        </attributes>
    </product>
</products>
XML;

$doc = simplexml_load_string($xmlText);

foreach ( $doc->product as $product)   {
   echo "Product id=".$product->id.",";
   foreach ( $product->attributes->attribute as $attribute){
       echo "name:".$attribute->name.",";
   }
   echo "\n";
}

echo "Complete";

The output of which is...

Product id=1006,name:44,
Product id=2501,name:42.5,name:44,
Complete

When loaded using simple_xml_ you can then access sub-elements as though they are attributes of the element above, so $product->attributes->attribute uses each product and then picks out the attributes element and then each attribute element within that.
To load from a file, use simplexml_load_file().


问:
Wordpress: Enabling GZIP compression
According the GTMetrix Page and Googe Pagespeed I need to enable for many ressources the GZIP compression. But www.checkgzipcompression.com says GZIP is enabled. How can I enable my GZIP Compression?</p>

答:
www.checkgzipcompression.com will count GZIP enable even if GZIP is enabled for a single filetype only while pagespeed tools like Pingdom and GTMetrix want you to integrate GZIP compression for all the file types out possible.

You can enable GZIP compression both manually by updating your .htaccess or by using a plugin which will do the same for you but with a user friendly UI.

If you want to enable GZIP compression manually, add the following code to your .htaccess file in your WP root directory.

```<code><IfModule mod_deflate.c>
    # Compress HTML, CSS, JavaScript, Text, XML and fonts
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
    AddOutputFilterByType DEFLATE application/x-font
    AddOutputFilterByType DEFLATE application/x-font-opentype
    AddOutputFilterByType DEFLATE application/x-font-otf
    AddOutputFilterByType DEFLATE application/x-font-truetype
    AddOutputFilterByType DEFLATE application/x-font-ttf
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE font/opentype
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE image/x-icon
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/xml

    # Remove browser bugs (only needed for really old browsers)
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    Header append Vary User-Agent
</IfModule>
</code>```

The above code is for Apache server. If you're on NGINX server, use this code instead in nginx.conf file:

```<code>gzip on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
gzip_vary on;
gzip_types text/plain text/css text/javascript image/svg+xml image/x-icon application/javascript application/x-javascript;
</code>```

Now, GZIP compression can be enabled with many caching plugins, popular of them is W3 Total Cache. Check this article on how to setup W3 Total Cache and it's GZIP compression module.

Code Source

Title: Wordpress: Enabling GZIP compression

Body:
www.checkgzipcompression.com will count GZIP enable even if GZIP is enabled for a single filetype only while pagespeed tools like Pingdom and GTMetrix want you to integrate GZIP compression for all the file types out possible.

You can enable GZIP compression both manually by updating your .htaccess or by using a plugin which will do the same for you but with a user friendly UI.

If you want to enable GZIP compression manually, add the following code to your .htaccess file in your WP root directory.

<IfModule mod_deflate.c>
    # Compress HTML, CSS, JavaScript, Text, XML and fonts
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
    AddOutputFilterByType DEFLATE application/x-font
    AddOutputFilterByType DEFLATE application/x-font-opentype
    AddOutputFilterByType DEFLATE application/x-font-otf
    AddOutputFilterByType DEFLATE application/x-font-truetype
    AddOutputFilterByType DEFLATE application/x-font-ttf
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE font/opentype
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE image/x-icon
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/xml

    # Remove browser bugs (only needed for really old browsers)
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    Header append Vary User-Agent
</IfModule>

The above code is for Apache server. If you're on NGINX server, use this code instead in nginx.conf file:

gzip on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
gzip_vary on;
gzip_types text/plain text/css text/javascript image/svg+xml image/x-icon application/javascript application/x-javascript;

Now, GZIP compression can be enabled with many caching plugins, popular of them is W3 Total Cache. Check this article on how to setup W3 Total Cache and it's GZIP compression module.

Code Source


问:
JAVAME: Sort Java Vector
What would be the best and most efficient way to sort a Java Vector in JAVAME.

My object has five properties, and I would like to sort by a property called price which is of type double. In my Vector I will have a maximum of 150 items. A sample code would be appreciated.

Thanx for your time.

答:
```<code>import java.lang.reflect.Field;
import java.util.*;

public class Sorter {

    public static List sort(List list, String fieldName, boolean asc) {
        Comparator c = new FieldComparator(fieldName, asc);
        Collections.sort(list, c);
        return list;
    }

    public static int compareNumbers(Number n1, Number n2) {
        double d1 = n1.doubleValue();
        double d2 = n2.doubleValue();

        if (d1 < d2) {
            return -1;
        }
        if (d2 < d1) {
            return 1;
        }
        return 0;
    }

    public static int compareDates(Date d1, Date d2) {
        long l1 = d1.getTime();
        long l2 = d2.getTime();

        if (l1 < l2) {
            return -1;
        }
        if (l2 < l1) {
            return 1;
        }
        return 0;
    }

    public static int compareStrings(String s1, String s2) {
        return s1.compareTo(s2);
    }

    public static Object getFieldValue(Object obj, String fn) {
        try {
            Class clazz = obj.getClass();
            Field f = null;
            try {
                f = clazz.getDeclaredField(fn);
            } catch (Exception e) {}

            while (f == null && clazz.getSuperclass() != null) {
                clazz = clazz.getSuperclass();
                try {
                    f = clazz.getDeclaredField(fn);
                } catch (Exception e) {}
            }//while

            if (f != null) {
                f.setAccessible(true);
                return f.get(obj);
            }
        } catch (IllegalAccessException e) {}
        return null;
    }

    protected static class FieldComparator implements Comparator {
        String fieldName;
        int asc;

        protected FieldComparator(String fieldName, boolean asc) {
            this.fieldName = fieldName;
            this.asc = asc ? 1 : -1;
        }

        public int compare(Object o1, Object o2) {
            if (o1 == null) {
                if (o2 == null) {
                    return 0;
                } else {
                    return -1 * asc;
                }
            }

            if (o2 == null) {
                return asc;
            }

            //compare fields
            Object fieldValue1 = getFieldValue(o1, fieldName);
            Object fieldValue2 = getFieldValue(o2, fieldName);

            if (fieldValue1 == null) {
                if (fieldValue2 == null) {
                    return 0;
                } else {
                    return -1 * asc;
                }
            }

            if (fieldValue2 == null) {
                return asc;
            }

            //both field values aren't nulls
            if (fieldValue1 instanceof Number && fieldValue2 instanceof Number) {
                return compareNumbers((Number) fieldValue1, (Number) fieldValue2) * asc;
            } else if (fieldValue1 instanceof Date && fieldValue2 instanceof Date) {
                return compareDates((Date) fieldValue1, (Date) fieldValue2) * asc;
            } else {
                return compareStrings(fieldValue1.toString(), fieldValue2.toString()) * asc;
            }
        }
    }

    public static void main(String[] args) {
        ArrayList source = new ArrayList();
        source.add(new TestNumber(5));
        source.add(new TestNumber(1));
        source.add(new TestNumber(4));
        source.add(new TestNumber(2));
        source.add(new TestNumber(3));

        List dest = sort(source, "value", true);
        out(dest);

        source = new ArrayList();
        source.add(new TestString("cc"));
        source.add(new TestString("dd"));
        source.add(new TestString("bb"));
        source.add(new TestString("ee"));
        source.add(new TestString("aa"));

        dest = sort(source, "value", false);
        out(dest);
    }

    private static class TestNumber {
        private int value;

        public TestNumber(int v) {
            value = v;
        }

        public String toString() {
            return "" + value;
        }
    }

    private static class TestString {
        private String value;

        public TestString(String v) {
            value = v;
        }

        public String toString() {
            return "" + value;
        }
    }

    private static void out(List list) {
        for (Object obj : list) {
            System.out.println("" + obj.toString());
        }
        System.out.println("----------------------------");
    }
}
</code>```

Title: JAVAME: Sort Java Vector


问:
SSL still displaying as unsecure
I'm trying to set up my SSL certificate but the site still says that https is unsecure.

I've edited the 000-default.conf as follows:

```<code><VirtualHost *:80>
    ServerName millingtonmayers.co.uk
    Redirect permanent / https://millingtonmayers.co.uk/
 </VirtualHost>

 <VirtualHost *:443>
    ServerName millingtonmayers.co.uk
    SSLEngine on
    SSLCertificateFile /home/bensleym/millingtonmayers.co.uk.crt
    SSLCertificateKeyFile /home/bensleym/millingtonmayers.co.uk.key
    SSLCertificateChainFile /home/bensleym/intermediate.crt
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless

    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
 </VirtualHost>
</code>```

The redirect doesn't seem to be working either any ideas?

答:
certificate signing process as follows:

Genarate key and the csr
"openssl req -new -newkey rsa:1024 -nodes -keyout millingtonmayers.co.uk.key -out millingtonmayers.co.uk..csr"

2.Send the CSR for CA agent like comodo (https://www.instantssl.com/free-ssl-certificate.html).you will get the following certificates from the CA.
 CA agent will provide 3 certs

2.1.The Root Certificate

2.2.Intermediate certificates

2.3. millingtonmayers.co.uk.crt

You can get 90 days free cert from above

3.concatanate the above 3 certificate to one.

cat  millingtonmayers.co.uk.crt DigiCertCA.crt TrustedRoot.crt   >millingtonmayers.co.uk.concatanated.crt

4.configure the millingtonmayers.co.uk.concatanated.crt and millingtonmayers.co.uk.key to lb

Title: SSL still displaying as unsecure

Body:
I'm trying to set up my SSL certificate but the site still says that https is unsecure.

I've edited the 000-default.conf as follows:

<VirtualHost *:80>
    ServerName millingtonmayers.co.uk
    Redirect permanent / https://millingtonmayers.co.uk/
 </VirtualHost>

 <VirtualHost *:443>
    ServerName millingtonmayers.co.uk
    SSLEngine on
    SSLCertificateFile /home/bensleym/millingtonmayers.co.uk.crt
    SSLCertificateKeyFile /home/bensleym/millingtonmayers.co.uk.key
    SSLCertificateChainFile /home/bensleym/intermediate.crt
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless

    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
 </VirtualHost>

The redirect doesn't seem to be working either any ideas?


问:
trouble making an "if" statment with time.now on ruby on rails
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

```<code><% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>! <br>
<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

答:
You can write like this Instead of Parsing the Time you can write simply

Solution : 1

```<code><% if Time.now.hour >= 7 && Time.now.hour <= 14 %>
Good Morning <%= current_user.nome %>! <br>
<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

Solution : 2

you can write less code via using ternary operator

```<code>(0..11).include?(Time.now.hour) ? "Good Morning <%= current_user.nome %>" : Good Afternoon <%= current_user.nome %>
</code>```

Body:
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

<% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>!

<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

Body:
You can write like this Instead of Parsing the Time you can write simply

Solution : 1

<% if Time.now.hour >= 7 && Time.now.hour <= 14 %>
Good Morning <%= current_user.nome %>! <br>
<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>

Solution : 2

you can write less code via using ternary operator

(0..11).include?(Time.now.hour) ? "Good Morning <%= current_user.nome %>" : Good Afternoon <%= current_user.nome %>


问:
unable to validate email and number
I need help because I have added the following javascript(mentioned below in code) to my form and I am passing ID to js, but unable to validate it.

Javascript Code

```<code>function validateForm() {
    var x = document.getElementById('emailid').value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    var txt = document.getElementById('mobNo');
    var filter = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;
    var test_bool = filter.test(txt.value);
    if (test_bool == false) {
        alert('Please enter valid Mobile Number ');
        txt.focus();
        return false;
    }
}
</code>```

HTML

```<code><div class="form-group">
    <input type="email" class="form-control" value="" placeholder="Email ID" id="emailid" name="Email" required="required" maxlength="70" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>
<div class="form-group">
    <input type="text" class="form-control" value="" placeholder="Mobile Number" id="mobNo" name="number" required="required" maxlength="14" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>
</code>```

答:
There's a lot wrong with your code...

First, your HTML is not valid because your label elements have values for the for attributes that do not point to the id attribute values of the elements they are "for".

Additionally (and perhaps you do have it but aren't showing it in your question), you do not have a form element that contains all your inputs.

Now, since you are using input type=email and required in your HTML, you will get validation automatically. If you simply add the pattern attribute to your mobile phone filed, you won't need any JavaScript to validate as this is built-in. Using the built-in email field and then writing email validation code that validates the same way makes no sense.

<form action="#" method="post">

          <input type="email" required class="form-control"
                 placeholder="Email ID" id="emailid" name="Email"  maxlength="70">

          <input type="text" class="form-control" pattern="([0]|\+91|\+91-|\+91\s)?\d{10}" required
                 placeholder="Mobile Number" id="mobNo" name="number" maxlength="14">

         <input type="submit" value="Submit"><input type="reset">

</form>```
</div>
</div>
</p>

<p>If you do want to write your own validation code, then you would go back to using non-validation form fields or HTML5 custom validations. Assuming that were the case...</p>

<p>Your validation function is not ever being called. It needs to be "wired" up to an event, so that when the event occurs, the function will automatically be invoked. That is called a "callback function". Since you are working with a <code>form</code> (or should be), the form will have a <code>submit</code> event and this is the appropriate time to do form validation.</p>

<p>Additionally, your email validation logic is flawed (an email address of <code>me.you@</code> would be allowed for example). </p>

<p>Here's what the code should look like. I have removed the HTML validation so that you can see the JavaScript doing its job.</p>

<p>Please read the comments in the code for explanations on what is being done and why:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Don't mix HTML and JavaScript (as others have suggested). Keep them separate

// All this code should be placed inside of a <script> element and the entire thing
// should be placed just before the end of the body element (</body>) so that by the
// time this code runs all the HTML will have been read into memory.

// Get a reference to the elements you'll need to work with
var frm = document.querySelector("form");
var email = document.getElementById("emailid");
var mobNum = document.getElementById("mobNo");

// Set the form up to have a submit event callback function
// This is what makes it so that when your form is submitted,
// your validation function runs.
frm.addEventListener("submit", validateForm);

// This function will now be automatically called when the form is submitted
// All event handling functions will automatically be passed a reference to
// the event they are responding to and that reference will be passed as the
// first argument to the funciton (we are receiving that reference with the
// "evt" argument here).
function validateForm(evt) {

  // validate the email input with a regular expression
  var emailExpr = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  // validate the phone number with a regular expression
  var mobNumExpr = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;

  // Assume the form is valid
  var valid = true;

  // Test the input. Always call the trim() string method on user input as it
  // will strip off any leading or trailing spaces.
  if(!emailExpr.test(email.value.trim())){
     // Bad email.
     valid = false;
     alert("Bad email");
  }

  // Test to see if the email is good and the mobile is bad
  if(valid && !mobNumExpr.test(mobNum.value.trim())){
     valid = false;
     alert("Bad mobile number");
  }

  // If something has set the form to be invalid....
  if(!valid){
     evt.preventDefault();  // Cancel the event (don't submit the form)
     evt.stopPropagation(); // Prevent the event from bubbling
  }

}</code>```

<form action="#" method="post">

      <input type="text" class="form-control"
             placeholder="Email ID" id="emailid" name="Email"  maxlength="70">

      <input type="text" class="form-control"
             placeholder="Mobile Number" id="mobNo" name="number" maxlength="14">

     <input type="submit" value="Submit"><input type="reset">

</form>```

Finally, no matter how you implement your client-side validation, you must always remember that it can be easily circumvented by anyone wishing to bypass it, so you should always repeat the validations on the server-side before it accepts the data.

Title: unable to validate email and number

Body:
I need help because I have added the following javascript(mentioned below in code) to my form and I am passing ID to js, but unable to validate it.

Javascript Code

function validateForm() {
    var x = document.getElementById('emailid').value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    var txt = document.getElementById('mobNo');
    var filter = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;
    var test_bool = filter.test(txt.value);
    if (test_bool == false) {
        alert('Please enter valid Mobile Number ');
        txt.focus();
        return false;
    }
}

HTML

    <input type="email" class="form-control" value="" placeholder="Email ID" id="emailid" name="Email" required="required" maxlength="70" />

    <input type="text" class="form-control" value="" placeholder="Mobile Number" id="mobNo" name="number" required="required" maxlength="14" />

Body:
There's a lot wrong with your code...

First, your HTML is not valid because your label elements have values for the for attributes that do not point to the id attribute values of the elements they are "for".

Additionally (and perhaps you do have it but aren't showing it in your question), you do not have a form element that contains all your inputs.

Now, since you are using input type=email and required in your HTML, you will get validation automatically. If you simply add the pattern attribute to your mobile phone filed, you won't need any JavaScript to validate as this is built-in. Using the built-in email field and then writing email validation code that validates the same way makes no sense.

<form action="#" method="post">
       <div class="form-group">
          <!-- There's no need to set value="" on a text field when you want it to start blank -->
          <!-- When you use the HTML validation fields and attributes, you don't need JavaScript
               unless you want to implement custom validation.      -->
          <input type="email" required class="form-control"
                 placeholder="Email ID" id="emailid" name="Email"  maxlength="70">
          <!-- The "for" attribute of a label must point to the ID of the element it is for -->
          <label class="input-field-icon icon-email" for="emailid"></label>
       </div>
       <div class="form-group">
          <input type="text" class="form-control" pattern="([0]|\+91|\+91-|\+91\s)?\d{10}" required
                 placeholder="Mobile Number" id="mobNo" name="number" maxlength="14">
          <!-- You had a copy of the email label down here -->
          <label class="input-field-icon" for="mobNo"></label>
       </div>
       <div>
         <input type="submit" value="Submit"><input type="reset">
       </div>
</form>

If you do want to write your own validation code, then you would go back to using non-validation form fields or HTML5 custom validations. Assuming that were the case...

Your validation function is not ever being called. It needs to be "wired" up to an event, so that when the event occurs, the function will automatically be invoked. That is called a "callback function". Since you are working with a form (or should be), the form will have a submit event and this is the appropriate time to do form validation.

Additionally, your email validation logic is flawed (an email address of me.you@ would be allowed for example).

Here's what the code should look like. I have removed the HTML validation so that you can see the JavaScript doing its job.

Please read the comments in the code for explanations on what is being done and why:

// Don't mix HTML and JavaScript (as others have suggested). Keep them separate

// All this code should be placed inside of a <script> element and the entire thing
// should be placed just before the end of the body element (</body>) so that by the
// time this code runs all the HTML will have been read into memory.

// Get a reference to the elements you'll need to work with
var frm = document.querySelector("form");
var email = document.getElementById("emailid");
var mobNum = document.getElementById("mobNo");

// Set the form up to have a submit event callback function
// This is what makes it so that when your form is submitted,
// your validation function runs.
frm.addEventListener("submit", validateForm);

// This function will now be automatically called when the form is submitted
// All event handling functions will automatically be passed a reference to
// the event they are responding to and that reference will be passed as the
// first argument to the funciton (we are receiving that reference with the
// "evt" argument here).
function validateForm(evt) {

  // validate the email input with a regular expression
  var emailExpr = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  // validate the phone number with a regular expression
  var mobNumExpr = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;

  // Assume the form is valid
  var valid = true;

  // Test the input. Always call the trim() string method on user input as it
  // will strip off any leading or trailing spaces.
  if(!emailExpr.test(email.value.trim())){
     // Bad email.
     valid = false;
     alert("Bad email");
  }

  // Test to see if the email is good and the mobile is bad
  if(valid && !mobNumExpr.test(mobNum.value.trim())){
     valid = false;
     alert("Bad mobile number");
  }

  // If something has set the form to be invalid....
  if(!valid){
     evt.preventDefault();  // Cancel the event (don't submit the form)
     evt.stopPropagation(); // Prevent the event from bubbling
  }

}

<form action="#" method="post">
   <div class="form-group">
      <!-- There's no need to set value="" on a text field when you want it to start blank -->
      <input type="text" class="form-control"
             placeholder="Email ID" id="emailid" name="Email"  maxlength="70">
      <!-- The "for" attribute of a label must point to the ID of the element it is for -->
      <label class="input-field-icon icon-email" for="emailid"></label>
   </div>
   <div class="form-group">
      <input type="text" class="form-control"
             placeholder="Mobile Number" id="mobNo" name="number" maxlength="14">
      <!-- You had a copy of the email label down here -->
      <label class="input-field-icon" for="mobNo"></label>
   </div>
   <div>
     <input type="submit" value="Submit"><input type="reset">
   </div>
</form>

Finally, no matter how you implement your client-side validation, you must always remember that it can be easily circumvented by anyone wishing to bypass it, so you should always repeat the validations on the server-side before it accepts the data.


问:
how to access the response value outside done function
```<code>var response = [];

    $.ajax({
    method: "GET",
    url: "{{url('api/xyz')}}",
    })
    .done(function( res ) {
        var rr;
        if(res.status == 'success'){
            rr = res.data;
            response.push(rr);
        }
    });

    console.log(response);
</code>```

Not getting exact response

getting

Array[0]length: 0__proto__: Array[0]concat: concat()constructor: Array()copyWithin: copyWithin()entries: entries()every: every()fill: fill()filter: filter()find: find()findIndex: findIndex()forEach: forEach()includes: includes()indexOf: indexOf()join: join()keys: keys()lastIndexOf: lastIndexOf()length: 0map: map()pop: pop()push: push()reduce: reduce()reduceRight: reduceRight()reverse: reverse()shift: shift()slice: slice()some: some()sort: sort()splice: splice()toLocaleString: toLocaleString()toString: toString()unshift: unshift()Symbol(Symbol.iterator): values()Symbol(Symbol.unscopables): Object__proto__: Object

答:
Ajax is asynchronous call , your console.log executed before you push the data , try console.log after you push into array</p>

```<code>var response = [];

    $.ajax({
    method: "GET",
    url: "{{url('api/xyz')}}",
    })
    .done(function( res ) {
        var rr;
        if(res.status == 'success'){
            rr = res.data;
            response.push(rr);
           console.log(response);
        }
    });
</code>```

Body:
var response = [];

    $.ajax({
    method: "GET",
    url: "{{url('api/xyz')}}",
    })
    .done(function( res ) {
        var rr;
        if(res.status == 'success'){
            rr = res.data;
            response.push(rr);
        }
    });

    console.log(response);

Not getting exact response

getting

Array[0]length: 0__proto__: Array[0]concat: concat()constructor: Array()copyWithin: copyWithin()entries: entries()every: every()fill: fill()filter: filter()find: find()findIndex: findIndex()forEach: forEach()includes: includes()indexOf: indexOf()join: join()keys: keys()lastIndexOf: lastIndexOf()length: 0map: map()pop: pop()push: push()reduce: reduce()reduceRight: reduceRight()reverse: reverse()shift: shift()slice: slice()some: some()sort: sort()splice: splice()toLocaleString: toLocaleString()toString: toString()unshift: unshift()Symbol(Symbol.iterator): values()Symbol(Symbol.unscopables): Object__proto__: Object

Body:
Ajax is asynchronous call , your console.log executed before you push the data , try console.log after you push into array

var response = [];

    $.ajax({
    method: "GET",
    url: "{{url('api/xyz')}}",
    })
    .done(function( res ) {
        var rr;
        if(res.status == 'success'){
            rr = res.data;
            response.push(rr);
           console.log(response);
        }
    });


问:
mingw64 nothing to be done for file / no rule to make target
I am trying to build a 64 bit version of a library using mingw-w64. here is the makefile i am trying to make, with these rules:

```<code>mingw32-make.exe -t ...\makefiles\makefile-mingw-sdl2 all
</code>```

And here is the rule for all:

```<code>all : debug release

release : libtcod-mingw.dll libtcod-gui-mingw.dll upx

debug : libtcod-mingw-debug.dll libtcod-gui-mingw-debug.dll
</code>```

I get two messages:

Nothing to be done for ...\makefile.mingw-sdl2.

*** No rule to make target 'all'. Stop.

Never worked around with makefiles so I haven't the slightest idea what's wrong with it.

答:
The option to use a different Makefile is -f, not -t.

-t means only "touch" everything to mark it as updated. You'll always never want this option.

Because -t doesn't have an argument, your ..\makefiles\makefile-mingw-sdl2 is interpreted as a target to be built, and as this exists and make doesn't know any prerequisites for it, there's nothing to do to build it, and make is telling you this with the message

Nothing to be done for ...\makefile.mingw-sdl2.

For the second message: Either there is no Makefile in your current directory or it doesn't contain a rule for all.

What you want is mingw32-make.exe -f ..\makefiles\makefile-mingw-sdl2

Next time you run into a problem, I suggest to at least read the output of mingw32-make --help. For anything else, GNU make also has a good online manual.

Body:
I am trying to build a 64 bit version of a library using mingw-w64. here is the makefile i am trying to make, with these rules:

mingw32-make.exe -t ...\makefiles\makefile-mingw-sdl2 all

And here is the rule for all:

all : debug release

release : libtcod-mingw.dll libtcod-gui-mingw.dll upx

debug : libtcod-mingw-debug.dll libtcod-gui-mingw-debug.dll

I get two messages:

Nothing to be done for ...\makefile.mingw-sdl2.

*** No rule to make target 'all'. Stop.

Never worked around with makefiles so I haven't the slightest idea what's wrong with it.


问:
Cannot Login in SQL Server Management Studio, Error: 233
I changed authentication mode from "Windows Authentication" to "Windows Authentication and SQL Server Authentication" and also enabled "sa" user and changed it's password and defined another user.

But now when I want to login in SQL Server Management Studio, it will show me this error:

I restarted SQL services

I restarted windows

I changed authentication mode from windows registry (because I couldn't login and change it in Properties)

答: You should login with windows auth. again and you should change sa user permission in roles as system admin. at the end of this process you should restart again sql service in services.</p>


问:
Angular 2 and Bootstrap 3. Different integration approaches
I'm trying to integrate Bootstrap 3 into my Angular 2 project.
I have two choices:

Use npm install bootstrap --save command and install Bootstrap 3
to my project.

Install angular bootstrap using npm install ngx-bootstrap --save,
which is based on Angular and there won't be any jquery dependancies.

What is the main difference between these two approaches. Which one is better for single page applications?

答:
ngx-bootstrap comes with pre-defined components out of the box which can be used directly in your angular app
while bootstrap is the pure library where you need to build the components by yourself

If you like re-inventing the wheel (aka being flexible and BYO) it is better to use bootstrap, but if you like pre-made components which are quite easy to use (still you can participate and create missing or custom components by yourself)

Hint: ngx-bootstrap for Bootstrap 4 is not feature complete yet, so there are couple of components missing. Not sure about Bootstrap 3 coverage. Still we have chosen to go with ngx-bootstrap as it saved us some time.


问:
C++ methods for network protocol parsing
I am looking for a good strategy people use in C++/C to parse complex binary network protocols (such as DNS). Any tips and articles would be great.</p>

答:
Google Protocol Buffers appears to support the types that Python struct() can handle.  It supports Python too.

Welcome to the developer documentation
  for protocol buffers – a
  language-neutral, platform-neutral,
  extensible way of serializing
  structured data for use in
  communications protocols, data
  storage, and more.


问:
Notification when database gets a new entry on VB .net
Is there a way to display a notification everytime a entry gets added to a mysql database? For each entry there is a status column and 1 is the default value which is a New entry and i want to display a notification every time the database gets a new entry so I can go see on the site we have setup(each entry is a servicedesk ticket) to review it. I'm using VB.net
Should also be of concern i have the showing the notification part worked out</p>

答:
For anyone curious, i got it working myself, the code i used was

```<code>Dim curCount = data_set2.Tables(0).Rows(0).Item(0) 'gets the current count

If curCount > prevCount Then 'if there are more than the previous count, that means a entry was added
    NotifyIcon1.Icon = SystemIcons.Exclamation
    NotifyIcon1.BalloonTipText =
    data_set.Tables(0).Rows(0).Item(0)NotifyIcon1.ShowBalloonTip(10000)
End If
prevCount = data_set2.Tables(0).Rows(0).Item(0) 'sets the previous count to the current one for checking
</code>```

This is all on a timer and it has worked for me while testing stuff out, it might be a bit bad now but its the first piece that worked.

Body:
For anyone curious, i got it working myself, the code i used was

Dim curCount = data_set2.Tables(0).Rows(0).Item(0) 'gets the current count

If curCount > prevCount Then 'if there are more than the previous count, that means a entry was added
    NotifyIcon1.Icon = SystemIcons.Exclamation
    NotifyIcon1.BalloonTipText =
    data_set.Tables(0).Rows(0).Item(0)NotifyIcon1.ShowBalloonTip(10000)
End If
prevCount = data_set2.Tables(0).Rows(0).Item(0) 'sets the previous count to the current one for checking

This is all on a timer and it has worked for me while testing stuff out, it might be a bit bad now but its the first piece that worked.


问:
C# Asynchronous Chat Server
I'm trying to build an Asynchronous Chat Server and this is what I got so far:

Server

```<code>using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);

public AsynchronousSocketListener()
{
}

public static void StartListening()
{
    byte[] bytes = new Byte[1024];
    IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true)
        {
            allDone.Reset();
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
            allDone.WaitOne();
        }

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();

}

public static void AcceptCallback(IAsyncResult ar)
{
    allDone.Set();
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}

public static void ReadCallback(IAsyncResult ar)
{
    String content = String.Empty;
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    int bytesRead = handler.EndReceive(ar);

    if (bytesRead > 0)
    {
        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
        content = state.sb.ToString();
        if (content.IndexOf("<EOF>") > -1)
        {
            Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);
            Send(handler, content);
        }
        else
        {
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
        }
    }
}

private static void Send(Socket handler, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket handler = (Socket)ar.AsyncState;
        int bytesSent = handler.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to client.", bytesSent);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartListening();
    return 0;
}
}
</code>```

Client

```<code>using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 256;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    private const int port = 11000;
    private static ManualResetEvent connectDone =new ManualResetEvent(false);
    private static ManualResetEvent sendDone =new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =new ManualResetEvent(false);
    private static String response = String.Empty;
    static String username = "";
    static int a = 1;

private static void StartClient()
{
    try
    {
        Console.WriteLine("Username: ");
        username = Console.ReadLine();

        while (a == 1)
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            Console.WriteLine("Receiver: ");
            String receiver = Console.ReadLine();
            Console.WriteLine("Message: ");
            String message = Console.ReadLine();

            String Message = username + "[" + receiver + "[" + message + "<EOF>";
            Send(client, Message);
            sendDone.WaitOne();
            Receive(client);
            receiveDone.WaitOne();
            Console.WriteLine("Response received : {0}", response);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ConnectCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        client.EndConnect(ar);
        connectDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Receive(Socket client)
{
    try
    {
        StateObject state = new StateObject();
        state.workSocket = client;
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;
        int bytesRead = client.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
            }
            receiveDone.Set();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Send(Socket client, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    client.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), client);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        int bytesSent = client.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to server.", bytesSent);
        sendDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartClient();
    return 0;
}
}
</code>```

I'm able to send messages to the server and get back an answer, but the connection is cut every time and I have to reconnect it and like this I wouldn't be able to get messages after I send one. I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Furthermore I'm looking for a way to send messages from one client to another one and to send a message to all clients, who are connected to the server.

Another Question I have, how can I set up multiple ports and let the server listen to all ports? I wanted to open one port for the login and one port for the messages.

答:
I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.

Closing the connection could be done by adding a disconnect call after the loop: client.Disconnect(false). After some exit condition you simply quit the loop.

It would be preferable to create the client in a using statement though, this way it will be disposed automatically.

Title: C# Asynchronous Chat Server

Body:
I'm trying to build an Asynchronous Chat Server and this is what I got so far:

Server

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);

public AsynchronousSocketListener()
{
}

public static void StartListening()
{
    byte[] bytes = new Byte[1024];
    IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true)
        {
            allDone.Reset();
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
            allDone.WaitOne();
        }

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();

}

public static void AcceptCallback(IAsyncResult ar)
{
    allDone.Set();
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}

public static void ReadCallback(IAsyncResult ar)
{
    String content = String.Empty;
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    int bytesRead = handler.EndReceive(ar);

    if (bytesRead > 0)
    {
        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
        content = state.sb.ToString();
        if (content.IndexOf("<EOF>") > -1)
        {
            Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);
            Send(handler, content);
        }
        else
        {
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
        }
    }
}

private static void Send(Socket handler, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket handler = (Socket)ar.AsyncState;
        int bytesSent = handler.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to client.", bytesSent);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartListening();
    return 0;
}
}

Client

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 256;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    private const int port = 11000;
    private static ManualResetEvent connectDone =new ManualResetEvent(false);
    private static ManualResetEvent sendDone =new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =new ManualResetEvent(false);
    private static String response = String.Empty;
    static String username = "";
    static int a = 1;

private static void StartClient()
{
    try
    {
        Console.WriteLine("Username: ");
        username = Console.ReadLine();

        while (a == 1)
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            Console.WriteLine("Receiver: ");
            String receiver = Console.ReadLine();
            Console.WriteLine("Message: ");
            String message = Console.ReadLine();

            String Message = username + "[" + receiver + "[" + message + "<EOF>";
            Send(client, Message);
            sendDone.WaitOne();
            Receive(client);
            receiveDone.WaitOne();
            Console.WriteLine("Response received : {0}", response);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ConnectCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        client.EndConnect(ar);
        connectDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Receive(Socket client)
{
    try
    {
        StateObject state = new StateObject();
        state.workSocket = client;
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;
        int bytesRead = client.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
            }
            receiveDone.Set();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Send(Socket client, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    client.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), client);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        int bytesSent = client.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to server.", bytesSent);
        sendDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartClient();
    return 0;
}
}

I'm able to send messages to the server and get back an answer, but the connection is cut every time and I have to reconnect it and like this I wouldn't be able to get messages after I send one. I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Furthermore I'm looking for a way to send messages from one client to another one and to send a message to all clients, who are connected to the server.

Another Question I have, how can I set up multiple ports and let the server listen to all ports? I wanted to open one port for the login and one port for the messages.


问:
IBM Watson vs Amazon Lex (chatbot)
Okay so i'm a newbie and i am interning for a software company. We need to build a chatbot using Watson or Lex. But I'm not sure which one to use. Also does Lex have an engine to support automated email conversations too? </p>

答:
I'm not an IBMer ;-) but would also recommend the Watson Conversation service. It's easy to build a chatbot which you can then connect to via RESTful api to make integration with your website / apps relatively easy.

AWS Lex involves using two services - Lex and Lambda, which are both great and useful, but overall it's not as simple a process.

I also think the IBM code examples and API reference are more developer-friendly.

Title: IBM Watson vs Amazon Lex (chatbot)


问:
How to display hidden data of one div to another div?
I am working on a project where I came across where when I click plus sign the data will hide and the appear in the div next to it.
here is the code:

```<code><fieldset class="col-md-4" >
    <legend>Services</legend>
    <div class="col-md-12" >
        <?php
            $id = 0;
            foreach ($servicesname as $val) {
            $id++;
        ?>
        <div class="col-md-12" style="font-size: 16px;" id="itemservices<?php echo $id ?>">
            <span style="float:left;" ><?php echo $val[0]['servicename']; ?></span>
            <a  style="float:right;" href onclick="return addSrvToCart('itemservices<?php echo $id ?>')" >
                <strong>&#8377 <?php echo $val[0]['amount']; ?></strong>
                <span class="glyphicon glyphicon-plus-sign" id="id_<?php echo $id; ?>"></span>
            </a>
        </div>

        <?php } ?>
    </div>
</fieldset>
</code>```

and the code for next div:

```<code><fieldset class="col-md-4" >
    <legend>Cart</legend>
    <div style="list-style:none;" class="no-left-padding" id="cart">
        <div class="col-md-12" >

        </div>
    </div>

    <div class="col-sm-12 no-right-padding" style="background-color:#f3f0f0; padding-top:6px; border:1px solid#ccc">
        <label class="pull-right">/*what should i write here to show the sum */: ₨ </label>
    </div>
    <button style="margin-top:10px;" class="btn btn-primary btn-sm pull-right" onclick="bookNowAfterFilter()">Book Now</button>
</fieldset>
</code>```

And This the Jquery code:

```<code><script>
 function addSrvToCart(elem){
    alert($('#' + elem).html());
    $('#' + elem).hide();

   //return false;
  //what should i write here the show that hidden div
  document.getElementById('summery);
  return false;
 }
</script>
</code>```

This is the picture and I want to display the data in the Cart div and show the amount

答:
You need to change in both HTML and Script to achieve the result

Try like this

HTML

```<code><fieldset class="col-md-4" >
    <legend>Services</legend>
    <div class="col-md-12" >
        <?php
            $id = 0;
            foreach ($servicesname as $val) {
            $id++;
        ?>
        <div class="col-md-12" style="font-size: 16px;" id="itemservices<?php echo $id ?>">
            <span style="float:left;" ><?php echo $val[0]['servicename']; ?></span>
            <a  style="float:right;" onclick=" addSrvToCart('itemservices<?php echo $id ?>')" >
                &#8377<strong> <?php echo $val[0]['amount']; ?></strong>
                <span class="glyphicon glyphicon-plus-sign" id="id_<?php echo $id; ?>"></span>
            </a>
        </div>

        <?php } ?>
    </div>
</fieldset>
</code>```

and the code for next div:

```<code><fieldset class="col-md-4" >
    <legend>Cart</legend>
    <div style="list-style:none;" class="no-left-padding">
        <div class="col-md-12"  id="cart" >

        </div>
    </div>

    <div class="col-sm-12 no-right-padding pull-right"  style="background-color:#f3f0f0; padding-top:6px; border:1px solid#ccc">
            Total: ₨ <label class="" id="sumAmount">0</label>
        </div>
    <button style="margin-top:10px;" class="btn btn-primary btn-sm pull-right" onclick="bookNowAfterFilter()">Book Now</button>
</fieldset>
</code>```

Script:

```<code>function addSrvToCart(elem){
    var div=$('#' + elem);
    div.hide();
    $('#cart').append(div.html());
    var total = parseInt(div.find('strong').html()) + parseInt($('#sumAmount').html());
    $('#sumAmount').html(total);
}
</code>```

It will produce output as

I think it will help you.

Body:
I am working on a project where I came across where when I click plus sign the data will hide and the appear in the div next to it.
here is the code:

<fieldset class="col-md-4" >
    <legend>Services</legend>

        <?php
            $id = 0;
            foreach ($servicesname as $val) {
            $id++;
        ?>
        <div class="col-md-12" style="font-size: 16px;" id="itemservices<?php echo $id ?>">
            <?php echo $val[0]['servicename']; ?>
            <a  style="float:right;" href onclick="return addSrvToCart('itemservices<?php echo $id ?>')" >
                &#8377 <?php echo $val[0]['amount']; ?>
                <span class="glyphicon glyphicon-plus-sign" id="id_<?php echo $id; ?>">

        <?php } ?>

</fieldset>

and the code for next div:

<fieldset class="col-md-4" >
    <legend>Cart</legend>

        /*what should i write here to show the sum */: ₨

    <button style="margin-top:10px;" class="btn btn-primary btn-sm pull-right" onclick="bookNowAfterFilter()">Book Now</button>
</fieldset>

And This the Jquery code:

This is the picture and I want to display the data in the Cart div and show the amount

Body:
You need to change in both HTML and Script to achieve the result

Try like this

HTML

<fieldset class="col-md-4" >
    <legend>Services</legend>
    <div class="col-md-12" >
        <?php
            $id = 0;
            foreach ($servicesname as $val) {
            $id++;
        ?>
        <div class="col-md-12" style="font-size: 16px;" id="itemservices<?php echo $id ?>">
            <span style="float:left;" ><?php echo $val[0]['servicename']; ?></span>
            <a  style="float:right;" onclick=" addSrvToCart('itemservices<?php echo $id ?>')" >
                &#8377<strong> <?php echo $val[0]['amount']; ?></strong>
                <span class="glyphicon glyphicon-plus-sign" id="id_<?php echo $id; ?>"></span>
            </a>
        </div>

        <?php } ?>
    </div>
</fieldset>

and the code for next div:

<fieldset class="col-md-4" >
    <legend>Cart</legend>
    <div style="list-style:none;" class="no-left-padding">
        <div class="col-md-12"  id="cart" >

        </div>
    </div>

    <div class="col-sm-12 no-right-padding pull-right"  style="background-color:#f3f0f0; padding-top:6px; border:1px solid#ccc">
            Total: ₨&nbsp;<label class="" id="sumAmount">0</label>
        </div>
    <button style="margin-top:10px;" class="btn btn-primary btn-sm pull-right" onclick="bookNowAfterFilter()">Book Now</button>
</fieldset>

Script:

function addSrvToCart(elem){
    var div=$('#' + elem);
    div.hide();
    $('#cart').append(div.html());
    var total = parseInt(div.find('strong').html()) + parseInt($('#sumAmount').html());
    $('#sumAmount').html(total);
}

It will produce output as

I think it will help you.


问:
Choosing specific python interpreter in the shell
I've been developing a set of scripts in PyCharm using C:/Python27/python.exe interpreter...

I'm creating a batch file and then running all of the scripts through this file from the cmd shell however the shell is not recognizing most modules because it is using the wrong interpreter (path for anaconda instead)...

How do I change the shell to use the C:/Python27/python.exe interpreter as default all the time instead?

I've tried looking this up but it all points to just adding the interpreter path, which I have... but the shell still uses the anaconda interpreter.

Any help appreicated

答:
Found a solution to my problem...

I needed to use:

set path=%path%;C:\Python27

This switched interpreter.

Cheers


问:
In a nested if loop, how to return true for multiple matching conditions?
In the below program, even though all the if conditions are matching, it returns true just once. How do i make it return true and print as many times as the conditions match?</p>

```<code>lotto_numbers = [1,1,1]
fireball_number = 1
user_input1 = user_input2 = user_input3 = 1

def fbcheck():
    if lotto_numbers == [user_input1,user_input2,fireball_number]:
        return True
    elif lotto_numbers == [fireball_number, user_input2, user_input3]:
        return True
    elif lotto_numbers == [user_input1, fireball_number, user_input3]:
        return True
    else:
        return False

if (fbcheck() == True):
    print ('you won')
</code>```

答:
You can use all:

```<code>def fbcheck():
    user_data = [user_input1,user_input2,fireball_number]

    lotto_numbers = [1,1,1]

    print([a==b for a, b in zip(lotto_numbers, user_data)])

    return all(a==b for a, b in zip(lotto_numbers, user_data))

print(fbcheck())
</code>```

Output:

```<code>[True, True, True]

True
</code>```

Body:
In the below program, even though all the if conditions are matching, it returns true just once. How do i make it return true and print as many times as the conditions match?

lotto_numbers = [1,1,1]
fireball_number = 1
user_input1 = user_input2 = user_input3 = 1

def fbcheck():
    if lotto_numbers == [user_input1,user_input2,fireball_number]:
        return True
    elif lotto_numbers == [fireball_number, user_input2, user_input3]:
        return True
    elif lotto_numbers == [user_input1, fireball_number, user_input3]:
        return True
    else:
        return False

if (fbcheck() == True):
    print ('you won')

Body:
You can use all:

def fbcheck():
    user_data = [user_input1,user_input2,fireball_number]

    lotto_numbers = [1,1,1]

    print([a==b for a, b in zip(lotto_numbers, user_data)])

    return all(a==b for a, b in zip(lotto_numbers, user_data))

print(fbcheck())

Output:

[True, True, True]

True


问:
Get unique value from an array php
I want to display only unique strings and I have this code:

```<code>$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    $array = array_unique($array);
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
    }
}
</code>```

I have put an array_unique like this:

```<code>$array = array_unique($array);
</code>```

But it returns this:

```<code>word-word
word
word2
word3
word-word
</code>```

It doesn't print only unique values. What is wrong?

答:
Explode your string.

Trim outer spaces from each element.

Replace inner spaces with hyphen in each element.

Only keep non-empty elements.

Only keep unique elements (using double array_flip).

Display results.

Code: (Demo)

```<code>while($rez=$result->fetch_assoc()) {
    $array=explode(',',$rez['tags']);       // split into elements
    foreach($array as $v){
        $v=str_replace(" ","-",trim($v));   // remove outer spaces, replace inner spaces
        if($v){$clean[]=$v;}                // retain non-empty values
    }
    $clean=array_flip(array_flip($clean));  // double flip is faster than array_unique
    foreach($clean as $v){
        echo "<a href=\"http://example.com/$v\">$v</a><br>";
    }
}
</code>```

Alternatively, you could do all of the value and html prep in the first foreach loop and then use implode to display the batch.  This will remove the potentially unnecessary trailing
 from final element:

Code:

```<code>$rez['tags']=' ,  word , word-word, word2 , word word, word3,';
$array=explode(',',$rez['tags']);       // split into elements
foreach($array as $v){
    $v=str_replace(" ","-",trim($v));   // remove outer spaces, replace inner spaces
    if($v){
        $clean[]="<a href=\"http://example.com/$v\">$v</a>";  // prep non-empty values for display
    }
}
echo implode("<br>",array_unique($clean));
</code>```

Output:

```<code><a href="http://example.com/word">word</a><br>
<a href="http://example.com/word-word">word-word</a><br>
<a href="http://example.com/word2">word2</a><br>
<a href="http://example.com/word3">word3</a>
</code>```

Title: Get unique value from an array php

Body:
I want to display only unique strings and I have this code:

$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    $array = array_unique($array);
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        echo '' . $value . '
';
    }
}

I have put an array_unique like this:

$array = array_unique($array);

But it returns this:

word-word
word
word2
word3
word-word

It doesn't print only unique values. What is wrong?

Body:
Explode your string.

Trim outer spaces from each element.

Replace inner spaces with hyphen in each element.

Only keep non-empty elements.

Only keep unique elements (using double array_flip).

Display results.

Code: (Demo)

while($rez=$result->fetch_assoc()) {
    $array=explode(',',$rez['tags']);       // split into elements
    foreach($array as $v){
        $v=str_replace(" ","-",trim($v));   // remove outer spaces, replace inner spaces
        if($v){$clean[]=$v;}                // retain non-empty values
    }
    $clean=array_flip(array_flip($clean));  // double flip is faster than array_unique
    foreach($clean as $v){
        echo "<a href=\"http://example.com/$v\">$v</a><br>";
    }
}

Alternatively, you could do all of the value and html prep in the first foreach loop and then use implode to display the batch.  This will remove the potentially unnecessary trailing
 from final element:

Code:

$rez['tags']=' ,  word , word-word, word2 , word word, word3,';
$array=explode(',',$rez['tags']);       // split into elements
foreach($array as $v){
    $v=str_replace(" ","-",trim($v));   // remove outer spaces, replace inner spaces
    if($v){
        $clean[]="<a href=\"http://example.com/$v\">$v</a>";  // prep non-empty values for display
    }
}
echo implode("<br>",array_unique($clean));

Output:

<a href="http://example.com/word">word</a><br>
<a href="http://example.com/word-word">word-word</a><br>
<a href="http://example.com/word2">word2</a><br>
<a href="http://example.com/word3">word3</a>


问:
How to securely store secret keys on react-native client side?
Let's say i'm building a react-native app with firebase, which assumes having secret key in app. Is it possible for someone to steal the key? If so, then how do i protect it?</p>

答:
There's no 100% secure way to store anything secret on the device because you have no control over access to the source. The only way to guarantee security of your keys is to never have them on the device in the first place.

Any solution you find will have a flaw, illustrated quite nicely by this article by Michael Ramirez

You need to strike a balance of how secure you really need those keys to be.

For example on Android we store some of our keys we care less about for Google and other APIs in a res/values/secrets.xml string file, which is not committed to version control. It's easy for someone to strings out_app.api, but we've already decided to care less about securing those keys.

```<code><resources>
    <string name="google_api_key">OurApiKey</string>
</resources>
</code>```

If you're working with ReactNative on Android & depending on the types of key you want to store, you could make use of the Android Keystore System using the Keystore API
however I don't think this will work for storing Firebase keys.

Body:
There's no 100% secure way to store anything secret on the device because you have no control over access to the source. The only way to guarantee security of your keys is to never have them on the device in the first place.

Any solution you find will have a flaw, illustrated quite nicely by this article by Michael Ramirez

You need to strike a balance of how secure you really need those keys to be.

For example on Android we store some of our keys we care less about for Google and other APIs in a res/values/secrets.xml string file, which is not committed to version control. It's easy for someone to strings out_app.api, but we've already decided to care less about securing those keys.

<resources>
    <string name="google_api_key">OurApiKey</string>
</resources>

If you're working with ReactNative on Android & depending on the types of key you want to store, you could make use of the Android Keystore System using the Keystore API
however I don't think this will work for storing Firebase keys.


问:
jQuery not working when I load dynamic component in Angular
I have implemented dynamic components in Angular and whenever a dynamic component is loaded its corresponding jQuery is not working. Same jQuery script is working elsewhere.

This is where my dynamic component loads:

```<code><div class="listing-table-outer" [@myAwesomeAnimation]='state'>
      <app-dynamic-question [componentData]="componentData"></app-dynamic-question>
    </div>
</code>```

Below html will be loaded dynamically.

```<code><div class="panel panel-default " >
    <div class="panel-body" >
     <h1>{{textLabel}}</h1>
        <p>{{textHeader}}</p>

        <div class="form-inline display-one" role="form">
            <input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="">
        </div>

        <div class="learn-more magtop10">
            <a> <i class=" glyphicon glyphicon-play"></i> Learn More</a>
        </div>
        <div class="display_advance">
            <div class="well">
                <p>{{textFooter}}</p>
            </div>
        </div>
        <div class="bs-component">
            <a href="#" class="btn panel-theme-clearbutton btn-lg" *ngIf="this.showButton[0].txt_button == 'Clear'">Clear</a>
            <a href="#" class="btn panel-theme-clearbutton btn-lg" *ngIf="this.showButton[1].txt_button == 'Skip'">Skip</a>
            <a href="#" class="btn panel-theme-button btn-lg" *ngIf="this.showButton[2].txt_button == 'Continue'">Continue</a>
        </div>
    </div>
</div>
</code>```

I have written this script

```<code>$(document).ready(function(){
$('.learn-more').click(function() {

    $('.display_advance').slideToggle('1000');
    $("i", this).toggleClass(" glyphicon-play glyphicon-triangle-bottom");
});

});
</code>```

I have checked this script and it is working perfectly elsewhere.

Please let me know why this is happening.

答:
As you already stated yourself, the html is loaded dynamically. That means that this html is not yet there when $(document).ready(function() { ... }) is executed. So you're trying to add a click event to an element that doesn't exist at that moment.
For this exact situation there's a thing called event delegation.

Instead of doing

```<code>$('.learn-more').on('click', function() { ... });
</code>```

you would do

```<code>$(document).on('click', '.learn-more', function() { ... });
</code>```

This way any elements below document with class learn-more, now or in the future, will get this click event.

Body:
I have implemented dynamic components in Angular and whenever a dynamic component is loaded its corresponding jQuery is not working. Same jQuery script is working elsewhere.

This is where my dynamic component loads:

      <app-dynamic-question [componentData]="componentData"></app-dynamic-question>

Below html will be loaded dynamically.

{{textLabel}}

{{textHeader}}

            <input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="">

              Learn More

{{textFooter}}

            Clear
            Skip
            Continue

I have written this script

$(document).ready(function(){
$('.learn-more').click(function() {

    $('.display_advance').slideToggle('1000');
    $("i", this).toggleClass(" glyphicon-play glyphicon-triangle-bottom");
});

});

I have checked this script and it is working perfectly elsewhere.

Please let me know why this is happening.

Body:
As you already stated yourself, the html is loaded dynamically. That means that this html is not yet there when $(document).ready(function() { ... }) is executed. So you're trying to add a click event to an element that doesn't exist at that moment.
For this exact situation there's a thing called event delegation.

Instead of doing

$('.learn-more').on('click', function() { ... });

you would do

$(document).on('click', '.learn-more', function() { ... });

This way any elements below document with class learn-more, now or in the future, will get this click event.


问:
Hooking in .Net
I want to hook some function in .Net is there a way to do it?
I don’t mean windows hooking, I want to hook CLR function like when DataAdapter.Fill is called
Thanks,</p>

答:
Don't know if it's possible with .Net framework itself, but what you are looking for is called Aspect Oriented Programming. .Net versions works by modifying the IL code that Visual Studio generates during compilation.

Look here for more information: http://www.codeproject.com/KB/cs/UsingAOPInCSharp.aspx

Title: Hooking in .Net