问:
Inserting a dynamic number of rows into SQL Server
Is there a way to insert a dynamic number of rows from within sql server (.sql script) given the value of a look up, and setting one column for each insert?
I want to attach a row with the foreign key of every row in a different table.

For instance:

```<code>table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)

table 2:
2 hi you
3 hey ho
</code>```

Now say I wanted to add 2 rows to table 1, with the fk values from table 2 of 2 and 3.

So the final table would look like:

```<code>table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)
4 a a a a a 3-(fk)
5 a a a a a 2-(fk)
</code>```

With a programming language, this would be easy. Psuedo:
    For (rows in table 2) DO
        Insert into table 1 'a a a a a rows.id'

How could this be accomplished within sql server?

Edit:

For every row in table 2, get it's id, set it as the fk in a row for table 1, and insert it.

答:
Ok, someone came along and showed me a way to do this...

```<code>insert into table_one
select col1 = 'a',
   col2 = 'b',
   col3 = 'c',
   col4fk,
   col5 = 'k'
from table2
</code>```

It's only selecting col4fk from table 2, as long as it has the same name as the column in table 1.

OwnerDisplayName: Josh Smeaton

Body:
Is there a way to insert a dynamic number of rows from within sql server (.sql script) given the value of a look up, and setting one column for each insert?
I want to attach a row with the foreign key of every row in a different table.

For instance:

table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)

table 2:
2 hi you
3 hey ho

Now say I wanted to add 2 rows to table 1, with the fk values from table 2 of 2 and 3.

So the final table would look like:

table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)
4 a a a a a 3-(fk)
5 a a a a a 2-(fk)

With a programming language, this would be easy. Psuedo:
    For (rows in table 2) DO
        Insert into table 1 'a a a a a rows.id'

How could this be accomplished within sql server?

Edit:

For every row in table 2, get it's id, set it as the fk in a row for table 1, and insert it.

LastEditorDisplayName: Josh Smeaton

Body:
Ok, someone came along and showed me a way to do this...

insert into table_one
select col1 = 'a',
   col2 = 'b',
   col3 = 'c',
   col4fk,
   col5 = 'k'
from table2

It's only selecting col4fk from table 2, as long as it has the same name as the column in table 1.


来源: stackexchange

问:
What is the spec for formatting data in QR codes? I can not find it anywhere
I'm specifically asking if, and what, is the specification for formatting the text inside a QR code - not how to generate a code (which I can do).

I need to put hCard data into a QR code, however I don't know how to mark the QR code as VCF data (versus URL, text, etc) so the decoder knows what to do.

All the info I've seen online has to do with generating the QR code, not formatting the data inside.

答:
See http://www.denso-wave.com/qrcode/qrstandard-e.html
and http://www.denso-wave.com/qrcode/aboutqr-e.html

QR Code is a kind of 2-D
  (two-dimensional) symbology developed
  by Denso Wave (a division of Denso
  Corporation at the time) and released
  in 1994 with the primary aim of being
  a symbol that is easily interpreted by
  scanner equipment.
  ...
  QR Code is open in the sense that the
  specification of QR Code is disclosed
  and that the patent right owned by
  Denso Wave is not exercised.

from http://www.denso-wave.com/qrcode/qrstandard-e.html:

QR Code is established as an ISO (ISO/IEC18004) standard. QR Code
  specification can, therefore, be purchased from this organization.
   Please seach by inputting ISO No.18004 to "Search
  and ISO Catalogue".
  http://www.iso.ch/iso/en/prods-services/ISOstore/store.html

ContentLicense: CC BY-SA 3.0


问:
How to solve "Failed to parse content to map" error while creating index?
I am getting an error.

Error :

"{"error":{"root_cause":[{"type":"parse_exception","reason":"Failed to parse content to map"}],"type":"parse_exception","reason":"Failed to parse content to map","caused_by":{"type":"json_parse_exception","reason":"Unexpected character ('s' (code 115)): was expecting double-quote to start field name\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@38a4cd00; line: 2, column: 3]"}},"status":400}" error while trying to create index

Code :

```<code>{
  "settings" : {
        "number_of_shards" : 1,
        "number_of_replicas" : 1
    },
   "mappings": {
             "properties": {
        "anonymous": {"type": "boolean"},
        "content_text_form": {"type": "text"},
        "details": {"type": "text"},
        "language": {"type": "keyword"},
        "no_of_comments": {"type": "long"},
        "up_votes": {"type": "long"},
        "down_votes": {"type": "long"},
        "no_of_views": {"type": "long"},
        "no_of_impressions": {"type": "long"},
        "short_id": {"type": "keyword"},
        "no_of_reposts": {"type": "long"},
        "createdAt": {"type": "date"},
        "updatedAt": {"type": "date"},
        "re_post_date": {"type": "date"},
        "media_urls": {
                        "properties": {
                          "url": {"type": "keyword"},
                          "type": {"type": "keyword"},
                          "uploadedOn": {"type": "date"},
                          "description": {"type": "text"},
                          "thumbnail": {"type": "text"},
                          "file_type": {"type": "keyword"},
                          "dimensions": {
                            "properties": {
                              "type": {
                                "properties": {
                                  "height": {"type": "long"},
                                  "width": {"type": "long"},
                                  "aspect_ratio":{"type":"long"}
                                },
                              "required": {"type": "boolean"}
                              }
                            }}
                          }
                          },
      "tags": {"type": "keyword"},
         "tag_positions": {
                          "properties": {
                            "tag": {"type": "keyword"},
                            "tag_start": {"type": "long"},
                            "tag_end": {"type": "long"}}},
          "source": {
          "properties": {
            "title" : {"type": "text"},
            "description": {"type": "text"},
            "media_type": {"type": "text"},
            "url": {"type": "text"}
          }
        },
           "moderation": {
          "properties": {
            "done": {"type":"boolean"}
          }
        }
       }
     }
}
</code>```

答:
I am not sure which version of Elasticsearch you are using but I use 6.7 and here is the one that worked after two modifications

```<code>1) I added "_doc"
2) I moved `"required": { "type": "boolean"}`  to one curly below ... look at it and it will make sense
</code>```

Here is the mapping that worked for me

```<code>  PUT so_test6
   {
      "settings" : {
         "number_of_shards" : 1,
         "number_of_replicas" : 1
      },
    "mappings": {
        "_doc":{
         "properties": {
           "anonymous": {"type": "boolean"},
           "content_text_form": {"type": "text"},
           "details": {"type": "text"},
           "language": {"type": "keyword"},
           "no_of_comments": {"type": "long"},
           "up_votes": {"type": "long"},
           "down_votes": {"type": "long"},
           "no_of_views": {"type": "long"},
           "no_of_impressions": {"type": "long"},
           "short_id": {"type": "keyword"},
           "no_of_reposts": {"type": "long"},
           "createdAt": {"type": "date"},
           "updatedAt": {"type": "date"},
           "re_post_date": {"type": "date"},
           "media_urls": {
                    "properties": {
                      "url": {"type": "keyword"},
                      "type": {"type": "keyword"},
                      "uploadedOn": {"type": "date"},
                      "description": {"type": "text"},
                      "thumbnail": {"type": "text"},
                      "file_type": {"type": "keyword"},
                      "dimensions": {
                        "properties": {
                          "type": {
                            "properties": {
                              "height": {"type": "long"},
                              "width": {"type": "long"},
                              "aspect_ratio":{"type":"long"}
                            }

                          },
                          "required": {"type": "boolean"}
                        }}
                      }
                      },
         "tags": {"type": "keyword"},
          "tag_positions": {
                      "properties": {
                        "tag": {"type": "keyword"},
                        "tag_start": {"type": "long"},
                        "tag_end": {"type": "long"}}},
      "source": {
      "properties": {
        "title" : {"type": "text"},
        "description": {"type": "text"},
        "media_type": {"type": "text"},
        "url": {"type": "text"}
      }
    },
       "moderation": {
      "properties": {
        "done": {"type":"boolean"}
      }
    }
   }
  }
 }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting an error.

Error :

"{"error":{"root_cause":[{"type":"parse_exception","reason":"Failed to parse content to map"}],"type":"parse_exception","reason":"Failed to parse content to map","caused_by":{"type":"json_parse_exception","reason":"Unexpected character ('s' (code 115)): was expecting double-quote to start field name\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@38a4cd00; line: 2, column: 3]"}},"status":400}" error while trying to create index

Code :

{
  "settings" : {
        "number_of_shards" : 1,
        "number_of_replicas" : 1
    },
   "mappings": {
             "properties": {
        "anonymous": {"type": "boolean"},
        "content_text_form": {"type": "text"},
        "details": {"type": "text"},
        "language": {"type": "keyword"},
        "no_of_comments": {"type": "long"},
        "up_votes": {"type": "long"},
        "down_votes": {"type": "long"},
        "no_of_views": {"type": "long"},
        "no_of_impressions": {"type": "long"},
        "short_id": {"type": "keyword"},
        "no_of_reposts": {"type": "long"},
        "createdAt": {"type": "date"},
        "updatedAt": {"type": "date"},
        "re_post_date": {"type": "date"},
        "media_urls": {
                        "properties": {
                          "url": {"type": "keyword"},
                          "type": {"type": "keyword"},
                          "uploadedOn": {"type": "date"},
                          "description": {"type": "text"},
                          "thumbnail": {"type": "text"},
                          "file_type": {"type": "keyword"},
                          "dimensions": {
                            "properties": {
                              "type": {
                                "properties": {
                                  "height": {"type": "long"},
                                  "width": {"type": "long"},
                                  "aspect_ratio":{"type":"long"}
                                },
                              "required": {"type": "boolean"}
                              }
                            }}
                          }
                          },
      "tags": {"type": "keyword"},
         "tag_positions": {
                          "properties": {
                            "tag": {"type": "keyword"},
                            "tag_start": {"type": "long"},
                            "tag_end": {"type": "long"}}},
          "source": {
          "properties": {
            "title" : {"type": "text"},
            "description": {"type": "text"},
            "media_type": {"type": "text"},
            "url": {"type": "text"}
          }
        },
           "moderation": {
          "properties": {
            "done": {"type":"boolean"}
          }
        }
       }
     }
}

Body:
I am not sure which version of Elasticsearch you are using but I use 6.7 and here is the one that worked after two modifications

1) I added "_doc"
2) I moved `"required": { "type": "boolean"}`  to one curly below ... look at it and it will make sense

Here is the mapping that worked for me

  PUT so_test6
   {
      "settings" : {
         "number_of_shards" : 1,
         "number_of_replicas" : 1
      },
    "mappings": {
        "_doc":{
         "properties": {
           "anonymous": {"type": "boolean"},
           "content_text_form": {"type": "text"},
           "details": {"type": "text"},
           "language": {"type": "keyword"},
           "no_of_comments": {"type": "long"},
           "up_votes": {"type": "long"},
           "down_votes": {"type": "long"},
           "no_of_views": {"type": "long"},
           "no_of_impressions": {"type": "long"},
           "short_id": {"type": "keyword"},
           "no_of_reposts": {"type": "long"},
           "createdAt": {"type": "date"},
           "updatedAt": {"type": "date"},
           "re_post_date": {"type": "date"},
           "media_urls": {
                    "properties": {
                      "url": {"type": "keyword"},
                      "type": {"type": "keyword"},
                      "uploadedOn": {"type": "date"},
                      "description": {"type": "text"},
                      "thumbnail": {"type": "text"},
                      "file_type": {"type": "keyword"},
                      "dimensions": {
                        "properties": {
                          "type": {
                            "properties": {
                              "height": {"type": "long"},
                              "width": {"type": "long"},
                              "aspect_ratio":{"type":"long"}
                            }

                          },
                          "required": {"type": "boolean"}
                        }}
                      }
                      },
         "tags": {"type": "keyword"},
          "tag_positions": {
                      "properties": {
                        "tag": {"type": "keyword"},
                        "tag_start": {"type": "long"},
                        "tag_end": {"type": "long"}}},
      "source": {
      "properties": {
        "title" : {"type": "text"},
        "description": {"type": "text"},
        "media_type": {"type": "text"},
        "url": {"type": "text"}
      }
    },
       "moderation": {
      "properties": {
        "done": {"type":"boolean"}
      }
    }
   }
  }
 }
}


问:
PHP: How to detect direct requests of external visitors?
I would like to detect/prevent/forward direct requests of external visitors. Some scripts should only be displayed in a jQuery dialog.

My current code:

```<code><script>
$(".dialog").click(function() {
    // some code for validation
    // ...
    $("#dialog").load(this.href).dialog();
});
</script>

<a href="http://domain.de/path/to/form/" class="dialog">Open me in a dialog</a>
</code>```

That works fine BUT if I open this link in a new tab/window (e.g. by clicking the middle mouse-button), the form will be displayed "naked".

In this case I would like to forward the user to the refered page, e.g.:

```<code>if ($requester != $server) {
    header ("Location: " . $_SERVER["HTTP_REFERER"];
}
</code>```

How can I detect $requester and $server? I don't want to block every script or a whole directory!

Thanks in advance!

答:
I have those values coming in on a external request:

[HTTP_HOST] => 104.219.42.237

[HTTP_REFERER] => http:// someurl.com

So, my solution is :

```<code>if (strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== FALSE) {

    echo 'same origin/request';

} else {

   echo 'different origin/request';
}
</code>```

...

...

...

The Reason that previous solutions did not work !

In My case:
$_SERVER['HTTP_REFERER'] ==  'http:// someurl.com'

while
 $_SERVER["HTTP_HOST"] does not contains 'http' nor 'https'

So,

```<code>if($_SERVER['HTTP_REFERER']!=$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"])
</code>```

won't match

The other answer

```<code>if( $_SERVER['REMOTE_ADDR'] == $your_Server_IP_Address)
</code>```

will not work on localhost

Body:
I would like to detect/prevent/forward direct requests of external visitors. Some scripts should only be displayed in a jQuery dialog.

My current code:

Open me in a dialog

That works fine BUT if I open this link in a new tab/window (e.g. by clicking the middle mouse-button), the form will be displayed "naked".

In this case I would like to forward the user to the refered page, e.g.:

if ($requester != $server) {
    header ("Location: " . $_SERVER["HTTP_REFERER"];
}

How can I detect $requester and $server? I don't want to block every script or a whole directory!

Thanks in advance!

Body:
I have those values coming in on a external request:

[HTTP_HOST] => 104.219.42.237

[HTTP_REFERER] => http:// someurl.com

So, my solution is :

if (strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== FALSE) {

    echo 'same origin/request';

} else {

   echo 'different origin/request';
}

...

...

...

The Reason that previous solutions did not work !

In My case:
$_SERVER['HTTP_REFERER'] ==  'http:// someurl.com'

while
 $_SERVER["HTTP_HOST"] does not contains 'http' nor 'https'

So,

if($_SERVER['HTTP_REFERER']!=$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"])

won't match

The other answer

if( $_SERVER['REMOTE_ADDR'] == $your_Server_IP_Address)

will not work on localhost


问:
HTML5 <video> tag in Chrome doesn't work
I have noticed a strange problem with the HTML5 <video/> tag in Chrome.

Using this, it works fine:

```<code><video poster="023.png" autoplay controls>
<source src="todojunto.mp4" type="video/mp4"  />
</video>
</code>```

This only plays the sound, no video:

```<code><video poster="023.png" autoplay >
<source src="todojunto.mp4" type="video/mp4"  />
</video>
</code>```

If I remove the poster attribute, it works again.

All other browsers (even IE9...!) works perfectly, and I can't seem to find the reason.

Any ideas/help?

Thanks

答:
You need to use muted=""; it does work for video

 <video width="auto" height="400px" autoplay="" loop="" muted="">
       <source src="Video.mp4"  type="video/mp4">
    <source src="Video.ogg" type="video/ogg">
 </video>

```

Body:
I have noticed a strange problem with the HTML5 <video/> tag in Chrome.

Using this, it works fine:

<video poster="023.png" autoplay controls>
<source src="todojunto.mp4" type="video/mp4"  />
</video>

This only plays the sound, no video:

<video poster="023.png" autoplay >
<source src="todojunto.mp4" type="video/mp4"  />
</video>

If I remove the poster attribute, it works again.

All other browsers (even IE9...!) works perfectly, and I can't seem to find the reason.

Any ideas/help?

Thanks

Body:
You need to use muted=""; it does work for video

<div class="wrap">
 <video width="auto" height="400px" autoplay="" loop="" muted="">
       <source src="Video.mp4"  type="video/mp4">
    <source src="Video.ogg" type="video/ogg">
 </video>
</div>


问:
Iterator bounds checking exceeding vector size
My question is different because I am not looking for a range-3v solution. Also, I was specifically asking how to fix the issue with the 2nd for a loop. I accepted the answer below my question already. For I didn't need a second for loop, They showed me how to use a single index by anding it with 1 for odd iterations. This solved my problem!

I am writing a function that will take a vector assuming it is of even length of elements; In my function, I'm creating two temp vectors from the original vector where their elements are {0,2,4,6,...} and {1,3,5,7,...} respectively. Then I am adding the corresponding indexed elements and storing the results into my results vector.

Here is my function:

```<code>void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    using It = std::vector<int>::const_iterator;
    std::vector<int> temp1, temp2;

    // First lets divide the original vector into two temp vectors
    for (It it1 = values.cbegin(); it1 != values.cend(); it1 += 2)
        temp1.push_back(*it1);

    for (It it2 = values.cbegin() + 1; it2 != values.cend() ; it2 += 2)
        temp2.push_back(*it2);

    // Add each corresponding vector and store that into our results.
    for (std::size_t i = 0; i < values.size() / 2; i++)
        result[i] = temp1[i] + temp2[i];
}
</code>```

Here is how I'm using it:

```<code>int main()
{
    std::vector<int> values{ 1,2,3,4,5,6 };
    for (auto i : values)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<int> results;

    sumElementPairsFromVector(values, results);
    for (auto i : results)
        std::cout << i << " ";
    std::cout << '\n';

    return 0;
}
</code>```

The expected output should be:

```<code>1 2 3 4 5 6
3 7 11
</code>```

The debug assertion is failing on this line of code from the function:

```<code>for (It it2 = values.cbegin() + 1; it2 != values.cend(); it2 += 2 )
</code>```

I know what is causing the error; on the last iteration after it increments by 2 and goes to check if it2 != values.cend() it is going past the end of the vector. How do I fix this?

答:
I know what is causing the error; on the last iteration after it
  increments by 2 and goes to check if it2 != values.cend() it is going
  past the end of the vector. How do I fix this?

You do not need two different loops for iterate through vector values.

```<code>std::vector<int> temp1, temp2;
temp1.reserve(values.size() / 2); // reserve the memory
temp2.reserve(values.size() / 2);

for (std::size_t index = 0; index < values.size(); ++index)
{
    if (index & 1) temp2.emplace_back(values[index]); // odd index
    else temp1.emplace_back(values[index]);           // even index
}
</code>```

Secondly, results did not allocate any memory at the time

```<code>result[i] = temp1[i] + temp2[i];
</code>```

hence out of bound undefined behavior. You should

```<code>for (std::size_t i = 0; i < std::min(temp1.size(), temp2.size()); i++)
    result.emplace_back(temp1[i] + temp2[i]);
</code>```

On the other hand, if the goal is to have a resulting vector from the sum of the consecutive pair of elements, the temp1  and temp2 are redundant. The result  can be filled simply:

```<code>void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    result.reserve(values.size() / 2);

    for (std::size_t index = 0; index < values.size() - 1; index += 2)
        result.emplace_back(values[index] + values[index+1]);
}
</code>```

Body:
My question is different because I am not looking for a range-3v solution. Also, I was specifically asking how to fix the issue with the 2nd for a loop. I accepted the answer below my question already. For I didn't need a second for loop, They showed me how to use a single index by anding it with 1 for odd iterations. This solved my problem!

I am writing a function that will take a vector assuming it is of even length of elements; In my function, I'm creating two temp vectors from the original vector where their elements are {0,2,4,6,...} and {1,3,5,7,...} respectively. Then I am adding the corresponding indexed elements and storing the results into my results vector.

Here is my function:

void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    using It = std::vector<int>::const_iterator;
    std::vector<int> temp1, temp2;

    // First lets divide the original vector into two temp vectors
    for (It it1 = values.cbegin(); it1 != values.cend(); it1 += 2)
        temp1.push_back(*it1);

    for (It it2 = values.cbegin() + 1; it2 != values.cend() ; it2 += 2)
        temp2.push_back(*it2);

    // Add each corresponding vector and store that into our results.
    for (std::size_t i = 0; i < values.size() / 2; i++)
        result[i] = temp1[i] + temp2[i];
}

Here is how I'm using it:

int main()
{
    std::vector<int> values{ 1,2,3,4,5,6 };
    for (auto i : values)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<int> results;

    sumElementPairsFromVector(values, results);
    for (auto i : results)
        std::cout << i << " ";
    std::cout << '\n';

    return 0;
}

The expected output should be:

1 2 3 4 5 6
3 7 11

The debug assertion is failing on this line of code from the function:

for (It it2 = values.cbegin() + 1; it2 != values.cend(); it2 += 2 )

I know what is causing the error; on the last iteration after it increments by 2 and goes to check if it2 != values.cend() it is going past the end of the vector. How do I fix this?

Body:
I know what is causing the error; on the last iteration after it
  increments by 2 and goes to check if it2 != values.cend() it is going
  past the end of the vector. How do I fix this?

You do not need two different loops for iterate through vector values.

std::vector<int> temp1, temp2;
temp1.reserve(values.size() / 2); // reserve the memory
temp2.reserve(values.size() / 2);

for (std::size_t index = 0; index < values.size(); ++index)
{
    if (index & 1) temp2.emplace_back(values[index]); // odd index
    else temp1.emplace_back(values[index]);           // even index
}

Secondly, results did not allocate any memory at the time

result[i] = temp1[i] + temp2[i];

hence out of bound undefined behavior. You should

for (std::size_t i = 0; i < std::min(temp1.size(), temp2.size()); i++)
    result.emplace_back(temp1[i] + temp2[i]);

On the other hand, if the goal is to have a resulting vector from the sum of the consecutive pair of elements, the temp1  and temp2 are redundant. The result  can be filled simply:

void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    result.reserve(values.size() / 2);

    for (std::size_t index = 0; index < values.size() - 1; index += 2)
        result.emplace_back(values[index] + values[index+1]);
}


问:
Measuring performance of java.io.InputStream
I have a file 5GB in size which I want to read by chunks, say 2MB. Using java.io.InputStream works fine. So I measured this thing as follows:

```<code>static final byte[] buffer = new byte[2 * 1024 * 1024];

public static void main(String args[]) throws IOException {
    while(true){
        InputStream is = new FileInputStream("/tmp/log_test.log");
        long bytesRead = 0;
        int readCurrent;
        long start = System.nanoTime();
        while((readCurrent = is.read(buffer)) > 0){
            bytesRead += readCurrent;
        }
        long end = System.nanoTime();
        System.out.println(
            "Bytes read = " + bytesRead + ". Time elapsed = " + (end - start)
        );
    }
}
</code>```

RESULT = 2121714428

It can be seen that averagely it takes 2121714428 nanos. It is so because the implementation does (*env)->SetByteArrayRegion(env, bytes, off, nread, (jbyte *)buf); of the data read into a malloced or stack allocated buffer as shown here. So memcpy takes pretty large amount of CPU time:

Since JNI spec defines that

Inside a critical region, native code must not call other JNI
  functions, or any system call that may cause the current thread to
  block and wait for another Java thread. (For example, the current
  thread must not call read on a stream being written by another Java
  thread.)

I don't see any problems to do read from a regular file within a critical section. Reading from a regular file is blocked only briefly and does not depend on any java thread. Something like this:

```<code>static final byte[] buffer = new byte[2 * 1024 * 1024];

public static void main(String args[]) throws IOException {
    while (true) {
        int fd = open("/tmp/log_test.log");
        long bytesRead = 0;
        int readCurrent;
        long start = System.nanoTime();
        while ((readCurrent = read(fd, buffer)) > 0) {
            bytesRead += readCurrent;
        }
        long end = System.nanoTime();
        System.out.println("Bytes read = " + bytesRead + ". Time elapsed = " + (end - start));
    }
}

private static native int open(String path);

private static native int read(int fd, byte[] buf);
</code>```

JNI functions:

```<code>JNIEXPORT jint JNICALL Java_com_test_Main_open
  (JNIEnv *env, jclass jc, jstring path){
    const char *native_path = (*env)->GetStringUTFChars(env, path, NULL);
    int fd = open(native_path, O_RDONLY);
    (*env)->ReleaseStringUTFChars(env, path, native_path);
    return fd;
}

JNIEXPORT jint JNICALL Java_com_test_Main_read
  (JNIEnv *env, jclass jc, jint fd, jbyteArray arr){
    size_t java_array_size = (size_t) (*env)->GetArrayLength(env, arr);
    void *buf = (*env)->GetPrimitiveArrayCritical(env, arr, NULL);
    ssize_t bytes_read = read(fd, buf, java_array_size);
    (*env)->ReleasePrimitiveArrayCritical(env, arr, buf, 0);
    return (jint) bytes_read;
}
</code>```

RESULT = 1179852225

Runnning this in a loop it takes averagely 1179852225 nanos which is almost twice more efficient.

Question: What's the actual problem with reading from a regular file within critical section?

答:
2MB buffer with FileInputStream is probably not the best choice. See this question for details. Although it was on Windows, I've seen a similar performance issue on Linux. Depending on the OS, allocating a temporary large buffer may result in extra mmap calls and subsequent page faults. Also such a large buffer makes L1/L2 caches useless.

Reading from a regular file is blocked only briefly and does not
  depend on any java thread.

This is not always true. In your benchmark the file is apparently cached in OS page cache and no device I/O happens. Accessing the real hardware (especially a spinning disk) can be orders of magnitude slower. The worst time of disk I/O is not fully predictable - it can be as large as hundreds of milliseconds, depending on the hardware condition, the length of I/O queue, the scheduling policy and so on.

The problem with JNI critical section is whenever a delay happens, it may affect all threads, not only the one doing I/O. This is not an issue for a single-threaded application, but this may cause undesirable stop-the-world pauses in a multi-threaded app.

The other reason against JNI critical is JVM bugs related to GCLocker. Sometimes they may cause redundant GC cycles or ignoring certain GC flags. Here are some examples (still not fixed):

JDK-8048556 Unnecessary GCLocker-initiated young GCs

JDK-8057573 CMSScavengeBeforeRemark ignored if GCLocker is active

JDK-8057586 Explicit GC ignored if GCLocker is active

So, the question is whether you care about throughput or latency. If you need only higher throughput, JNI critical is probably the right way to go. However, if you also care about predictable latency (not the average latency, but say, 99.9%) then JNI critical does not seem like the good choice.

Body:
I have a file 5GB in size which I want to read by chunks, say 2MB. Using java.io.InputStream works fine. So I measured this thing as follows:

static final byte[] buffer = new byte[2 * 1024 * 1024];

public static void main(String args[]) throws IOException {
    while(true){
        InputStream is = new FileInputStream("/tmp/log_test.log");
        long bytesRead = 0;
        int readCurrent;
        long start = System.nanoTime();
        while((readCurrent = is.read(buffer)) > 0){
            bytesRead += readCurrent;
        }
        long end = System.nanoTime();
        System.out.println(
            "Bytes read = " + bytesRead + ". Time elapsed = " + (end - start)
        );
    }
}

RESULT = 2121714428

It can be seen that averagely it takes 2121714428 nanos. It is so because the implementation does (*env)->SetByteArrayRegion(env, bytes, off, nread, (jbyte *)buf); of the data read into a malloced or stack allocated buffer as shown here. So memcpy takes pretty large amount of CPU time:

Since JNI spec defines that

Inside a critical region, native code must not call other JNI
  functions, or any system call that may cause the current thread to
  block and wait for another Java thread. (For example, the current
  thread must not call read on a stream being written by another Java
  thread.)

I don't see any problems to do read from a regular file within a critical section. Reading from a regular file is blocked only briefly and does not depend on any java thread. Something like this:

static final byte[] buffer = new byte[2 * 1024 * 1024];

public static void main(String args[]) throws IOException {
    while (true) {
        int fd = open("/tmp/log_test.log");
        long bytesRead = 0;
        int readCurrent;
        long start = System.nanoTime();
        while ((readCurrent = read(fd, buffer)) > 0) {
            bytesRead += readCurrent;
        }
        long end = System.nanoTime();
        System.out.println("Bytes read = " + bytesRead + ". Time elapsed = " + (end - start));
    }
}

private static native int open(String path);

private static native int read(int fd, byte[] buf);

JNI functions:

JNIEXPORT jint JNICALL Java_com_test_Main_open
  (JNIEnv *env, jclass jc, jstring path){
    const char *native_path = (*env)->GetStringUTFChars(env, path, NULL);
    int fd = open(native_path, O_RDONLY);
    (*env)->ReleaseStringUTFChars(env, path, native_path);
    return fd;
}

JNIEXPORT jint JNICALL Java_com_test_Main_read
  (JNIEnv *env, jclass jc, jint fd, jbyteArray arr){
    size_t java_array_size = (size_t) (*env)->GetArrayLength(env, arr);
    void *buf = (*env)->GetPrimitiveArrayCritical(env, arr, NULL);
    ssize_t bytes_read = read(fd, buf, java_array_size);
    (*env)->ReleasePrimitiveArrayCritical(env, arr, buf, 0);
    return (jint) bytes_read;
}

RESULT = 1179852225

Runnning this in a loop it takes averagely 1179852225 nanos which is almost twice more efficient.

Question: What's the actual problem with reading from a regular file within critical section?


问:
Url from getSignedUrl will expire in few weeks
I've got storage trigger function which resize and replace uploaded image into storage and then update URL in my database

```<code>    }).then(() => {
        console.log('Original file deleted', filePath)
        const logo = storageRef.file(JPEGFilePath)
        return logo.getSignedUrl({ action: 'read', expires: date })

        // const logo = storageRef.child(JPEGFilePath)
        // return logo.getDownloadURL()

        // return storageUrl.getDownloadURL(JPEGFilePath)
    }).then((url) => {
        const newRef = db.collection("user").doc(uid)
        return newRef.set({
            profile: { profileImg: url[0] }
        }, {
                merge: true
            })
    })
</code>```

here is how I set expiry date

```<code>const d = new Date()
const date = new Date(d.setFullYear(d.getFullYear() + 200)).toString()
</code>```

However the image expire in few weeks (roughly about 2 weeks). Does anyone know how to fix that? I have even played with getDownloadURL as you can see from commented code but that doesn't seems to work in trigger

答:
Ok so I have tried something but I have no idea if this will work or not so I'll come back in 2 weeks to mark my question as answered if it will work. For those with the same problem I'll try to recapitulate what I've done.

1/ Download the service account key from console. Here is the link

https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk

2/ Save the downloaded JSON file in your function directory

3/ Include the key in your function storage. But be careful how you set the path to the file. Here is my question about it

https://stackoverflow.com/a/56407592/11486115

UPDATE

I just found mistake in my function. My URL was provided by cloud function by mistake (commented code)

Here is complete function

```<code>const {
db
} = require('../../admin')

const projectId = "YOUR-PROJECT-ID"
const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: 'PATH-TO-SERVICE-ACCOUNT'})

const os = require('os');
const fs = require('fs');
const path = require('path');

const spawn = require('child-process-promise').spawn

const JPEG_EXTENSION = '.jpg'

exports.handler = ((object) => {
const bucket = object.bucket;
const contentType = object.contentType;
const filePath = object.name
const JPEGFilePath = path.normalize(path.format({ dir: path.dirname(filePath), name: 'profileImg', ext: JPEG_EXTENSION }))
const destBucket = storage.bucket(bucket)
const tempFilePath = path.join(os.tmpdir(), path.basename(filePath))
const tempLocalJPEGFile = path.join(os.tmpdir(), path.basename(JPEGFilePath))
const metadata = {
    contentType: contentType
}
const uid = filePath.split("/").slice(1, 2).join("")
const d = new Date()
const date = new Date(d.setFullYear(d.getFullYear() + 200)).toString()

if (!object.contentType.startsWith('image/')) {
    return destBucket.file(filePath).delete().then(() => {
        console.log('File is not an image ', filePath, ' DELETED')
        return null
    });
}

if (object.metadata.modified) {
    console.log('Image processed')
    return null
}

return destBucket.file(filePath).download({
    destination: tempFilePath
})
    .then(() => {
        console.log('The file has been downloaded to', tempFilePath)
        return spawn('convert', [tempFilePath, '-resize', '100x100', tempLocalJPEGFile])
    }).then(() => {
        console.log('JPEG image created at', tempLocalJPEGFile)
        metadata.modified = true
        return destBucket.upload(tempLocalJPEGFile,
            {
                destination: JPEGFilePath,
                metadata: { metadata: metadata }
            })
    }).then(() => {
        console.log('JPEG image uploaded to Storage at', JPEGFilePath)
        return destBucket.file(filePath).delete()
    }).then(() => {
        console.log('Original file deleted', filePath)
        //const logo = storageRef.file(JPEGFilePath)
        const logo = destBucket.file(JPEGFilePath)
        return logo.getSignedUrl({ action: 'read', expires: date })
    }).then((url) => {
        const newRef = db.collection("user").doc(uid)
        return newRef.set({
            profile: { profileImg: url[0] }
        }, {
                merge: true
            })
    }).then(() => {
        fs.unlinkSync(tempFilePath);
        fs.unlinkSync(tempLocalJPEGFile)
        console.log(uid, 'user database updated ')
        return null
    })
})
</code>```

I'm pretty confident that this will work now.

Body:
I've got storage trigger function which resize and replace uploaded image into storage and then update URL in my database

    }).then(() => {
        console.log('Original file deleted', filePath)
        const logo = storageRef.file(JPEGFilePath)
        return logo.getSignedUrl({ action: 'read', expires: date })

        // const logo = storageRef.child(JPEGFilePath)
        // return logo.getDownloadURL()

        // return storageUrl.getDownloadURL(JPEGFilePath)
    }).then((url) => {
        const newRef = db.collection("user").doc(uid)
        return newRef.set({
            profile: { profileImg: url[0] }
        }, {
                merge: true
            })
    })

here is how I set expiry date

const d = new Date()
const date = new Date(d.setFullYear(d.getFullYear() + 200)).toString()

However the image expire in few weeks (roughly about 2 weeks). Does anyone know how to fix that? I have even played with getDownloadURL as you can see from commented code but that doesn't seems to work in trigger

Body:
Ok so I have tried something but I have no idea if this will work or not so I'll come back in 2 weeks to mark my question as answered if it will work. For those with the same problem I'll try to recapitulate what I've done.

1/ Download the service account key from console. Here is the link

https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk

2/ Save the downloaded JSON file in your function directory

3/ Include the key in your function storage. But be careful how you set the path to the file. Here is my question about it

https://stackoverflow.com/a/56407592/11486115

UPDATE

I just found mistake in my function. My URL was provided by cloud function by mistake (commented code)

Here is complete function

const {
db
} = require('../../admin')

const projectId = "YOUR-PROJECT-ID"
const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: 'PATH-TO-SERVICE-ACCOUNT'})

const os = require('os');
const fs = require('fs');
const path = require('path');

const spawn = require('child-process-promise').spawn

const JPEG_EXTENSION = '.jpg'

exports.handler = ((object) => {
const bucket = object.bucket;
const contentType = object.contentType;
const filePath = object.name
const JPEGFilePath = path.normalize(path.format({ dir: path.dirname(filePath), name: 'profileImg', ext: JPEG_EXTENSION }))
const destBucket = storage.bucket(bucket)
const tempFilePath = path.join(os.tmpdir(), path.basename(filePath))
const tempLocalJPEGFile = path.join(os.tmpdir(), path.basename(JPEGFilePath))
const metadata = {
    contentType: contentType
}
const uid = filePath.split("/").slice(1, 2).join("")
const d = new Date()
const date = new Date(d.setFullYear(d.getFullYear() + 200)).toString()

if (!object.contentType.startsWith('image/')) {
    return destBucket.file(filePath).delete().then(() => {
        console.log('File is not an image ', filePath, ' DELETED')
        return null
    });
}

if (object.metadata.modified) {
    console.log('Image processed')
    return null
}

return destBucket.file(filePath).download({
    destination: tempFilePath
})
    .then(() => {
        console.log('The file has been downloaded to', tempFilePath)
        return spawn('convert', [tempFilePath, '-resize', '100x100', tempLocalJPEGFile])
    }).then(() => {
        console.log('JPEG image created at', tempLocalJPEGFile)
        metadata.modified = true
        return destBucket.upload(tempLocalJPEGFile,
            {
                destination: JPEGFilePath,
                metadata: { metadata: metadata }
            })
    }).then(() => {
        console.log('JPEG image uploaded to Storage at', JPEGFilePath)
        return destBucket.file(filePath).delete()
    }).then(() => {
        console.log('Original file deleted', filePath)
        //const logo = storageRef.file(JPEGFilePath)
        const logo = destBucket.file(JPEGFilePath)
        return logo.getSignedUrl({ action: 'read', expires: date })
    }).then((url) => {
        const newRef = db.collection("user").doc(uid)
        return newRef.set({
            profile: { profileImg: url[0] }
        }, {
                merge: true
            })
    }).then(() => {
        fs.unlinkSync(tempFilePath);
        fs.unlinkSync(tempLocalJPEGFile)
        console.log(uid, 'user database updated ')
        return null
    })
})

I'm pretty confident that this will work now.


问:
Can't derefence variable so function is satisfied
I can't seem to run this function called factorial() without getting an error.

At first if I have inbuf = atoi(factorial(inbuf));, gcc will spit out,

```<code>main.c:103: warning: passing argument 1 of ‘factorial’ makes integer from pointer without a cast
</code>```

If I change it to inbuf = atoi(factorial(inbuf*));, gcc will spit out,

```<code>main.c:103: error: expected expression before ‘)’ token
</code>```

Relevant code:

```<code>int factorial(int n)
{
    int temp;

    if (n <= 1)
        return 1;
    else
        return temp = n * factorial(n - 1);
} // end factorial

int main (int argc, char *argv[])
{
    char *inbuf[MSGSIZE];
    int fd[2];

    # pipe() code
    # fork() code

    // read the number to factorialize from the pipe
    read(fd[0], inbuf, MSGSIZE);

    // close read
    close(fd[0]);

    // find factorial using input from pipe, convert to string
    inbuf = atoi(factorial(inbuf*));

    // send the number read from the pipe to the recursive factorial() function
    write(fd[1], inbuf, MSGSIZE);

    # more code

} // end main
</code>```

What am I missing about dereferencing and my syntax??

答:
You need to rearrange your calls on this line:

```<code>inbuf = atoi(factorial(inbuf*));
</code>```

should be

```<code>int answ = factorial(atoi(inbuf));
</code>```

*Assuming all the other code works, but I think you need to change the declaration of inbuf from char *inbuf[MSGSIZE]; to char inbuf[MSGSIZE];

Body:
I can't seem to run this function called factorial() without getting an error.

At first if I have inbuf = atoi(factorial(inbuf));, gcc will spit out,

main.c:103: warning: passing argument 1 of ‘factorial’ makes integer from pointer without a cast

If I change it to inbuf = atoi(factorial(inbuf*));, gcc will spit out,

main.c:103: error: expected expression before ‘)’ token

Relevant code:

int factorial(int n)
{
    int temp;

    if (n <= 1)
        return 1;
    else
        return temp = n * factorial(n - 1);
} // end factorial

int main (int argc, char *argv[])
{
    char *inbuf[MSGSIZE];
    int fd[2];

    # pipe() code
    # fork() code

    // read the number to factorialize from the pipe
    read(fd[0], inbuf, MSGSIZE);

    // close read
    close(fd[0]);

    // find factorial using input from pipe, convert to string
    inbuf = atoi(factorial(inbuf*));

    // send the number read from the pipe to the recursive factorial() function
    write(fd[1], inbuf, MSGSIZE);

    # more code

} // end main

What am I missing about dereferencing and my syntax??

Body:
You need to rearrange your calls on this line:

inbuf = atoi(factorial(inbuf*));

should be

int answ = factorial(atoi(inbuf));

*Assuming all the other code works, but I think you need to change the declaration of inbuf from char *inbuf[MSGSIZE]; to char inbuf[MSGSIZE];


问:
Laravel Axios Failed with status code 419 using Vue
Concept: I have an application that allows users post a question... When the user clicks the Ask button i trying to submit the the quesiton using Vue.js and Axios.

Problem: 70% of the time the question is submitted properly, but 30% of the time it fails and returns "Failed to load resource: the server responded with a status of 419 (unknown status)"

My Vue component

```<code><template>
    <div id = "main_question_box" class = "tab-pane fade">
        <div class="panel-body posting-field-box">
            <textarea name="feed_body" class="summernote posting-field form-control"></textarea>
            <button class = "example-btn btn btn-xs btn-default pull-right">View Question Examples</button>
        </div>

        <div class="panel-footer">
            <ul class="list-inline pull-right">
                <li>
                    <button @click = "sendPost" class="feed-post-btn btn btn-submit btn-sm btn-success pl-l pr-l">
                        <span>Ask</span>
                        <i class="fa fa-paper-plane pl-sm"></i>
                    </button>
                </li>
            </ul>

            <div class="clearfix"></div>
        </div>
    </div>
</template>

<script>

    axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

    export default {
        props:['timelineId'],
        data(){
            return {
                feed_body: '',
                timeline_id: this.timelineId,
                type: 'Question',
                post_ready: false
            }
        },
        methods: {
            sendPost: function () {
                this.compilePost(this);
                if(this.post_ready){
                    var self = this;
                    self.startLoader();
                    axios.post('/timeline',
                    {
                        feed_body: this.feed_body,
                        timeline_id: this.timeline_id,
                        feed_type: this.type

                    }).then(response =>{
                        this.feed_body = '';
                        this.post_ready = false;
                        $('#main_question_box .summernote').summernote('code', '');
                        this.$emit('newFeedSent', response.data);
                    });
                }
            },
            startLoader: function(){
                $('.feed-post-btn').addClass('btn-default').removeClass('btn-success').prop('disabled', true).find('span').hide();
                $('.feed-post-btn').find('i').attr('class', 'fa fa-cog fa-spin fa-2x fa-fw');
            },
            compilePost: function(instance) {
                var editor = $('#main_question_box .summernote');
                var isEmpty = $(editor).summernote('isEmpty');
                if(!isEmpty){
                    instance.feed_body = $(editor).summernote('code');
                    instance.post_ready = true;
                }else{
                    instance.post_ready = false;
                }
            }
        }
    }

</script>
</code>```

My Web.php

```<code>Route::post('/timeline', 'FeedController@storeFeed');
</code>```

My Controller

```<code>public function storeFeed(Request $request)
{

    if($request->feed_type == 'Debate'){
        $this->validate(request(), [
            'feed_subject' => 'required',
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishDebate($request);

    }elseif($request->feed_type == 'Question'){
        $this->validate(request(), [
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishQuestion($request);

    }else{
        $this->validate(request(), [
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishPost($request);
    }

    return $publishedFeed->id;

}
</code>```

My HTML Head

```<code><!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="login-status" content="{{ Auth::check() }}">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

My resources\assets\js\Bootstrap.js

```<code>    window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
</code>```

答:
I can reproduce this problem.

Use Vuejs/Laravel app as normal.

Refresh page with \Session::flush() in your controller

public function getProduct(Request $request)
    {
        \Session::flush();
        return view('product');
    }

Make a put/post request from client ->Request failed with status code 419

This likely means that in development your session expires so you can try to set your session lifetime to a higher number to see if that resolves the issue.

Body:
Concept: I have an application that allows users post a question... When the user clicks the Ask button i trying to submit the the quesiton using Vue.js and Axios.

Problem: 70% of the time the question is submitted properly, but 30% of the time it fails and returns "Failed to load resource: the server responded with a status of 419 (unknown status)"

My Vue component

<template>

            <textarea name="feed_body" class="summernote posting-field form-control"></textarea>
            <button class = "example-btn btn btn-xs btn-default pull-right">View Question Examples</button>

                    <button @click = "sendPost" class="feed-post-btn btn btn-submit btn-sm btn-success pl-l pr-l">
                        Ask

                    </button>

</template>

My Web.php

Route::post('/timeline', 'FeedController@storeFeed');

My Controller

public function storeFeed(Request $request)
{

    if($request->feed_type == 'Debate'){
        $this->validate(request(), [
            'feed_subject' => 'required',
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishDebate($request);

    }elseif($request->feed_type == 'Question'){
        $this->validate(request(), [
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishQuestion($request);

    }else{
        $this->validate(request(), [
            'feed_body' => 'required',
        ]);

        $publishedFeed = Auth::user()->publishPost($request);
    }

    return $publishedFeed->id;

}

My HTML Head

<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="login-status" content="{{ Auth::check() }}">

    <meta name="csrf-token" content="{{ csrf_token() }}">

My resources\assets\js\Bootstrap.js

    window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}


问:
Search substring in a string using regex
I'm trying to search for a set of words, contained within an ArrayList(terms_1pers), inside a string and, since the precondition is that before and after the search word there should be no letters, I thought of using expression regular.

I just don't know what I'm doing wrong using the matches operator. In the code reported, if the matching is not verified, it writes to an external file.

```<code>String url = csvRecord.get("url");
String text = csvRecord.get("review");
String var = null;
for(String term : terms_1pers)
{
   if(!text.matches("[^a-z]"+term+"[^a-z]"))
   {
      var="true";
   }
}
if(!var.equals("true"))
{
    bw.write(url+";"+text+"\n");
}
</code>```

答:
you did not consider the case where the start and end may contain letters
so adding .* at the front and end should solve your problem. </p>

```<code>for(String term : terms_1pers)
{
   if( text.matches(".*[^a-zA-Z]+" + term + "[^a-zA-Z]+.*)" )
   {
      var="true";
      break; //exit the loop
   }
}
if(!var.equals("true"))
{
    bw.write(url+";"+text+"\n");
}
</code>```

Body:
I'm trying to search for a set of words, contained within an ArrayList(terms_1pers), inside a string and, since the precondition is that before and after the search word there should be no letters, I thought of using expression regular.

I just don't know what I'm doing wrong using the matches operator. In the code reported, if the matching is not verified, it writes to an external file.

String url = csvRecord.get("url");
String text = csvRecord.get("review");
String var = null;
for(String term : terms_1pers)
{
   if(!text.matches("[^a-z]"+term+"[^a-z]"))
   {
      var="true";
   }
}
if(!var.equals("true"))
{
    bw.write(url+";"+text+"\n");
}

Body:
you did not consider the case where the start and end may contain letters
so adding .* at the front and end should solve your problem.

for(String term : terms_1pers)
{
   if( text.matches(".*[^a-zA-Z]+" + term + "[^a-zA-Z]+.*)" )
   {
      var="true";
      break; //exit the loop
   }
}
if(!var.equals("true"))
{
    bw.write(url+";"+text+"\n");
}


问:
Laravel union and join in the query
I have 3 tables

send_to_employees

onprocess

employees

I want to do union of the two table send_to_employees and onprocess. After that I want to join the result with the employees table.

I have done it in a raw SQL query like the following already:

```<code>SELECT *
FROM (
  SELECT
    send_to_employees.caseid,
    send_to_employees.docs,
    send_to_employees.helper,
    send_to_employees.employee_id
  FROM send_to_employees
  UNION
  SELECT
    onprocess.caseid,
    onprocess.docs,
    onprocess.helper,
    onprocess.employee_id
  FROM onprocess
) t1
INNER JOIN employees
  ON employees.employee_id = t1.employee_id
</code>```

But I can't figure out how to do it with Laravel. Please help me to write this query using the query builder of Laravel 5.8.

答:
Try this code snippet. I think it should work. I am using query builder

//getting all record from table

```<code> $data['recorddisplay'] = DB::table('send_to_employees')
 ->leftjoin('onprocess', 'send_to_employee.caseid', '=', 'onprocess.caseid')
 ->leftjoin('employees', 'send_to_employee.employee_id', '=', 'employees.employee_id')
 ->get();
</code>```

Title: Laravel union and join in the query

Body:
I have 3 tables

send_to_employees

onprocess

employees

I want to do union of the two table send_to_employees and onprocess. After that I want to join the result with the employees table.

I have done it in a raw SQL query like the following already:

SELECT *
FROM (
  SELECT
    send_to_employees.caseid,
    send_to_employees.docs,
    send_to_employees.helper,
    send_to_employees.employee_id
  FROM send_to_employees
  UNION
  SELECT
    onprocess.caseid,
    onprocess.docs,
    onprocess.helper,
    onprocess.employee_id
  FROM onprocess
) t1
INNER JOIN employees
  ON employees.employee_id = t1.employee_id

But I can't figure out how to do it with Laravel. Please help me to write this query using the query builder of Laravel 5.8.

Body:
Try this code snippet. I think it should work. I am using query builder

//getting all record from table

 $data['recorddisplay'] = DB::table('send_to_employees')
 ->leftjoin('onprocess', 'send_to_employee.caseid', '=', 'onprocess.caseid')
 ->leftjoin('employees', 'send_to_employee.employee_id', '=', 'employees.employee_id')
 ->get();


问:
Given an array of objects, how do I replace the key name with another whilst keeping the value from the original key?
I'm trying to take an array of objects and, without mutating the original array, rename a specific key in each object.

I've created a new variable and assigned it to the result of using 'map' on my original array (to avoid mutation).
Within the 'map' method, I've tried to deconstruct the 'keyToChange' parameter and spread the rest of the values to the 'newKey'.

```<code>const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({keyToChange: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
   };
</code>```

The above code returns
'newKey: [undefined]' followed by the original array of objects.

Any help would be greatly appreciated.

答:
If you want a an expression to be the key to be changed then use square brackets around it []

```<code>const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({[keyToChange]: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
};
</code>```

Body:
I'm trying to take an array of objects and, without mutating the original array, rename a specific key in each object.

I've created a new variable and assigned it to the result of using 'map' on my original array (to avoid mutation).
Within the 'map' method, I've tried to deconstruct the 'keyToChange' parameter and spread the rest of the values to the 'newKey'.

const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({keyToChange: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
   };

The above code returns
'newKey: [undefined]' followed by the original array of objects.

Any help would be greatly appreciated.

Body:
If you want a an expression to be the key to be changed then use square brackets around it []

const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({[keyToChange]: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
};


答:
You need a computed property name instead of a (not given) propery keyToChange.

```<code>const spreadArray = array.map(({ [keyToChange]: newKey, ...rest }) => ({ newKey, ...rest }));
//                               ^^^^^^^^^^^^^
</code>```

Title: Given an array of objects, how do I replace the key name with another whilst keeping the value from the original key?

Body:
You need a computed property name instead of a (not given) propery keyToChange.

const spreadArray = array.map(({ [keyToChange]: newKey, ...rest }) => ({ newKey, ...rest }));
//                               ^^^^^^^^^^^^^


问:
Why can't I use var in this instance?
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

```<code>var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;
</code>```

Thanks to anyone who can tell me the correct method of making this work.

答:
If it's a local variable and the query itself were valid, you would be able to.

However, the query expression is invalid. Just looking at the last line, this:

```<code>select brand_family.brand_family_name, priority, roll_image;
</code>```

should probably be:

```<code>select new { brand_family.brand_family_name,
             brand.priority,
             brand.roll_image };
</code>```

It's worth looking closely at the compiler error - it generally gives a reasonably good explanation of what's wrong.

Next up, your ordering is almost certainly wrong - I very much doubt that this does what you want it to. To express multiple orderings, you typically just list them, separated by commas, like this:

```<code>var brandslist = from brand in brandDB.brands
                 join brand_family in brandDB.brand_family
                   on brand.brand_family_id equals brand_family.bf_id
                 orderby brand_family.brand_family_name,
                         brand.priority,
                         brand.order_id
                 select new { brand_family.brand_family_name,
                              brand.priority,
                              brand.roll_image };
</code>```

This will translate to an OrderBy call followed by subsequent ThenBy calls - treating brand_family_name as the primary sort ordering, and the others as secondary orderings.

Title: Why can't I use var in this instance?

Body:
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;

Thanks to anyone who can tell me the correct method of making this work.

Body:
If it's a local variable and the query itself were valid, you would be able to.

However, the query expression is invalid. Just looking at the last line, this:

select brand_family.brand_family_name, priority, roll_image;

should probably be:

select new { brand_family.brand_family_name,
             brand.priority,
             brand.roll_image };

It's worth looking closely at the compiler error - it generally gives a reasonably good explanation of what's wrong.

Next up, your ordering is almost certainly wrong - I very much doubt that this does what you want it to. To express multiple orderings, you typically just list them, separated by commas, like this:

var brandslist = from brand in brandDB.brands
                 join brand_family in brandDB.brand_family
                   on brand.brand_family_id equals brand_family.bf_id
                 orderby brand_family.brand_family_name,
                         brand.priority,
                         brand.order_id
                 select new { brand_family.brand_family_name,
                              brand.priority,
                              brand.roll_image };

This will translate to an OrderBy call followed by subsequent ThenBy calls - treating brand_family_name as the primary sort ordering, and the others as secondary orderings.


问:
Android Manifest error: Activities not assignable to android.app.activity
So I went to sleep and then when I woke up I opened up my Android project. There is one blaring error all over my Android Manifest file.

All screens in the AndroidManifest show that they are not assignable to 'android.app.activity'

I never had this problem before. Obviously all of my activities are activities and not fragments. (Looking at the answers here, most of it have that kind of error; mistaking fragment for activity)

Also, this Android project has never thrown this kind of error for the past few months.

Right now all of my screens are showing red lines.

Somehow I can run the project just fine even with all those red lines.

Here's what I've tried so far:

Cleaned up the project (Build -> Clean Up)

Rebuild the project (Build -> Rebuild)

Invalidate caches and restart

I'm running the latest Android Studio.

UPDATE:

Here's my Android Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.thispackage.thispackagename">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <activity android:name=".MainActivity">

        </activity>
        <activity android:name=".SplashScreen"
            android:screenOrientation="portrait">

            </activity>

        <activity android:name=".ScreenOne"
            android:screenOrientation="portrait">

        </activity>

        <activity android:name=".ScreenTwo"
            android:screenOrientation="portrait">

        </activity>

        <activity android:name=".RegisterActivity"
            android:screenOrientation="portrait">
            </activity>

        <activity android:name=".ScreenThree"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ScreenFour"
            android:screenOrientation="portrait">
        </activity>

        <activity android:name=".ScreenFive"
            android:screenOrientation="portrait">

        </activity>

        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />

        <!--<activity android:name="com.facebook.FacebookActivity"-->
            <!--android:configChanges=-->
                <!--"keyboard|keyboardHidden|screenLayout|screenSize|orientation"-->
            <!--android:theme="@android:style/Theme.Translucent.NoTitleBar"-->
            <!--android:label="@string/app_name" />-->

    </application>

</manifest>
</code>```

UPDATE 2: The following is the screenshot of the error.

UPDATE 3: When I clicked more, it shows this:

答: Go to your activity where your error is occurring. There will be an import in the top which included android.app.Activity. Just clear it and reimport by pressing Alt+Enter.</p>

Body:
So I went to sleep and then when I woke up I opened up my Android project. There is one blaring error all over my Android Manifest file.

All screens in the AndroidManifest show that they are not assignable to 'android.app.activity'

I never had this problem before. Obviously all of my activities are activities and not fragments. (Looking at the answers here, most of it have that kind of error; mistaking fragment for activity)

Also, this Android project has never thrown this kind of error for the past few months.

Right now all of my screens are showing red lines.

Somehow I can run the project just fine even with all those red lines.

Here's what I've tried so far:

Cleaned up the project (Build -> Clean Up)

Rebuild the project (Build -> Rebuild)

Invalidate caches and restart

I'm running the latest Android Studio.

UPDATE:

Here's my Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.thispackage.thispackagename">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <activity android:name=".MainActivity">

        </activity>
        <activity android:name=".SplashScreen"
            android:screenOrientation="portrait">

            </activity>

        <activity android:name=".ScreenOne"
            android:screenOrientation="portrait">

        </activity>

        <activity android:name=".ScreenTwo"
            android:screenOrientation="portrait">

        </activity>

        <activity android:name=".RegisterActivity"
            android:screenOrientation="portrait">
            </activity>

        <activity android:name=".ScreenThree"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ScreenFour"
            android:screenOrientation="portrait">
        </activity>

        <activity android:name=".ScreenFive"
            android:screenOrientation="portrait">

        </activity>

        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />

    </application>

</manifest>

UPDATE 2: The following is the screenshot of the error.

UPDATE 3: When I clicked more, it shows this:


问:
how can i parse json weather response
this is my response from weather map api

```<code>      {
            "message": "accurate",
            "cod": "200",
"count": 3,
"list": [
    {
        "id": 2641549,
        "name": "Newtonhill",
        "coord": {
            "lat": 57.0333,
            "lon": -2.15
        },
        "main": {
            "temp": 275.15,
            "pressure": 1010,
            "humidity": 93,
            "temp_min": 275.15,
            "temp_max": 275.15
        },
        "dt": 1521204600,
        "wind": {
            "speed": 9.3,
            "deg": 120,
            "gust": 18
        },
        "sys": {
            "country": ""
        },
        "rain": null,
        "snow": null,
        "clouds": {
            "all": 75
        },
        "weather": [
            {
                "id": 311,
                "main": "Drizzle",
                "description": "rain and drizzle",
                "icon": "09d"
            }
        ]
    }
</code>```

how can i get the description i did get the temperature using a retrofit by seriazable object but i could'nt get the weather description
i did that to get temperature  and the country
       class WeatherResponse {

```<code>     @SerializedName("sys")
     var sys: Sys? = null

    @SerializedName("main")
    var main: Main? = null

    @SerializedName("weather")
   var weather: Weather? = null
 }

class Main {
   @SerializedName("temp")
   var temp: Float = 0.0f

   }
</code>```

and i my main class im using a callback
           fun getCurrentData() {

```<code>    val retrofit = Retrofit.Builder()
        .baseUrl(BaseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    val service = retrofit.create(WeatherService::class.java)
    val call = service.getCurrentWeatherData(lat, lon, AppId)

    call.enqueue(object : Callback<WeatherResponse> {
        override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
            if (response.code() == 200) {
                val weatherResponse = response.body()!!
                var temp = (weatherResponse.main!!.temp - 273).toString().substring(0,3) + " ºC"
                tmp.text=temp

            }
        }

        override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {

        }
    })
}
</code>```

答:
Here is POJO class for your JSON. It now can be parsed easily.

WeatherResponse.kt

```<code>data class WeatherResponse(
    @SerializedName("cod")
    val cod: String? = null,
    @SerializedName("count")
    val count: Int? = null,
    @SerializedName("list")
    val list: List<X?>? = null,
    @SerializedName("message")
    val message: String? = null
) {
    data class X(
        @SerializedName("clouds")
        val clouds: Clouds? = null,
        @SerializedName("coord")
        val coord: Coord? = null,
        @SerializedName("dt")
        val dt: Int? = null,
        @SerializedName("id")
        val id: Int? = null,
        @SerializedName("main")
        val main: Main? = null,
        @SerializedName("name")
        val name: String? = null,
        @SerializedName("rain")
        val rain: Any? = null,
        @SerializedName("snow")
        val snow: Any? = null,
        @SerializedName("sys")
        val sys: Sys? = null,
        @SerializedName("weather")
        val weather: List<Weather?>? = null,
        @SerializedName("wind")
        val wind: Wind? = null
    )

    data class Clouds(
        @SerializedName("all")
        val all: Int?
    )

    data class Coord(
        @SerializedName("lat")
        val lat: Double? = null,
        @SerializedName("lon")
        val lon: Double? = null
    )

    data class Main(
        @SerializedName("humidity")
        val humidity: Int? = null,
        @SerializedName("pressure")
        val pressure: Int? = null,
        @SerializedName("temp")
        val temp: Double? = null,
        @SerializedName("temp_max")
        val tempMax: Double? = null,
        @SerializedName("temp_min")
        val tempMin: Double? = null
    )

    data class Sys(
        @SerializedName("country")
        val country: String?
    )

    data class Weather(
        @SerializedName("description")
        val description: String? = null,
        @SerializedName("icon")
        val icon: String? = null,
        @SerializedName("id")
        val id: Int? = null,
        @SerializedName("main")
        val main: String? = null
    )

    data class Wind(
        @SerializedName("deg")
        val deg: Int? = null,
        @SerializedName("gust")
        val gust: Int? = null,
        @SerializedName("speed")
        val speed: Double? = null
    )

}
</code>```

You can get Weather description by using

```<code>var description = weatherResponse.list?.get(0)?.weather?.get(0)?.description
</code>```

Title: how can i parse json weather response

Body:
this is my response from weather map api

      {
            "message": "accurate",
            "cod": "200",
"count": 3,
"list": [
    {
        "id": 2641549,
        "name": "Newtonhill",
        "coord": {
            "lat": 57.0333,
            "lon": -2.15
        },
        "main": {
            "temp": 275.15,
            "pressure": 1010,
            "humidity": 93,
            "temp_min": 275.15,
            "temp_max": 275.15
        },
        "dt": 1521204600,
        "wind": {
            "speed": 9.3,
            "deg": 120,
            "gust": 18
        },
        "sys": {
            "country": ""
        },
        "rain": null,
        "snow": null,
        "clouds": {
            "all": 75
        },
        "weather": [
            {
                "id": 311,
                "main": "Drizzle",
                "description": "rain and drizzle",
                "icon": "09d"
            }
        ]
    }

how can i get the description i did get the temperature using a retrofit by seriazable object but i could'nt get the weather description
i did that to get temperature  and the country
       class WeatherResponse {

     @SerializedName("sys")
     var sys: Sys? = null

    @SerializedName("main")
    var main: Main? = null

    @SerializedName("weather")
   var weather: Weather? = null
 }

class Main {
   @SerializedName("temp")
   var temp: Float = 0.0f

   }

and i my main class im using a callback
           fun getCurrentData() {

    val retrofit = Retrofit.Builder()
        .baseUrl(BaseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    val service = retrofit.create(WeatherService::class.java)
    val call = service.getCurrentWeatherData(lat, lon, AppId)

    call.enqueue(object : Callback<WeatherResponse> {
        override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
            if (response.code() == 200) {
                val weatherResponse = response.body()!!
                var temp = (weatherResponse.main!!.temp - 273).toString().substring(0,3) + " ºC"
                tmp.text=temp

            }
        }

        override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {

        }
    })
}

Body:
Here is POJO class for your JSON. It now can be parsed easily.

WeatherResponse.kt

data class WeatherResponse(
    @SerializedName("cod")
    val cod: String? = null,
    @SerializedName("count")
    val count: Int? = null,
    @SerializedName("list")
    val list: List<X?>? = null,
    @SerializedName("message")
    val message: String? = null
) {
    data class X(
        @SerializedName("clouds")
        val clouds: Clouds? = null,
        @SerializedName("coord")
        val coord: Coord? = null,
        @SerializedName("dt")
        val dt: Int? = null,
        @SerializedName("id")
        val id: Int? = null,
        @SerializedName("main")
        val main: Main? = null,
        @SerializedName("name")
        val name: String? = null,
        @SerializedName("rain")
        val rain: Any? = null,
        @SerializedName("snow")
        val snow: Any? = null,
        @SerializedName("sys")
        val sys: Sys? = null,
        @SerializedName("weather")
        val weather: List<Weather?>? = null,
        @SerializedName("wind")
        val wind: Wind? = null
    )

    data class Clouds(
        @SerializedName("all")
        val all: Int?
    )

    data class Coord(
        @SerializedName("lat")
        val lat: Double? = null,
        @SerializedName("lon")
        val lon: Double? = null
    )

    data class Main(
        @SerializedName("humidity")
        val humidity: Int? = null,
        @SerializedName("pressure")
        val pressure: Int? = null,
        @SerializedName("temp")
        val temp: Double? = null,
        @SerializedName("temp_max")
        val tempMax: Double? = null,
        @SerializedName("temp_min")
        val tempMin: Double? = null
    )

    data class Sys(
        @SerializedName("country")
        val country: String?
    )

    data class Weather(
        @SerializedName("description")
        val description: String? = null,
        @SerializedName("icon")
        val icon: String? = null,
        @SerializedName("id")
        val id: Int? = null,
        @SerializedName("main")
        val main: String? = null
    )

    data class Wind(
        @SerializedName("deg")
        val deg: Int? = null,
        @SerializedName("gust")
        val gust: Int? = null,
        @SerializedName("speed")
        val speed: Double? = null
    )

}

You can get Weather description by using

var description = weatherResponse.list?.get(0)?.weather?.get(0)?.description


答:
In order to find regex matches, you should use the regex classes. Pattern and Matcher.

```<code>String term = "term";
ArrayList<String> a  = new ArrayList<String>();
a.add("123term456"); //true
a.add("A123Term5"); //false
a.add("term456"); //true
a.add("123term"); //true
Pattern p = Pattern.compile("^[^A-Za-z]*(" + term + ")[^A-Za-z]*$");
for(String text : a) {
    Matcher m = p.matcher(text);
    if (m.find()) {
         System.out.println("Found: " + m.group(1) );
         //since the term you are adding is the second matchable portion, you're looking for group(1)
    }
    else System.out.println("No match for: " + term);
}
</code>```

}

In the example there, we create an instance of a https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html to find matches in the text you are matching against.

Note that I adjusted the regex a bit. The choice in this code excludes all letters A-Z and the lowercase versions from the initial matching part. It will also allow for situations where there are no characters at all before or after the match term. If you need to have something there, use + instead of *. I also limited the regex to force the match to only contain matches for these three groups by using ^ and $ to verify end the end of the matching text. If this doesn't fit your use case, you may need to adjust.

To demonstrate using this with a variety of different terms:

```<code>ArrayList<String> terms = new ArrayList<String>();
terms.add("term");
terms.add("the book is on the table");
terms.add("1981 was the best year ever!");
ArrayList<String> a  = new ArrayList<String>();
a.add("123term456");
a.add("A123Term5");
a.add("the book is on the table456");
a.add("1@#!231981 was the best year ever!9#");
for (String term: terms) {

    Pattern p = Pattern.compile("^[^A-Za-z]*(" + term + ")[^A-Za-z]*$");

    for(String text : a) {

        Matcher m = p.matcher(text);
        if (m.find()) {
             System.out.println("Found: " + m.group(1)  + " in " + text);
             //since the term you are adding is the second matchable portion, you're looking for group(1)
        }
        else System.out.println("No match for: " + term + " in " + text);
    }
}
</code>```

Output for this is:
Found: term in 123term456
No match for: term in A123Term5
No match for: term in the book is on the table456....

In response to the question about having String term being case insensitive, here's a way that we can build a string by taking advantage of java.lang.Character to options for upper and lower case letters.

```<code>String term = "This iS the teRm.";
String matchText = "123This is the term.";
StringBuilder str = new StringBuilder();
str.append("^[^A-Za-z]*(");
for (int i = 0; i < term.length(); i++) {
  char c = term.charAt(i);
  if (Character.isLetter(c))
    str.append("(" + Character.toLowerCase(c) + "|" + Character.toUpperCase(c) + ")");
  else str.append(c);
}
str.append(")[^A-Za-z]*$");

System.out.println(str.toString());

Pattern p = Pattern.compile(str.toString());
Matcher m = p.matcher(matchText);
if (m.find()) System.out.println("Found!");
else System.out.println("Not Found!");
</code>```

This code outputs two lines, the first line is the regex string that's being compiled in the Pattern. "^[^A-Za-z]*((t|T)(h|H)(i|I)(s|S) (i|I)(s|S) (t|T)(h|H)(e|E) (t|T)(e|E)(r|R)(m|M).)[^A-Za-z]*$" This adjusted regex allows for letters in the term to be matched regardless of case. The second output line is "Found!" because the mixed case term is found within matchText.

Title: Search substring in a string using regex

Body:
In order to find regex matches, you should use the regex classes. Pattern and Matcher.

String term = "term";
ArrayList<String> a  = new ArrayList<String>();
a.add("123term456"); //true
a.add("A123Term5"); //false
a.add("term456"); //true
a.add("123term"); //true
Pattern p = Pattern.compile("^[^A-Za-z]*(" + term + ")[^A-Za-z]*$");
for(String text : a) {
    Matcher m = p.matcher(text);
    if (m.find()) {
         System.out.println("Found: " + m.group(1) );
         //since the term you are adding is the second matchable portion, you're looking for group(1)
    }
    else System.out.println("No match for: " + term);
}

}

In the example there, we create an instance of a https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html to find matches in the text you are matching against.

Note that I adjusted the regex a bit. The choice in this code excludes all letters A-Z and the lowercase versions from the initial matching part. It will also allow for situations where there are no characters at all before or after the match term. If you need to have something there, use + instead of *. I also limited the regex to force the match to only contain matches for these three groups by using ^ and $ to verify end the end of the matching text. If this doesn't fit your use case, you may need to adjust.

To demonstrate using this with a variety of different terms:

ArrayList<String> terms = new ArrayList<String>();
terms.add("term");
terms.add("the book is on the table");
terms.add("1981 was the best year ever!");
ArrayList<String> a  = new ArrayList<String>();
a.add("123term456");
a.add("A123Term5");
a.add("the book is on the table456");
a.add("1@#!231981 was the best year ever!9#");
for (String term: terms) {

    Pattern p = Pattern.compile("^[^A-Za-z]*(" + term + ")[^A-Za-z]*$");

    for(String text : a) {

        Matcher m = p.matcher(text);
        if (m.find()) {
             System.out.println("Found: " + m.group(1)  + " in " + text);
             //since the term you are adding is the second matchable portion, you're looking for group(1)
        }
        else System.out.println("No match for: " + term + " in " + text);
    }
}

Output for this is:
Found: term in 123term456
No match for: term in A123Term5
No match for: term in the book is on the table456....

In response to the question about having String term being case insensitive, here's a way that we can build a string by taking advantage of java.lang.Character to options for upper and lower case letters.

String term = "This iS the teRm.";
String matchText = "123This is the term.";
StringBuilder str = new StringBuilder();
str.append("^[^A-Za-z]*(");
for (int i = 0; i < term.length(); i++) {
  char c = term.charAt(i);
  if (Character.isLetter(c))
    str.append("(" + Character.toLowerCase(c) + "|" + Character.toUpperCase(c) + ")");
  else str.append(c);
}
str.append(")[^A-Za-z]*$");

System.out.println(str.toString());

Pattern p = Pattern.compile(str.toString());
Matcher m = p.matcher(matchText);
if (m.find()) System.out.println("Found!");
else System.out.println("Not Found!");

This code outputs two lines, the first line is the regex string that's being compiled in the Pattern. "^[^A-Za-z]*((t|T)(h|H)(i|I)(s|S) (i|I)(s|S) (t|T)(h|H)(e|E) (t|T)(e|E)(r|R)(m|M).)[^A-Za-z]*$" This adjusted regex allows for letters in the term to be matched regardless of case. The second output line is "Found!" because the mixed case term is found within matchText.


问:
How Do I display current date and time in Toad for Oracle?
I have a sql statement that counts the units(cable boxes) that were refurbished (had damaged parts replaced) and total units(cable boxes that just went through refurb and had nothing replaced) and it's supposed to do this count regularly (every time a unit is processed the count). Can someone please help me? Thank you.

Justin

Heres my sql code so far:

SELECT COUNT(*)
FROM  cxadminn.repair_part

WHERE repair_type = 'REFURB' and created_date >?

答:
```<code>SELECT COUNT(*)
FROM cxadminn.repair_part
WHERE repair_type = 'REFURB'
  and created_date > sysdate
</code>```

To exclude the time that is part of any oracle DATE column, you would need to use this:

```<code>SELECT COUNT(*)
FROM cxadminn.repair_part
WHERE repair_type = 'REFURB'
  and trunc(created_date) > trunc(sysdate)
</code>```

Body:
SELECT COUNT(*)
FROM cxadminn.repair_part
WHERE repair_type = 'REFURB'
  and created_date > sysdate

To exclude the time that is part of any oracle DATE column, you would need to use this:

SELECT COUNT(*)
FROM cxadminn.repair_part
WHERE repair_type = 'REFURB'
  and trunc(created_date) > trunc(sysdate)


问:
Get Requsition ID based on PO
In FSCM I am looking to modify the Search view on Add/Update PO page (Main Menu--> Purchasing--> Purchase Orders--> Add/Update POs) to display the Requisition ID associated with the PO in the search results page. The only table I have found that has both PO_ID and REQ_ID is PS_PO_LINE_DISTRIB however unless I use a SELECT DISTINCT clause I will get multiple PO_ID rows when there are more than 1 line on a PO.

Within Purchase Order Inquiry you can see the related Requisition ID's related to a PO by clicking on Document Status link inside the Purchase Order inquiry details page.

I started looking at the PeopleCode within the the Purchase Order Inquiry to see how they are linking the PO to a Requisition and it appears to use work tables with related PeopleCode function libraries, but I wasn't able to figure our how they get linked. I am hoping someone else may know the answer to this. Thank you.

答:
I'm on an old version of PeopleSoft (SCM 8.80, Tools 8.51), so your mileage may vary.  I'm assuming you're familiar with App Designer.  If not, comment below and I'll add some details about what I'm clicking on.

Find the name of the Add/Update PO component.

Open the PURCHASE_ORDER component in App Designer.  Now let's find the name of the search record.  Note that there is a different record for the Add Search Record, so if you want to change that too, do all of this for that record as well.

Open the PO_SRCH record, and add the REQ_ID field to it.  Make sure you mark the field as a key.  You should consider saving your modified PO_SRCH under a new name in case you want to be able to revert to vanilla PeopleSoft.  If you do, change the Search Record in the component to your new record name.

We can see that PO_SRCH is a view.  So let's modify the view to pull in REQ_ID from PO_LINE_DISTRIB.  As you mentioned above, there doesn't appear to be another table with both PO_ID and REQ_ID, so you'll have to do a SELECT DISTINCT.

We should do a LEFT OUTER JOIN instead of a standard join because if you do a standard join and you enter a purchase order with no lines and save it, then you'll never be able to retrieve that purchase order in this window.  Since REQ_ID is a key field, we can't have a null, so we have to do the CASE.

One odd thing that I ran into here was building the view now gave me an error about selecting fewer columns in the SQL than I had in my record definition.  I solved it by modifying the view for SQL Server.  I've never had to do that before and I don't know why I had to do it for this specific record.  But anyway, I entered the same SQL under the record's "Microsoft SQL Server" definition.

In the properties of PO_SRCH, we can see that it has a related language record.  If you're only using one language, you can probably get away without changing this, but I'll do it for completeness.  Open PO_SRCHLN.  Now add REQ_ID to it (mark it as a key field like you did above), and save it as PO_SRCHLN2 (I'm saving it under a new name so I don't break anything else that may be using PO_SRCHLN).

Edit the SQL the same was as you did above.  Note: I didn't have to also change the Microsoft SQL Server definition like I did above.  I have no idea why.

Now build PO_SRCHLN2.

Go back to PO_SRCH and change its related language record to PO_SRCHLN2.

Now build PO_SRCH.

Hopefully you didn't get any errors and your search page has the requisition ID in it now.  My system doesn't use requisitions so they're all blank in the example below, but the new field is there.

Title: Get Requsition ID based on PO


问:
Embed two online websites in one HTML page
I am trying to embed two websites in one page like YouTube and Google using div tags and the links in between the div tags....is there any way this could work?</p>

答: Try using Iframes with the links set to your desired pages</p>


答: You're looking for the  tag.

Title: Embed two online websites in one HTML page

Body: I am trying to embed two websites in one page like YouTube and Google using div tags and the links in between the div tags....is there any way this could work?

Body: You're looking for the <iframe> tag.


问:
How to return an object or null in GraphQL?
I have the following schema:

```<code>type User {
    email: String!,
    user_id: String!,
    img: String!,
},

type Query {
    getUser(user_id: String!): User
}
</code>```

The schema reflects the fact that I must return an User object. However, I can not always do this, and sometimes I need to return null. For example, if I make a request to the DB, it will return return object or null (if the user was not found).

In my GraphQL schema, I set the type for a particular field. If I try to return a different type than what I set, I get an error. How do I allow a field to return either an object or null?

答:
According to the spec:

By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL Non‐Null type can be used.

In other words, types in GraphQL are nullable by default. So a field like

```<code>getUser: User
</code>```

may return either a User object or null. A field like

```<code>name: String
</code>```

may return either a String or null. Only by explicitly specifying a field as non-null (in SDL, by appending a ! to the type), can we specify that a field should never return null. For example:

```<code>name: String!
</code>```

It's also important to note that the Promise returned in your resolver must resolve to either null or undefined in order to be coerced into a null value. In other words, if you return an empty object ({}), an empty array ([]) or some other value, GraphQL will treat this as you returning an object and not a null value!

In your schema, the email field on User is String!, meaning it cannot resolve to null. If you run a query like

```<code>query {
  getUser(user_id: "1") {
    email
  }
}
</code>```

and the resolver for getUser returns an empty object ({}), GraphQL will attempt to resolve email, return null for it and blow up because email is not supposed to be null! If, however, getUser resolves to null, none of the child fields will be resolved and you will not get any error.

Body:
I have the following schema:

type User {
    email: String!,
    user_id: String!,
    img: String!,
},

type Query {
    getUser(user_id: String!): User
}

The schema reflects the fact that I must return an User object. However, I can not always do this, and sometimes I need to return null. For example, if I make a request to the DB, it will return return object or null (if the user was not found).

In my GraphQL schema, I set the type for a particular field. If I try to return a different type than what I set, I get an error. How do I allow a field to return either an object or null?

Body:
According to the spec:

By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL Non‐Null type can be used.

In other words, types in GraphQL are nullable by default. So a field like

getUser: User

may return either a User object or null. A field like

name: String

may return either a String or null. Only by explicitly specifying a field as non-null (in SDL, by appending a ! to the type), can we specify that a field should never return null. For example:

name: String!

It's also important to note that the Promise returned in your resolver must resolve to either null or undefined in order to be coerced into a null value. In other words, if you return an empty object ({}), an empty array ([]) or some other value, GraphQL will treat this as you returning an object and not a null value!

In your schema, the email field on User is String!, meaning it cannot resolve to null. If you run a query like

query {
  getUser(user_id: "1") {
    email
  }
}

and the resolver for getUser returns an empty object ({}), GraphQL will attempt to resolve email, return null for it and blow up because email is not supposed to be null! If, however, getUser resolves to null, none of the child fields will be resolved and you will not get any error.