问:
The magic of STREAMS in Linux. When to finish?
Today at 5am I read an article about read system call. And things become significantly clear for me.

ssize_t read(int fd, void *buf, size_t count);

The construction of *nix like operation system become  amazing in it's simplicity. File interface for any entity, just ask to write some date from this fd interface into some memory by *buf pointer. All the same for network, files, streams.

But some question appears.
How to distinguish two cases?:
1) Stream is empty need to wait for new data. 2) Stream is closed need to close program.

Here is a scenario:

Reading data from STDIN in loop, this STDIN redirected by pipe.

some text_data appears

just read bite by bite until what EOF in memory, or 0 as result of read call?

How program will understand: wait for a new input, or exit?

This is unclear. In case of endless or continuous streams.

UPD After speak with @Bailey Kocin and reading some docs I have this understanding.  Fix me if I'm wrong.

read holds the program execution and waits for count amount of bites.

When count amount of bites appears read writes it into buf and execution continues.

When stream is closed read returns 0, and it is a signal that program may be finished.

Question Do EOF appears in buf?

UPD2 EOF is a constant that can be in the output of getc function

```<code> while (ch != EOF)     {
    /* display contents of file on screen */
    putchar(ch);

    ch = getc(fp);
 }
</code>```

But in case of read the EOF value dose not appears in a buf. read system call signalize about file ending by returning 0. Instead of writing EOF constant into the data-area, as like ak in case of getc.

EOF is a constant that vary in different systems. And it used for getc.

答:
Let's deal first with your original question.  Note that man 7 pipe should give some useful information on this.

Say we have the standard input redirected to the input side of a descriptor created by a pipe call, as in:

```<code>pipe(p);
// ... fork a child to write to the output side of the pipe ...
dup2(p[0], 0);  // redirect standard input to input side
</code>```

and we call:

```<code>bytes = read(0, buf, 100);
</code>```

First, note that this behaves no differently than simply reading directly from p[0], so we could have just done:

```<code>pipe(p);
// fork child
bytes = read(p[0], buf, 100);
</code>```

Then, there are essentially three cases:

If there are bytes in the pipe (i.e., at least one byte has been written but not yet read), then the read call will return immediately, and it will return all bytes available up to a maximum of 100 bytes.  The return value will be the number of bytes read, and it will always be a positive number between 1 and 100.

If the pipe is empty (no bytes) and the output side has been closed, the buffer won't be touched, and the call will return immediately with return value of 0.

Otherwise, the read call will block until something is written to the pipe or the output side is closed, and then the read call will return immediately using the rules in cases 1 and 2.

So, if a read() call returns 0, that means the end-of-file was reached, and no more bytes are expected.  Waiting for additional data happens automatically, and after the wait, you'll either get data (positive return value) or an end-of-file signal (zero return value).  In the special case that another process writes some bytes and then immediately closes (the output side of) the pipe, the next read() call will return a positive value up to the specified count.  Subsequent read() calls will continue to return positive values as long as there's more data to read.  When the data are exhausted, the read() call will return 0 (since the pipe is closed).

On Linux, the above is always true for pipes and any positive count.  There can be differences for things other than pipes.  Also, if the count is 0, the read() call will always return immediately with return value 0.  Note that, if you are trying to write code that runs on platforms other than Linux, you may have to be more careful.  An implementation is allowed to return a non-zero number of bytes less than the number requested, even if more bytes are available in the pipe -- this might mean that there's an implementation-defined limit (so you never get more than 4096 bytes, no matter how many you request, for example) or that this implementation-defined limit changes from call to call (so if you request bytes over a page boundary in a kernel buffer, you only get the end of the page or something).  On Linux, there's no limit -- the read call will always return everything available up to count, no matter how big count is.

Anyway, the idea is that something like the following code should reliably read all bytes from a pipe until the output side is closed, even on platforms other than Linux:

```<code>#define _GNU_SOURCE 1
#include <errno.h>
#include <unistd.h>

/* ... */

    while ((count = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)))) > 0) {
        // process "count" bytes in "buffer"
    }
    if (count == -1) {
        // handle error
    }
    // otherwise, end of data reached
</code>```

If the pipe is never closed ("endless" or "continuous" stream), the while loop will run forever because read will block until it can return a non-zero byte count.

Note that the pipe can also be put into a non-blocking mode which changes the behavior substantially, but the above is the default blocking mode behavior.

With respect to your UPD questions:

Yes, read holds the program execution until data is available, but NO, it doesn't necessarily wait for count bytes.  It will wait for a least one non-empty write to the pipe, and that will wake the process; when the process gets a chance to run, it will return whatever's available up to but not necessarily equal to count bytes.  Usually, this means that if another process writes 5 bytes, a blocked read(fd, buffer, 100) call will return 5 and execution will continue.  Yes, if read returns 0, it's a signal that there's no more data to be read and the write side of the pipe has been closed (so no more data will ever be available).  No, an EOF value does not appear in the buffer.  Only bytes read will appear there, and the buffer won't be touched when read() returns 0, so it'll contain whatever was there before the read() call.

With respect to your UPD2 comment:

Yes, on Linux, EOF is a constant equal to the integer -1.  (Technically, according to the C99 standard, it is an integer constant equal to a negative value; maybe someone knows of a platform where it's something other than -1.)  This constant is not used by the read() interface, and it is certainly not written into the buffer.  While read() returns -1 in case of error, it would be considered bad practice to compare the return value from read() with EOF instead of -1.  As you note, the EOF value is really only used for C library functions like getc() and getchar() to distinguish the end of file from a successfully read character.

Body:
Today at 5am I read an article about read system call. And things become significantly clear for me.

ssize_t read(int fd, void *buf, size_t count);

The construction of *nix like operation system become  amazing in it's simplicity. File interface for any entity, just ask to write some date from this fd interface into some memory by *buf pointer. All the same for network, files, streams.

But some question appears.
How to distinguish two cases?:
1) Stream is empty need to wait for new data. 2) Stream is closed need to close program.

Here is a scenario:

Reading data from STDIN in loop, this STDIN redirected by pipe.

some text_data appears

just read bite by bite until what EOF in memory, or 0 as result of read call?

How program will understand: wait for a new input, or exit?

This is unclear. In case of endless or continuous streams.

UPD After speak with @Bailey Kocin and reading some docs I have this understanding.  Fix me if I'm wrong.

read holds the program execution and waits for count amount of bites.

When count amount of bites appears read writes it into buf and execution continues.

When stream is closed read returns 0, and it is a signal that program may be finished.

Question Do EOF appears in buf?

UPD2 EOF is a constant that can be in the output of getc function

 while (ch != EOF)     {
    /* display contents of file on screen */
    putchar(ch);

    ch = getc(fp);
 }

But in case of read the EOF value dose not appears in a buf. read system call signalize about file ending by returning 0. Instead of writing EOF constant into the data-area, as like ak in case of getc.

EOF is a constant that vary in different systems. And it used for getc.

Body:
Let's deal first with your original question.  Note that man 7 pipe should give some useful information on this.

Say we have the standard input redirected to the input side of a descriptor created by a pipe call, as in:

pipe(p);
// ... fork a child to write to the output side of the pipe ...
dup2(p[0], 0);  // redirect standard input to input side

and we call:

bytes = read(0, buf, 100);

First, note that this behaves no differently than simply reading directly from p[0], so we could have just done:

pipe(p);
// fork child
bytes = read(p[0], buf, 100);

Then, there are essentially three cases:

If there are bytes in the pipe (i.e., at least one byte has been written but not yet read), then the read call will return immediately, and it will return all bytes available up to a maximum of 100 bytes.  The return value will be the number of bytes read, and it will always be a positive number between 1 and 100.

If the pipe is empty (no bytes) and the output side has been closed, the buffer won't be touched, and the call will return immediately with return value of 0.

Otherwise, the read call will block until something is written to the pipe or the output side is closed, and then the read call will return immediately using the rules in cases 1 and 2.

So, if a read() call returns 0, that means the end-of-file was reached, and no more bytes are expected.  Waiting for additional data happens automatically, and after the wait, you'll either get data (positive return value) or an end-of-file signal (zero return value).  In the special case that another process writes some bytes and then immediately closes (the output side of) the pipe, the next read() call will return a positive value up to the specified count.  Subsequent read() calls will continue to return positive values as long as there's more data to read.  When the data are exhausted, the read() call will return 0 (since the pipe is closed).

On Linux, the above is always true for pipes and any positive count.  There can be differences for things other than pipes.  Also, if the count is 0, the read() call will always return immediately with return value 0.  Note that, if you are trying to write code that runs on platforms other than Linux, you may have to be more careful.  An implementation is allowed to return a non-zero number of bytes less than the number requested, even if more bytes are available in the pipe -- this might mean that there's an implementation-defined limit (so you never get more than 4096 bytes, no matter how many you request, for example) or that this implementation-defined limit changes from call to call (so if you request bytes over a page boundary in a kernel buffer, you only get the end of the page or something).  On Linux, there's no limit -- the read call will always return everything available up to count, no matter how big count is.

Anyway, the idea is that something like the following code should reliably read all bytes from a pipe until the output side is closed, even on platforms other than Linux:

#define _GNU_SOURCE 1
#include <errno.h>
#include <unistd.h>

/* ... */

    while ((count = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)))) > 0) {
        // process "count" bytes in "buffer"
    }
    if (count == -1) {
        // handle error
    }
    // otherwise, end of data reached

If the pipe is never closed ("endless" or "continuous" stream), the while loop will run forever because read will block until it can return a non-zero byte count.

Note that the pipe can also be put into a non-blocking mode which changes the behavior substantially, but the above is the default blocking mode behavior.

With respect to your UPD questions:

Yes, read holds the program execution until data is available, but NO, it doesn't necessarily wait for count bytes.  It will wait for a least one non-empty write to the pipe, and that will wake the process; when the process gets a chance to run, it will return whatever's available up to but not necessarily equal to count bytes.  Usually, this means that if another process writes 5 bytes, a blocked read(fd, buffer, 100) call will return 5 and execution will continue.  Yes, if read returns 0, it's a signal that there's no more data to be read and the write side of the pipe has been closed (so no more data will ever be available).  No, an EOF value does not appear in the buffer.  Only bytes read will appear there, and the buffer won't be touched when read() returns 0, so it'll contain whatever was there before the read() call.

With respect to your UPD2 comment:

Yes, on Linux, EOF is a constant equal to the integer -1.  (Technically, according to the C99 standard, it is an integer constant equal to a negative value; maybe someone knows of a platform where it's something other than -1.)  This constant is not used by the read() interface, and it is certainly not written into the buffer.  While read() returns -1 in case of error, it would be considered bad practice to compare the return value from read() with EOF instead of -1.  As you note, the EOF value is really only used for C library functions like getc() and getchar() to distinguish the end of file from a successfully read character.


来源: stackexchange

问:
PHP Function "... Days Ago" In "While Loop" Doesn't Work
I want to add a description of the posting time for each of my articles on the homepage. So there are some content published at different times, and I want to make it appear clearer by adding a description of the date of publication.

But I found a complicated problem. In my code example below, it produces the wrong time. I have tried several times but failed. Can I still fix this with this code or maybe there is another code that is more perfect.

PHP CODE:

```<code>$sql = $DBcon->query("SELECT content, post_date FROM article");
$row = $sql->fetch_array();
$post_date = $row['post_date']; // 2019-06-01 16:29:07

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

do {
// .......

echo $row['content'];
echo time_elapsed_string( $post_date );

// .......
} while ($row = $sql->fetch_array());
</code>```

The above code produces the same time for all content. Even though my content was made at different times. Obviously this is something wrong. So how do you fix it?

答:
Try following way:

```<code>   while($row = $result->fetch_assoc()) {
        echo $row['content'];
    }
</code>```

For Loop: You need to use a condition in while loop.
Here is 5 example about while loop. Check this out https://www.w3schools.com/php/php_looping.asp

ContentLicense: CC BY-SA 4.0

Body:
I want to add a description of the posting time for each of my articles on the homepage. So there are some content published at different times, and I want to make it appear clearer by adding a description of the date of publication.

But I found a complicated problem. In my code example below, it produces the wrong time. I have tried several times but failed. Can I still fix this with this code or maybe there is another code that is more perfect.

PHP CODE:

$sql = $DBcon->query("SELECT content, post_date FROM article");
$row = $sql->fetch_array();
$post_date = $row['post_date']; // 2019-06-01 16:29:07

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

do {
// .......

echo $row['content'];
echo time_elapsed_string( $post_date );

// .......
} while ($row = $sql->fetch_array());

The above code produces the same time for all content. Even though my content was made at different times. Obviously this is something wrong. So how do you fix it?

Body:
Try following way:

   while($row = $result->fetch_assoc()) {
        echo $row['content'];
    }

For Loop: You need to use a condition in while loop.
Here is 5 example about while loop. Check this out https://www.w3schools.com/php/php_looping.asp


问:
JQuery select a variable by passing a text string of its name
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

```<code>var test = "xxx";
</code>```

I'm thinking I could do something like this, but it won't work:

```<code>  alert($("#test"));
</code>```

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..

答:
What you are asking is best done with JavaScript objects, e.g.:

```<code>var obj = { test: "xxx" };
for(key in obj) {
    alert(key);  // "test"
    alert(obj.key); // "xxx"
}
</code>```

You can do something like this, though I really don't see the point:

```<code>var obj = { foo: "xxx" };
for(key in obj) {
    alert($("#" + key).length); // 1
}

<input id="foo"/>
</code>```

http://jsfiddle.net/J4hC8/

ContentLicense: CC BY-SA 3.0

Body:
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

var test = "xxx";

I'm thinking I could do something like this, but it won't work:

  alert($("#test"));

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..

Body:
What you are asking is best done with JavaScript objects, e.g.:

var obj = { test: "xxx" };
for(key in obj) {
    alert(key);  // "test"
    alert(obj.key); // "xxx"
}

You can do something like this, though I really don't see the point:

var obj = { foo: "xxx" };
for(key in obj) {
    alert($("#" + key).length); // 1
}

<input id="foo"/>

http://jsfiddle.net/J4hC8/


问:
Statement level trigger to enforce a constraint
I am trying to implement a statement level trigger to enforce the following "An applicant cannot apply for more than two positions in one day".

I am able to enforce it using a row level trigger (as shown below) but I have no clue how to do so using a statement level trigger when I can't use :NEW or :OLD.

I know there are alternatives to using a trigger but I am revising for my exam that would have a similar question so I would appreciate any help.

```<code>CREATE TABLE APPLIES(
anumber     NUMBER(6)   NOT NULL,  /* applicant number */
pnumber     NUMBER(8)   NOT NULL, /* position number */
appDate     DATE        NOT NULL, /* application date*/
CONSTRAINT APPLIES_pkey PRIMARY KEY(anumber, pnumber)
);

CREATE OR REPLACE TRIGGER app_trigger
BEFORE INSERT ON APPLIES
FOR EACH ROW
DECLARE
  counter NUMBER;
BEGIN
  SELECT COUNT(*) INTO counter
  FROM APPLIES
  WHERE anumber = :NEW.anumber
  AND to_char(appDate, 'DD-MON-YYYY') = to_char(:NEW.appDate, 'DD-MON-YYYY');

  IF counter = 2 THEN
      RAISE_APPLICATION_ERROR(-20001, 'error msg');
  END IF;
END;
</code>```

答:
Your rule involves more than one row at the same time. So you cannot use a FOR ROW LEVEL trigger: querying on APPLIES as you propose would hurl ORA-04091: table is mutating exception.

So, AFTER statement it is.

```<code>CREATE OR REPLACE TRIGGER app_trigger
AFTER INSERT OR UPDATE ON APPLIES
DECLARE
  cursor c_cnt is
    SELECT 1 INTO counter
    FROM APPLIES
    group by anumber, trunc(appDate) having count(*) > 2;
  dummy number;
BEGIN
  open c_cnt;
  fetch c_cnt in dummy;
  if c_cnt%found then
      close c_cnt;
      RAISE_APPLICATION_ERROR(-20001, 'error msg');
  end if;
  close c_cnt;
END;
</code>```

Obviously, querying the whole table will be inefficient at scale. (One of the reasons why triggers are not recommended for this sort of thing). So this is a situation in which we might want to use a compound trigger (assuming we're on 11g or later).

Body:
I am trying to implement a statement level trigger to enforce the following "An applicant cannot apply for more than two positions in one day".

I am able to enforce it using a row level trigger (as shown below) but I have no clue how to do so using a statement level trigger when I can't use :NEW or :OLD.

I know there are alternatives to using a trigger but I am revising for my exam that would have a similar question so I would appreciate any help.

CREATE TABLE APPLIES(
anumber     NUMBER(6)   NOT NULL,  /* applicant number */
pnumber     NUMBER(8)   NOT NULL, /* position number */
appDate     DATE        NOT NULL, /* application date*/
CONSTRAINT APPLIES_pkey PRIMARY KEY(anumber, pnumber)
);

CREATE OR REPLACE TRIGGER app_trigger
BEFORE INSERT ON APPLIES
FOR EACH ROW
DECLARE
  counter NUMBER;
BEGIN
  SELECT COUNT(*) INTO counter
  FROM APPLIES
  WHERE anumber = :NEW.anumber
  AND to_char(appDate, 'DD-MON-YYYY') = to_char(:NEW.appDate, 'DD-MON-YYYY');

  IF counter = 2 THEN
      RAISE_APPLICATION_ERROR(-20001, 'error msg');
  END IF;
END;

Body:
Your rule involves more than one row at the same time. So you cannot use a FOR ROW LEVEL trigger: querying on APPLIES as you propose would hurl ORA-04091: table is mutating exception.

So, AFTER statement it is.

CREATE OR REPLACE TRIGGER app_trigger
AFTER INSERT OR UPDATE ON APPLIES
DECLARE
  cursor c_cnt is
    SELECT 1 INTO counter
    FROM APPLIES
    group by anumber, trunc(appDate) having count(*) > 2;
  dummy number;
BEGIN
  open c_cnt;
  fetch c_cnt in dummy;
  if c_cnt%found then
      close c_cnt;
      RAISE_APPLICATION_ERROR(-20001, 'error msg');
  end if;
  close c_cnt;
END;

Obviously, querying the whole table will be inefficient at scale. (One of the reasons why triggers are not recommended for this sort of thing). So this is a situation in which we might want to use a compound trigger (assuming we're on 11g or later).


问:
Byte-buddy and cglib not available in Spock test
I started playing around with Spock testing framework and my build.gradle dependencies section looks like this:

```<code>dependencies {
    testCompile "org.spockframework:spock-core:1.3-groovy-2.5"
}
</code>```

I have a (useless) Spock test that requires creation of a stub:

```<code>def 'A test that will fail'() {
    given: ''
    def random = Stub(Random)
}
</code>```

When launched, the test fails with the given error:

CannotCreateMockException: Cannot create mock for class java.util.Random. Mocking of non-interface types requires a code generation library. Please put an up-to-date version of byte-buddy or cglib-nodep on the class path.

This error is mentioned in Spock documentation and it's caused by cglib or byte-buddy not being available at runtime.

Considering that spock-core's pom lists both byte-buddy and cglib as compile dependencies, why are they not retained at runtime? In other words, why do we need to explicitly add the following runtime dependency to our build.gradle file?

```<code>testRuntime "net.bytebuddy:byte-buddy:1.9.3"
</code>```

答:
They are optional dependencies, so you need to include them if you want that functionality

https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html

Body:
I started playing around with Spock testing framework and my build.gradle dependencies section looks like this:

dependencies {
    testCompile "org.spockframework:spock-core:1.3-groovy-2.5"
}

I have a (useless) Spock test that requires creation of a stub:

def 'A test that will fail'() {
    given: ''
    def random = Stub(Random)
}

When launched, the test fails with the given error:

CannotCreateMockException: Cannot create mock for class java.util.Random. Mocking of non-interface types requires a code generation library. Please put an up-to-date version of byte-buddy or cglib-nodep on the class path.

This error is mentioned in Spock documentation and it's caused by cglib or byte-buddy not being available at runtime.

Considering that spock-core's pom lists both byte-buddy and cglib as compile dependencies, why are they not retained at runtime? In other words, why do we need to explicitly add the following runtime dependency to our build.gradle file?

testRuntime "net.bytebuddy:byte-buddy:1.9.3"


问:
Cannot be opened because it is version 852. this server supports version 782 and earlier
I am using Visual Studio 2017 and SQL Server 2014. While attaching a database file to Visual Studio, I get this error:

""

After upgrading the file I used this connection string

```<code><connectionStrings>
    <add name="con"
         connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\binaaelmamorra.mdf;Integrated Security=True;Connect Timeout=30"/>
</connectionStrings>
</code>```

It's working fine on my machine, but on the client machine, an error pops up saying

Cannot be opened because it is version 852. This server supports version 782 and earlier

Though I installed SQL Server 2016 local DB on the client side, I still can't get rid of it.

My second question is: what is the current instance of SQL Server to which the database file is not compatible?

答:
In my case I had once updated the database with entity framework code first technique using the latest version of Visual Studio then I tried to run the project with an older version and it showed this exception.
I fixed it by just removing the database and re-running the command Update-Database -verbose -verbose flag is so you can see what commands were executed.

Body:
I am using Visual Studio 2017 and SQL Server 2014. While attaching a database file to Visual Studio, I get this error:

""

After upgrading the file I used this connection string

<connectionStrings>
    <add name="con"
         connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\binaaelmamorra.mdf;Integrated Security=True;Connect Timeout=30"/>
</connectionStrings>

It's working fine on my machine, but on the client machine, an error pops up saying

Cannot be opened because it is version 852. This server supports version 782 and earlier

Though I installed SQL Server 2016 local DB on the client side, I still can't get rid of it.

My second question is: what is the current instance of SQL Server to which the database file is not compatible?


问:
How to remove duplicate elements from an array in Swift 5?
I have an array of custom objects, a.k.a users, and some of them are duplicates.

How can I make sure there is only one of each element? No duplicates.

Also, what's the most efficient way?

```<code>var users: UserModel = [UserModel]()
</code>```

答:
Most efficient way if you don’t care about maintaining the original order in the array</p>

```<code>let uniqueUsers = Array(Set(users))
</code>```

Body:
I have an array of custom objects, a.k.a users, and some of them are duplicates.

How can I make sure there is only one of each element? No duplicates.

Also, what's the most efficient way?

var users: UserModel = [UserModel]()

Body:
Most efficient way if you don’t care about maintaining the original order in the array

let uniqueUsers = Array(Set(users))


问:
Logging using Crashlytics
I am using multiple Crashlytics.log() commands, for example:

```<code>Crashlytics.log("This is message 1");
Crashlytics.log("This is message 2");
</code>```

But when there is a crash in the dashboard I can only see "This is message 1" but not "This is message 2". Does Crashlytics log only show the first log not any subsequent log after that or am I doing anything wrong? How can I use multiple Crashlytics.log() commands.

答:
According to the Crashlytics docs:

To make sure that sending crash reports has the smallest impact on
  your user’s devices, Crashlytics logs have a maximum size of 64 KB.
  When a log exceeds 64 KB, the earliest logged values will be dropped
  in order to maintain this threshold.

Your first message will be dropped if the second message plus the first message exceed 64KB.

Title: Logging using Crashlytics

Body:
I am using multiple Crashlytics.log() commands, for example:

Crashlytics.log("This is message 1");
Crashlytics.log("This is message 2");

But when there is a crash in the dashboard I can only see "This is message 1" but not "This is message 2". Does Crashlytics log only show the first log not any subsequent log after that or am I doing anything wrong? How can I use multiple Crashlytics.log() commands.


问:
Ylim max to change dynamically with a variable, while min is set to 0 in R
I would like my graphs to start at y= 0, but I would like the maximum to change with a multiple of the data, or somehow otherwise zoom out dynamically. I have 34 charts in this set with various ymax.

I have tried scale_y_continuous and coord_cartesian but when I try to put in the expand = expand_scale(mult = 2) that works for getting my maximum to change dynamically, but then the graphs start to start at negative numbers, and I want them to start at 0.

```<code>title<- c(
  "Carangidae",
  "Atlantic cutlassfish",
  "Lizardfish",
  "Sharks",
  "Mackerel")
</code>```

```<code>#DATA#
biomass<- structure(list(timestep = structure(c(10957, 10988, 11017, 11048,
11078, 11109, 11139, 11170, 11201, 11231, 11262, 11292), class = "Date"),
    bio_pre_Carangidae = c(0.01105, 0.0199, 0.017,
    0.01018, 0.0119, 0.0101, 0.009874, 0.009507,
    0.009019, 0.00843, 0.00841, 0.00805), bio_obs_Carangidae = c(NA,
    NA, NA, NA, NA, 0.00239, NA, NA, NA, NA, NA, NA), bio_pre_Atl_cutlassfish = c(0.078,
    0.069, 0.067, 0.06872, 0.0729, 0.0769,
    0.0775, 0.075, 0.0743, 0.072, 0.071,
    0.069), bio_obs_Atl_cutlassfish = c(NA, NA, NA, NA, NA,
    0.0325, NA, NA, NA, NA, NA, NA), bio_pre_lizardfish = c(0.0635,
    0.062, 0.057, 0.0536, 0.0505, 0.0604,
    0.0627, 0.068, 0.0695, 0.066, 0.0623,
    0.0598), bio_obs_lizardfish = c(NA, NA, NA, NA, NA, 0.037,
    NA, NA, NA, NA, NA, NA), bio_pre_sharks = c(0.025, 0.0155,
    0.0148, 0.0135, 0.01379, 0.01398, 0.014,
    0.0139, 0.0136, 0.0132, 0.0126, 0.011),
    bio_obs_sharks = c(NA, NA, NA, NA, NA, 0.003, NA, NA,
    NA, NA, NA, NA), bio_pre_mackerel = c(0.0567, 0.0459,
    0.0384, 0.03, 0.0328, 0.0336, 0.0299,
    0.0296, 0.02343, 0.02713, 0.0239, 0.019
    ), bio_obs_mackerel = c(NA, NA, NA, NA, NA, 0.055, NA,
    NA, NA, NA, NA, NA)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -12L))
</code>```

This is my function:

```<code>function (biomass, .var1, .var2, .var3) {
    p <- ggplot(biomass, aes(x = timestep)) +
geom_line(aes(y = .data[[.var1]], linetype = "Predicted")) + geom_point(size = 3, aes(y = .data[[.var2]], shape = "Observed")) +
ggtitle(paste0(.var3)) +
ylab(expression("biomass" ~ (t/km^2))) +
theme_classic() +
scale_y_continuous(limits = c(0, NA), expand = expand_scale(mult = 2))+

  ###This is the portion where I cannot figure out how to set ymin = 0 and then ymax to 2* the maximum value of a dataset.##

theme(legend.position = "right") +
theme(axis.ticks = element_line(size = 1), axis.ticks.length = unit(0.25, "cm"))
    return(p)
}

## create two separate name vectors
var1_names <- colnames(biomass)[grepl("^bio_pre", colnames(biomass))]
var2_names <- colnames(biomass)[grepl("^bio_obs", colnames(biomass))]
var3_names <- title

## loop through two vectors simultaneously and save result in a list
# ..1 = var1_names, ..2 = var2_names
my_plot_b <- pmap(list(var1_names, var2_names, var3_names), ~ my_bio_plot(biomass, ..1, ..2, ..3))

## merge plots together
# https://cran.r-project.org/web/packages/cowplot/
# install.packages("cowplot", dependencies = TRUE)
dev.new(title = "Model Fit Biomass",
        width = 12,
        height = 6,
        noRStudioGD = TRUE
)
print(my_plot_b)
</code>```

I can manage to get EITHER a set ymin=0 (a) OR a dynamic ymax (b) but cannot manage to get both.

a

b

答:
How about this? Seems to work on your data.

Define the max for each chart at the top of your function:

```<code>my_bio_plot <-  function (biomass, .var1, .var2, .var3) {
  max_y = 2.0 * max(biomass[[.var1]])
  ...
  scale_y_continuous(limits = c(0, max_y)) +
  ...
</code>```

This seems to create the requested output, with min y = 0 and max y = 2 * max y in data.

Body:
I would like my graphs to start at y= 0, but I would like the maximum to change with a multiple of the data, or somehow otherwise zoom out dynamically. I have 34 charts in this set with various ymax.

I have tried scale_y_continuous and coord_cartesian but when I try to put in the expand = expand_scale(mult = 2) that works for getting my maximum to change dynamically, but then the graphs start to start at negative numbers, and I want them to start at 0.

title<- c(
  "Carangidae",
  "Atlantic cutlassfish",
  "Lizardfish",
  "Sharks",
  "Mackerel")

#DATA#
biomass<- structure(list(timestep = structure(c(10957, 10988, 11017, 11048,
11078, 11109, 11139, 11170, 11201, 11231, 11262, 11292), class = "Date"),
    bio_pre_Carangidae = c(0.01105, 0.0199, 0.017,
    0.01018, 0.0119, 0.0101, 0.009874, 0.009507,
    0.009019, 0.00843, 0.00841, 0.00805), bio_obs_Carangidae = c(NA,
    NA, NA, NA, NA, 0.00239, NA, NA, NA, NA, NA, NA), bio_pre_Atl_cutlassfish = c(0.078,
    0.069, 0.067, 0.06872, 0.0729, 0.0769,
    0.0775, 0.075, 0.0743, 0.072, 0.071,
    0.069), bio_obs_Atl_cutlassfish = c(NA, NA, NA, NA, NA,
    0.0325, NA, NA, NA, NA, NA, NA), bio_pre_lizardfish = c(0.0635,
    0.062, 0.057, 0.0536, 0.0505, 0.0604,
    0.0627, 0.068, 0.0695, 0.066, 0.0623,
    0.0598), bio_obs_lizardfish = c(NA, NA, NA, NA, NA, 0.037,
    NA, NA, NA, NA, NA, NA), bio_pre_sharks = c(0.025, 0.0155,
    0.0148, 0.0135, 0.01379, 0.01398, 0.014,
    0.0139, 0.0136, 0.0132, 0.0126, 0.011),
    bio_obs_sharks = c(NA, NA, NA, NA, NA, 0.003, NA, NA,
    NA, NA, NA, NA), bio_pre_mackerel = c(0.0567, 0.0459,
    0.0384, 0.03, 0.0328, 0.0336, 0.0299,
    0.0296, 0.02343, 0.02713, 0.0239, 0.019
    ), bio_obs_mackerel = c(NA, NA, NA, NA, NA, 0.055, NA,
    NA, NA, NA, NA, NA)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -12L))

This is my function:

function (biomass, .var1, .var2, .var3) {
    p <- ggplot(biomass, aes(x = timestep)) +
geom_line(aes(y = .data[[.var1]], linetype = "Predicted")) + geom_point(size = 3, aes(y = .data[[.var2]], shape = "Observed")) +
ggtitle(paste0(.var3)) +
ylab(expression("biomass" ~ (t/km^2))) +
theme_classic() +
scale_y_continuous(limits = c(0, NA), expand = expand_scale(mult = 2))+

  ###This is the portion where I cannot figure out how to set ymin = 0 and then ymax to 2* the maximum value of a dataset.##

theme(legend.position = "right") +
theme(axis.ticks = element_line(size = 1), axis.ticks.length = unit(0.25, "cm"))
    return(p)
}

## create two separate name vectors
var1_names <- colnames(biomass)[grepl("^bio_pre", colnames(biomass))]
var2_names <- colnames(biomass)[grepl("^bio_obs", colnames(biomass))]
var3_names <- title

## loop through two vectors simultaneously and save result in a list
# ..1 = var1_names, ..2 = var2_names
my_plot_b <- pmap(list(var1_names, var2_names, var3_names), ~ my_bio_plot(biomass, ..1, ..2, ..3))

## merge plots together
# https://cran.r-project.org/web/packages/cowplot/
# install.packages("cowplot", dependencies = TRUE)
dev.new(title = "Model Fit Biomass",
        width = 12,
        height = 6,
        noRStudioGD = TRUE
)
print(my_plot_b)

I can manage to get EITHER a set ymin=0 (a) OR a dynamic ymax (b) but cannot manage to get both.

a

b

Body:
How about this? Seems to work on your data.

Define the max for each chart at the top of your function:

my_bio_plot <-  function (biomass, .var1, .var2, .var3) {
  max_y = 2.0 * max(biomass[[.var1]])
  ...
  scale_y_continuous(limits = c(0, max_y)) +
  ...

This seems to create the requested output, with min y = 0 and max y = 2 * max y in data.


问:
How to make a simple JavaScript call from a PHP function?
I have a simple PHP function that is being called when a form is submitted:

```<code>function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}
</code>```

What I need is to be able to do a simple Google Analytics call like this:

```<code>_gaq.push(['_trackPageview', 'virtual/formSubmit']);
</code>```

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?

答:
Do you know that JavaScript is running in the client's browser while PHP is running on the server?

Anyway, now you do. So that should answer your question.

Simply echo ".

Body:
I have a simple PHP function that is being called when a form is submitted:

function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}

What I need is to be able to do a simple Google Analytics call like this:

_gaq.push(['_trackPageview', 'virtual/formSubmit']);

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?

Body:
Do you know that JavaScript is running in the client's browser while PHP is running on the server?

Anyway, now you do. So that should answer your question.

Simply echo <script type="text/javascript">yourJsCodeHere</script>".


问:
Displaying a BLOB file(An Image) gotten from a guzzle request
I was successfully able to get an image(which is stored as a BLOB file) from an API endpoint in guzzle, but I am having issues displaying this BLOB file as an image

I have tried several PHP functions for manipulating and converting a BLOB file to an image but all has been abortive.

```<code>after sending the request to my guzzle trait, I decided to var_dump the result to be sure that it was successful

    $userid = $_COOKIE['id'];

    $url = 'users/image/'.$userid;

    $requestResult = $this->sendGetWithHeader('users/image/'.$userid);

    $result = $requestResult->getBody()->read(1024);

    //$res = file_get_contents($result);

    // fopen($result, 0);

    var_dump($result);

    echo "<hr>";

    var_dump($requestResult);

    // $code = $requestResult->getStatusCode();
    // var_dump($code);
</code>```

My expected result is an image file but the actual is still the raw BLOB file gotten from my Guzzle request

string(1024) "����JFIF���              ��V�"��6 ���UG_ks1��r�[�% ��JMd�CL,��8�Q�B�yoA��g�p�-�a�f� D �)8@�.)ɠ� �yea@4��ԃ(��t��Ew��մPV'J��R��u������Ju��U ��ԥ��zѩaė��ya$�2�C�Sa�R$�4� ���� 2t��$��L�D���R�$�ґ-&RVdm��IDq)Jc�"'9�;/ �sb{��Z�r�̮��Q_MR=5�Gt���ddA�6�Fa�L���JGi�kh�d�FA�%(�$� �����.�� H�)��-BL������h|#���WW)݋r�"V[V2˚:��j��˩�>��-$��I�Y�@%dRL(K�(�-�m�I�t��R�JV@�I&JR��0����O2��d�-e@5�2}�2�D'��,Bע��{��!�k�Uw�2ʶ�]cAD�WPw���$��!�Ғu�X!��(�D%I0i�����Lye XI9) �[Nc����@!�miY,Rkiq(���$����mƬ��y��a����崔͒�t7"����͌ΊJgk Q��Ah�Iq$���ʍA�FmJ���7��AJ�a/�rB�"02A����@�d��J%D� �P�yH���m\ż>�i$��I�(�3jm�542k,��t#��@��@D�F�TJDP" �Z(��7�IZ���h9)$��$�Ԣ�Y� m�D�I�֐4�����Da�%DX�o ���fhh�.�c��aQhcΉ�٠��)��"

答:
Look at this example - https://github.com/andriichuk/php-curl-cookbook#download-file

Use 'sink' option to save file from request:

```<code>use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$imageFilePath = __DIR__ . '/resource/image.jpeg';
$imageFileResource = fopen($imageFilePath, 'w+');

$httpClient = new Client();
$response = $httpClient->get(
    'https://httpbin.org/image/jpeg',
    [
        RequestOptions::SINK => $imageFileResource,
    ]
);

if ($response->getStatusCode() === 200) {
    echo 'The image has been successfully downloaded: ' . $imageFilePath;
}
</code>```

Body:
I was successfully able to get an image(which is stored as a BLOB file) from an API endpoint in guzzle, but I am having issues displaying this BLOB file as an image

I have tried several PHP functions for manipulating and converting a BLOB file to an image but all has been abortive.

after sending the request to my guzzle trait, I decided to var_dump the result to be sure that it was successful

    $userid = $_COOKIE['id'];

    $url = 'users/image/'.$userid;

    $requestResult = $this->sendGetWithHeader('users/image/'.$userid);

    $result = $requestResult->getBody()->read(1024);

    //$res = file_get_contents($result);

    // fopen($result, 0);

    var_dump($result);

    echo "
";

    var_dump($requestResult);

    // $code = $requestResult->getStatusCode();
    // var_dump($code);

My expected result is an image file but the actual is still the raw BLOB file gotten from my Guzzle request

string(1024) "����JFIF���              ��V�"��6 ���UG_ks1��r�[�% ��JMd�CL,��8�Q�B�yoA��g�p�-�a�f� D �)8@�.)ɠ� �yea@4��ԃ(��t��Ew��մPV'J��R��u������Ju��U ��ԥ��zѩaė��ya$�2�C�Sa�R$�4� ���� 2t��$��L�D���R�$�ґ-&RVdm��IDq)Jc�"'9�;/ �sb{��Z�r�̮��Q_MR=5�Gt���ddA�6�Fa�L���JGi�kh�d�FA�%(�$� �����.�� H�)��-BL������h|#���WW)݋r�"V[V2˚:��j��˩�>��-$��I�Y�@%dRL(K�(�-�m�I�t��R�JV@�I&JR��0����O2��d�-e@5�2}�2�D'��,Bע��{��!�k�Uw�2ʶ�]cAD�WPw���$��!�Ғu�X!��(�D%I0i�����Lye XI9) �[Nc����@!�miY,Rkiq(���$����mƬ��y��a����崔͒�t7"����͌ΊJgk Q��Ah�Iq$���ʍA�FmJ���7��AJ�a/�rB�"02A����@�d��J%D� �P�yH���m\ż>�i$��I�(�3jm�542k,��t#��@��@D�F�TJDP" �Z(��7�IZ���h9)$��$�Ԣ�Y� m�D�I�֐4�����Da�%DX�o ���fhh�.�c��aQhcΉ�٠��)��"

Body:
Look at this example - https://github.com/andriichuk/php-curl-cookbook#download-file

Use 'sink' option to save file from request:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$imageFilePath = __DIR__ . '/resource/image.jpeg';
$imageFileResource = fopen($imageFilePath, 'w+');

$httpClient = new Client();
$response = $httpClient->get(
    'https://httpbin.org/image/jpeg',
    [
        RequestOptions::SINK => $imageFileResource,
    ]
);

if ($response->getStatusCode() === 200) {
    echo 'The image has been successfully downloaded: ' . $imageFilePath;
}


问:
Condense Array to Number
I'm trying to solve a problem for my homework but im stuck.

Here is the task:

Write a program to read an array of integers and condense them by summing adjacent couples of elements until a single integer is obtained. For example, if we have 3 elements {2, 10, 3}, we sum the first two and the second two elements and obtain {2+10, 10+3} = {12, 13}, then we sum again all adjacent elements and obtain {12+13} = {25}.

This is what i've done so far but im stuck and don't know how to continue.

```<code>for (int i = 0; i < arr.length; i++) {
    arr[i] = Integer.parseInt(input[i]);
}

int sum = 0;
int[] condensed = new int [arr.length-1];
System.out.println(condensed.length);

while (condensed.length > 1) {
    for (int i = 0; i < condensed.length; i++) {
        condensed[i] = arr[i] + arr[i+1];
    }
}

if (condensed.length == 1) {
    sum = condensed[0] + condensed[1];
    System.out.println(sum);
}
</code>```

The input is "5 0 4 1 2" and the output should be "35" but I get "4".

答:
Given that you already have your array (int arr[]) or numbers converter from the input, you can contiuously loop through the array from the first element to the one before the last adding that value to the next value and storing them in a temporary array.

You will then replace the value array with the temp array and continue the process until the length of the array is equal to one.

```<code>while (arr.length > 1) {
    int temp[] = new int[arr.length - 1];

    for (int i = 0; i < arr.length - 1; i++) {
        temp[i] = arr[i] + arr[i + 1];
    }

    arr = temp;
}
</code>```

Title: Condense Array to Number

Body:
I'm trying to solve a problem for my homework but im stuck.

Here is the task:

Write a program to read an array of integers and condense them by summing adjacent couples of elements until a single integer is obtained. For example, if we have 3 elements {2, 10, 3}, we sum the first two and the second two elements and obtain {2+10, 10+3} = {12, 13}, then we sum again all adjacent elements and obtain {12+13} = {25}.

This is what i've done so far but im stuck and don't know how to continue.

for (int i = 0; i < arr.length; i++) {
    arr[i] = Integer.parseInt(input[i]);
}

int sum = 0;
int[] condensed = new int [arr.length-1];
System.out.println(condensed.length);

while (condensed.length > 1) {
    for (int i = 0; i < condensed.length; i++) {
        condensed[i] = arr[i] + arr[i+1];
    }
}

if (condensed.length == 1) {
    sum = condensed[0] + condensed[1];
    System.out.println(sum);
}

The input is "5 0 4 1 2" and the output should be "35" but I get "4".

Body:
Given that you already have your array (int arr[]) or numbers converter from the input, you can contiuously loop through the array from the first element to the one before the last adding that value to the next value and storing them in a temporary array.

You will then replace the value array with the temp array and continue the process until the length of the array is equal to one.

while (arr.length > 1) {
    int temp[] = new int[arr.length - 1];

    for (int i = 0; i < arr.length - 1; i++) {
        temp[i] = arr[i] + arr[i + 1];
    }

    arr = temp;
}


问:
"error":"InvalidRegistration" error while sending message to FCM post swift
I'm adapting a working device to device function in order to send push notifications to topics. When I send a push to FcmToken it works perfectly, but when I sent it to a topic I get an "error":"InvalidRegistration"error. Is this registration related to the server key or what registration I'm missing to send with the request?
 Can you see where I'm mistaking?
As always many thanks.

Here is the working function to the fcmToken :

```<code>static func sendPushNotification(to receiverToken: String, title: String, subtitle: String, body: String) {
            let serverKey = firebaseServerKey // AAAA8c3j2...
//            let topic = "/topics/<your topic here>"  // replace it with partnerToken if you want to send a topic
            let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")

        let postParams: [String : Any] = [
                "to": receiverToken,
                "notification": [
//                    "badge" : 1, sendig the badge number, will cause aglitch
                    "body": body,
                    "title": title,
                    "subtitle": subtitle,
                    "sound" : true, // or specify audio name to play
                    "content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
                    "priority": "high"
//                    "click_action" : "", // action when user click notification (categoryIdentifier)
                ],
                "data" : [
                    "data": "ciao",
            ]
                ]

            let request = NSMutableURLRequest(url: url! as URL)
            request.httpMethod = "POST"
        request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            do {
//                request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: JSONSerialization.WritingOptions())
                request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: [.prettyPrinted]) // working
                print("My paramaters: \(postParams)")
            } catch {
                print("Caught an error: \(error)")
            }

            let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
                if let realResponse = response as? HTTPURLResponse {
                    if realResponse.statusCode != 200 {
                        print("Not a 200 response")
                    }
                }

                if let postString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String? {
                    print("POST: \(postString)")
                }
            }

            task.resume()
        }
</code>```

and this is the one for topics:

```<code>    static func sendTopicPushNotification(to topic: String, title: String, subtitle: String, body: String) {
        let serverKey = firebaseServerKey // AAAA8c3j2...
        //            let topic = "/topics/<your topic here>"  // replace it with partnerToken if you want to send a topic
        let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")

        let postParams: [String : Any] = [
            "priority": "high",
            "notification": [
                //                    "badge" : 1, sendig the badge number, will cause aglitch
                "body": body,
                "title": title,
                "subtitle": subtitle,
                "text": "some text",
                "sound" : true, // or specify audio name to play

                //                    "click_action" : "", // action when user click notification (categoryIdentifier)
            ],
            "to" : "topics/Bologna/Shop-promotions"
//            "data" : [
////                "data": "ciao",
//                "body": body,
//                "title": title,
//                "subtitle": subtitle,
//            ]
        ]

        let request = NSMutableURLRequest(url: url! as URL)
//        request.httpMethod = "POST" // error: POST: {"error":"InvalidParameters: Bad topic or filter provided"}
       request.httpMethod = "POST"
        request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

        do {
            //                request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: JSONSerialization.WritingOptions())
            request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: [.prettyPrinted]) // working
            print("sendTopicPushNotification : My paramaters: \(postParams)")
        } catch {
            print("sendTopicPushNotification : Caught an error: \(error)")
        }

        let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            if let realResponse = response as? HTTPURLResponse {
                if realResponse.statusCode != 200 {
                    print("sendTopicPushNotification : Not a 200 response : \(realResponse)")
                }
                print("sendTopicPushNotification : response : \(realResponse)")
            }

            if let postString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String? {
                print("sendTopicPushNotification : POST: \(postString)")
            }
        }

        task.resume()
    }
</code>```

答: I finally found where the problem was. Topics can't be defined in trees as I thought and I was missing / at the beginning so changing from "to" : "topics/Bologna/Shop-promotions" to "to" : "/topics/Bologna-Shop-promotions" solved my problem. I actually found it out by checking the error while subscripting to the topic "Bologna/Shop-promotions" and fixed it by changing it to "Bologna-Shop-promotions" or "/topics/Bologna-Shop-promotions". Hope this will help others.

Body:
I'm adapting a working device to device function in order to send push notifications to topics. When I send a push to FcmToken it works perfectly, but when I sent it to a topic I get an "error":"InvalidRegistration"error. Is this registration related to the server key or what registration I'm missing to send with the request?
 Can you see where I'm mistaking?
As always many thanks.

Here is the working function to the fcmToken :

static func sendPushNotification(to receiverToken: String, title: String, subtitle: String, body: String) {
            let serverKey = firebaseServerKey // AAAA8c3j2...
//            let topic = "/topics/<your topic here>"  // replace it with partnerToken if you want to send a topic
            let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")

        let postParams: [String : Any] = [
                "to": receiverToken,
                "notification": [
//                    "badge" : 1, sendig the badge number, will cause aglitch
                    "body": body,
                    "title": title,
                    "subtitle": subtitle,
                    "sound" : true, // or specify audio name to play
                    "content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
                    "priority": "high"
//                    "click_action" : "", // action when user click notification (categoryIdentifier)
                ],
                "data" : [
                    "data": "ciao",
            ]
                ]

            let request = NSMutableURLRequest(url: url! as URL)
            request.httpMethod = "POST"
        request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            do {
//                request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: JSONSerialization.WritingOptions())
                request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: [.prettyPrinted]) // working
                print("My paramaters: \(postParams)")
            } catch {
                print("Caught an error: \(error)")
            }

            let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
                if let realResponse = response as? HTTPURLResponse {
                    if realResponse.statusCode != 200 {
                        print("Not a 200 response")
                    }
                }

                if let postString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String? {
                    print("POST: \(postString)")
                }
            }

            task.resume()
        }

and this is the one for topics:

    static func sendTopicPushNotification(to topic: String, title: String, subtitle: String, body: String) {
        let serverKey = firebaseServerKey // AAAA8c3j2...
        //            let topic = "/topics/<your topic here>"  // replace it with partnerToken if you want to send a topic
        let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")

        let postParams: [String : Any] = [
            "priority": "high",
            "notification": [
                //                    "badge" : 1, sendig the badge number, will cause aglitch
                "body": body,
                "title": title,
                "subtitle": subtitle,
                "text": "some text",
                "sound" : true, // or specify audio name to play

                //                    "click_action" : "", // action when user click notification (categoryIdentifier)
            ],
            "to" : "topics/Bologna/Shop-promotions"
//            "data" : [
////                "data": "ciao",
//                "body": body,
//                "title": title,
//                "subtitle": subtitle,
//            ]
        ]

        let request = NSMutableURLRequest(url: url! as URL)
//        request.httpMethod = "POST" // error: POST: {"error":"InvalidParameters: Bad topic or filter provided"}
       request.httpMethod = "POST"
        request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

        do {
            //                request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: JSONSerialization.WritingOptions())
            request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: [.prettyPrinted]) // working
            print("sendTopicPushNotification : My paramaters: \(postParams)")
        } catch {
            print("sendTopicPushNotification : Caught an error: \(error)")
        }

        let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            if let realResponse = response as? HTTPURLResponse {
                if realResponse.statusCode != 200 {
                    print("sendTopicPushNotification : Not a 200 response : \(realResponse)")
                }
                print("sendTopicPushNotification : response : \(realResponse)")
            }

            if let postString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String? {
                print("sendTopicPushNotification : POST: \(postString)")
            }
        }

        task.resume()
    }


问:
What does command `sed -i "s/^ \+//g; s/ \+/\t/g"` mean?
I'm new to sed. Can someone help me to explain following sed command?

```<code>sed -i "s/^ \+//g; s/ \+/\t/g"
</code>```

I found the explanation for the -i option on Google, but no exact explanations for the above pattern meanings.

Sorry that I don't have example file to show here due to the reason that our in-house server recently is under maintenance, which means I cannot access to the example file that needed here.

答:
Here is what it means:

-i - apply modifications to the input file directly

"s/^ \+//g; - remove all spaces at the start of each line

s/ \+/\t/g" - after the first replacement, replace all space strings with tabs

Body:
I'm new to sed. Can someone help me to explain following sed command?

sed -i "s/^ \+//g; s/ \+/\t/g"

I found the explanation for the -i option on Google, but no exact explanations for the above pattern meanings.

Sorry that I don't have example file to show here due to the reason that our in-house server recently is under maintenance, which means I cannot access to the example file that needed here.


问:
How to implement routing from and to root (index.js) in react with redux
I'm programming a react server webpage, trying to redirect from index.js (i.e: localhost:3000) to Login page: (localhost:3000/login), and from login to index (in case of failed login). What do I need to write in index.js and login.js?

This is for a react based app, using also redux framework. I've tried a few ways including setting up a BrowserRouter etc. All won't really do the redirecting.

My current code is this:

in index.js:

```<code>class Index extends Component {
    static getInitialProps({store, isServer, pathname, query}) {
    }

    render() {
        console.log(this.props);
        //const hist = createMemoryHistory();
        if (!this.props.isLoggedIn){
            return(<Switch><Route exact path = "/login"/></Switch>)
        }
                else{...}
</code>```

in login.js:

```<code>render() {
        console.log(this.props);
        if (fire.auth().currentUser != null) {
            var db = fire.firestore();
            db.collection("users").doc(fire.auth().currentUser.uid).get().then((doc) => {
                this.props.dispatch({ type: 'LOGIN', user: doc.data() });
            })
        }
        const { isLoggedIn } = this.props
        console.log(isLoggedIn)

        if (isLoggedIn) return <Redirect to='/' />
</code>```

I except the root to redirect to login if no session is on, and login to redirect to root once there is a successful login.
I am currently getting "You should not use <Switch> outside a <Router>" at index (I have tried to wrap with BrowserRouter, ServerRouter, Router. the first says it needs DOM history. adding history does not change error. two others do not error but are blank display on browser.)
and "ReferenceError: Redirect is not defined" at login.

Any help will be appreciated.

答:
As of now you're trying to return a route declaration wrapped in a Switch component. If you want to redirect the user to the /login page if hes not logged in, you need the route to be declared higher up in the component hierarchy, and then you would be able to return the <Redirect /> component. Either way, I would suggest you check out the react router documentation to see how they do authentication.

https://reacttraining.com/react-router/web/example/auth-workflow

Body:
I'm programming a react server webpage, trying to redirect from index.js (i.e: localhost:3000) to Login page: (localhost:3000/login), and from login to index (in case of failed login). What do I need to write in index.js and login.js?

This is for a react based app, using also redux framework. I've tried a few ways including setting up a BrowserRouter etc. All won't really do the redirecting.

My current code is this:

in index.js:

class Index extends Component {
    static getInitialProps({store, isServer, pathname, query}) {
    }

    render() {
        console.log(this.props);
        //const hist = createMemoryHistory();
        if (!this.props.isLoggedIn){
            return(<Switch><Route exact path = "/login"/></Switch>)
        }
                else{...}

in login.js:

render() {
        console.log(this.props);
        if (fire.auth().currentUser != null) {
            var db = fire.firestore();
            db.collection("users").doc(fire.auth().currentUser.uid).get().then((doc) => {
                this.props.dispatch({ type: 'LOGIN', user: doc.data() });
            })
        }
        const { isLoggedIn } = this.props
        console.log(isLoggedIn)

        if (isLoggedIn) return <Redirect to='/' />

I except the root to redirect to login if no session is on, and login to redirect to root once there is a successful login.
I am currently getting "You should not use <Switch> outside a <Router>" at index (I have tried to wrap with BrowserRouter, ServerRouter, Router. the first says it needs DOM history. adding history does not change error. two others do not error but are blank display on browser.)
and "ReferenceError: Redirect is not defined" at login.

Any help will be appreciated.


问:
How to run commands on a remote host with an existing user on that machine
I am writing a shell scripts that requires to run commands on multiple remote host based on condition it satisfies. how can i run the commands on the remote host using its key pair and assign the output of those commands to a variable on the primary host.

I tried using

```<code>sshpass -f keypair hostname 'command' | 'commands'
</code>```

but this command executed on the host itself.

答:
1) Add host public keys (~/.ssh/id_rsa.pub)to remote user authenticated keys (~/.ssh/authorized_keys)

You will append the content of the public key to the authorized_keys

2) If you don't have this key you may generate it

```<code> ssh-keygen -t rsa
</code>```

3) after that you can

```<code>ssh <REMOTE USER NAME>@RemoteHOST  <command>
</code>```

As example

```<code>ssh mebada@123.44.2.12 ls
</code>```

4) If you have list of commands you may scp shell file and execute it from there ( without password too ) and it will override the remote

```<code>scp /path/to/shell.file user@host:/path/to/remote
ssh user@host chmod u+x /path/to/remote/shell.file
ssh user@host /path/to/remote/shell.file
</code>```

Body:
I am writing a shell scripts that requires to run commands on multiple remote host based on condition it satisfies. how can i run the commands on the remote host using its key pair and assign the output of those commands to a variable on the primary host.

I tried using

sshpass -f keypair hostname 'command' | 'commands'

but this command executed on the host itself.

Body:
1) Add host public keys (~/.ssh/id_rsa.pub)to remote user authenticated keys (~/.ssh/authorized_keys)

You will append the content of the public key to the authorized_keys

2) If you don't have this key you may generate it

 ssh-keygen -t rsa

3) after that you can

ssh <REMOTE USER NAME>@RemoteHOST  <command>

As example

ssh mebada@123.44.2.12 ls

4) If you have list of commands you may scp shell file and execute it from there ( without password too ) and it will override the remote

scp /path/to/shell.file user@host:/path/to/remote
ssh user@host chmod u+x /path/to/remote/shell.file
ssh user@host /path/to/remote/shell.file


问:
Performance issue with SD[] when indexing by variable
I am working with data.tables in R. The data has multiple records by id and I am trying to find the nth record for each individual using the .SD data.table option. If I specify N as an integer, the new data.table is created instantaneously. But if N is a variable (as it might be in a function), the code takes about 700 times longer. With large data sets, this is a problem. I was wondering if this is a known issue, and if there is any way to speed this up?

library(data.table)
library(microbenchmark)

set.seed(102938)

dd <- data.table(id = rep(1:10000, each = 10), seq = seq(1:10))
setkey(dd, id)

N <- 2
microbenchmark(dd[,.SD[2], keyby = id],
               dd[,.SD[N], keyby = id],
               times = 5)
```

<pre class="lang-r prettyprint-override"><code>#> Unit: microseconds
#>                      expr        min         lq       mean     median
#>  dd[, .SD[2], keyby = id]    886.269   1584.513   2904.497   1851.356
#>  dd[, .SD[N], keyby = id] 770822.875 810131.784 870418.622 903956.708
#>          uq        max neval
#>    1997.134   8203.214     5
#>  912223.026 954958.718     5
</code>```

答:
It may be better to do the subsetting with row index (.I) instead of .SD

```<code>dd[dd[, .I[N], keyby = id]$V1]
</code>```

-benchmarks

```<code>microbenchmark(dd[,.SD[2], keyby = id],
                dd[dd[,.I[N], keyby = id]$V1],
                times = 5)
#Unit: milliseconds
#                           expr      min       lq     mean   median       uq      max neval
#       dd[, .SD[2], keyby = id] 1.253097 1.343862 2.796684 1.352426 1.400910 8.633126     5
# dd[dd[, .I[N], keyby = id]$V1] 5.082752 5.383201 5.991076 5.866084 6.488898 7.134443     5
</code>```

With .I, it got improved much better than .SD, but there is still a performance hit and it would be the search time in the global env for finding the variable 'N'

Internally, optimizations play a role in the timings.  If we use, all optimizations FALSE by using the option 0

```<code>options(datatable.optimize = 0L)
microbenchmark(dd[,.SD[2], keyby = id],
             dd[dd[,.I[N], keyby = id]$V1],
             times = 5)
#Unit: milliseconds
#                          expr        min         lq      mean     median         uq        max neval
#      dd[, .SD[2], keyby = id] 660.612463 701.573252 761.51163 776.780341 785.940196 882.651875     5
#dd[dd[, .I[N], keyby = id]$V1]   3.860492   4.140469   5.05796   4.762518   5.342907   7.183416     5
</code>```

Now, the .I method is faster

Changing to 1

```<code>options(datatable.optimize = 1L)
microbenchmark(dd[,.SD[2], keyby = id],
                 dd[dd[,.I[N], keyby = id]$V1],
                 times = 5)
#Unit: milliseconds
#                           expr      min       lq     mean   median       uq      max neval
#       dd[, .SD[2], keyby = id] 4.934761 5.109478 5.496449 5.414477 5.868185 6.155342     5
# dd[dd[, .I[N], keyby = id]$V1] 3.923388 3.966413 4.325268 4.379745 4.494367 4.862426     5
</code>```

With 2 - gforce optimization - default method

```<code>options(datatable.optimize = 2L)
microbenchmark(dd[,.SD[2], keyby = id],
                 dd[dd[,.I[N], keyby = id]$V1],
                 times = 5)
#Unit: milliseconds
#                           expr      min       lq     mean   median       uq      max neval
#       dd[, .SD[2], keyby = id] 1.113463 1.179071 1.245787 1.205013 1.337216 1.394174     5
# dd[dd[, .I[N], keyby = id]$V1] 4.339619 4.523917 4.774221 4.833648 5.017755 5.156166     5
</code>```

Behind the hood optimizations can be checked with verbose = TRUE

```<code>out1 <- dd[,.SD[2], keyby = id, verbose = TRUE]
#Finding groups using forderv ... 0.017s elapsed (0.020s cpu)
#Finding group sizes from the positions (can be avoided to save RAM) ... 0.022s #elapsed (0.131s cpu)
#lapply optimization changed j from '.SD[2]' to 'list(seq[2])'
#GForce optimized j to 'list(`g[`(seq, 2))'
#Making each group and running j (GForce TRUE) ... 0.027s elapsed (0.159s cpu)

out2 <- dd[dd[,.I[N], keyby = id, verbose = TRUE]$V1, verbose = TRUE]
#Detected that j uses these columns: <none>
#Finding groups using forderv ... 0.023s elapsed (0.026s cpu)
#Finding group sizes from the positions (can be avoided to save RAM) ... 0.022s #elapsed (0.128s cpu)
#lapply optimization is on, j unchanged as '.I[N]'
#GForce is on, left j unchanged
#Old mean optimization is on, left j unchanged.
#Making each group and running j (GForce FALSE) ...
#  memcpy contiguous groups took 0.052s for 10000 groups
#  eval(j) took 0.065s for 10000 calls   #######
#0.068s elapsed (0.388s cpu)
</code>```

Body:
I am working with data.tables in R. The data has multiple records by id and I am trying to find the nth record for each individual using the .SD data.table option. If I specify N as an integer, the new data.table is created instantaneously. But if N is a variable (as it might be in a function), the code takes about 700 times longer. With large data sets, this is a problem. I was wondering if this is a known issue, and if there is any way to speed this up?

library(data.table)
library(microbenchmark)

set.seed(102938)

dd <- data.table(id = rep(1:10000, each = 10), seq = seq(1:10))
setkey(dd, id)

N <- 2
microbenchmark(dd[,.SD[2], keyby = id],
               dd[,.SD[N], keyby = id],
               times = 5)

#> Unit: microseconds
#>                      expr        min         lq       mean     median
#>  dd[, .SD[2], keyby = id]    886.269   1584.513   2904.497   1851.356
#>  dd[, .SD[N], keyby = id] 770822.875 810131.784 870418.622 903956.708
#>          uq        max neval
#>    1997.134   8203.214     5
#>  912223.026 954958.718     5

Body:
It may be better to do the subsetting with row index (.I) instead of .SD

dd[dd[, .I[N], keyby = id]$V1]

-benchmarks

microbenchmark(dd[,.SD[2], keyby = id],
                dd[dd[,.I[N], keyby = id]$V1],
                times = 5)
#Unit: milliseconds
#                           expr      min       lq     mean   median       uq      max neval
#       dd[, .SD[2], keyby = id] 1.253097 1.343862 2.796684 1.352426 1.400910 8.633126     5
# dd[dd[, .I[N], keyby = id]$V1] 5.082752 5.383201 5.991076 5.866084 6.488898 7.134443     5

With .I, it got improved much better than .SD, but there is still a performance hit and it would be the search time in the global env for finding the variable 'N'

Internally, optimizations play a role in the timings.  If we use, all optimizations FALSE by using the option 0

options(datatable.optimize = 0L)
microbenchmark(dd[,.SD[2], keyby = id],
             dd[dd[,.I[N], keyby = id]$V1],
             times = 5)
#Unit: milliseconds
#                          expr        min         lq      mean     median         uq        max neval
#      dd[, .SD[2], keyby = id] 660.612463 701.573252 761.51163 776.780341 785.940196 882.651875     5
#dd[dd[, .I[N], keyby = id]$V1]   3.860492   4.140469   5.05796   4.762518   5.342907   7.183416     5

Now, the .I method is faster

Changing to 1

options(datatable.optimize = 1L)
microbenchmark(dd[,.SD[2], keyby = id],
                 dd[dd[,.I[N], keyby = id]$V1],
                 times = 5)
#Unit: milliseconds
#                           expr      min       lq     mean   median       uq      max neval
#       dd[, .SD[2], keyby = id] 4.934761 5.109478 5.496449 5.414477 5.868185 6.155342     5
# dd[dd[, .I[N], keyby = id]$V1] 3.923388 3.966413 4.325268 4.379745 4.494367 4.862426     5

With 2 - gforce optimization - default method

options(datatable.optimize = 2L)
microbenchmark(dd[,.SD[2], keyby = id],
                 dd[dd[,.I[N], keyby = id]$V1],
                 times = 5)
#Unit: milliseconds
#                           expr      min       lq     mean   median       uq      max neval
#       dd[, .SD[2], keyby = id] 1.113463 1.179071 1.245787 1.205013 1.337216 1.394174     5
# dd[dd[, .I[N], keyby = id]$V1] 4.339619 4.523917 4.774221 4.833648 5.017755 5.156166     5

Behind the hood optimizations can be checked with verbose = TRUE

out1 <- dd[,.SD[2], keyby = id, verbose = TRUE]
#Finding groups using forderv ... 0.017s elapsed (0.020s cpu)
#Finding group sizes from the positions (can be avoided to save RAM) ... 0.022s #elapsed (0.131s cpu)
#lapply optimization changed j from '.SD[2]' to 'list(seq[2])'
#GForce optimized j to 'list(`g[`(seq, 2))'
#Making each group and running j (GForce TRUE) ... 0.027s elapsed (0.159s cpu)

out2 <- dd[dd[,.I[N], keyby = id, verbose = TRUE]$V1, verbose = TRUE]
#Detected that j uses these columns: <none>
#Finding groups using forderv ... 0.023s elapsed (0.026s cpu)
#Finding group sizes from the positions (can be avoided to save RAM) ... 0.022s #elapsed (0.128s cpu)
#lapply optimization is on, j unchanged as '.I[N]'
#GForce is on, left j unchanged
#Old mean optimization is on, left j unchanged.
#Making each group and running j (GForce FALSE) ...
#  memcpy contiguous groups took 0.052s for 10000 groups
#  eval(j) took 0.065s for 10000 calls   #######
#0.068s elapsed (0.388s cpu)


问:
IEqualityComparer for SequenceEqual
In C#, is there an IEqualityComparer<IEnumerable> that uses the SequenceEqual method to determine equality?

答:
Created a NuGet package based on Cédric Bignon's answer:

Assembly package:
https://www.nuget.org/packages/OBeautifulCode.Collection/

Code-file-only package: https://www.nuget.org/packages/OBeautifulCode.Collection.Recipes.EnumerableEqualityComparer/

```<code>var myEqualityComparer = new EnumerableEqualityComparer<string>();
</code>```

Title: IEqualityComparer for SequenceEqual

Body:
Created a NuGet package based on Cédric Bignon's answer:

Assembly package:
https://www.nuget.org/packages/OBeautifulCode.Collection/

Code-file-only package: https://www.nuget.org/packages/OBeautifulCode.Collection.Recipes.EnumerableEqualityComparer/

var myEqualityComparer = new EnumerableEqualityComparer<string>();


问:
how to write a CDATA node using libxml2?
I'm using libxml2 to read/write xml files.  Now I'm trying to write a CDATA node.

Here is what I tried:

```<code>nodePtr = xmlNewChild( parentPtr, NULL, "foo", NULL );
xmlNodeSetContentLen( nodePtr, "<![CDATA[\nTesting 1 < 2\n]]>", len );
</code>```

However, this results in the following encoded text:

```<code><foo><![CDATA[
Testing 1 < 2
]]></foo>
</code>```

I'm thinking that perhaps there might be a CDATA-specific libxml2 API.  Or maybe I have to call something else to tell libxml2 not to automatically encode the node content?

答:
Figured it out.  The trick is in knowing that CDATA text content is actually a child and not a part of the current node, and the critical API to call is xmlNewCDataBlock().  Using the same example as above:

```<code>nodePtr = xmlNewChild( parentPtr, NULL, "foo", NULL );
cdataPtr = xmlNewCDataBlock( doc, "Testing 1 < 2", 13 );
xmlAddChild( nodePtr, cdataPtr );
</code>```

This will produce the following xml:

```<code><foo><![CDATA[Testing 1 < 2]]></foo>
</code>```

Body:
I'm using libxml2 to read/write xml files.  Now I'm trying to write a CDATA node.

Here is what I tried:

nodePtr = xmlNewChild( parentPtr, NULL, "foo", NULL );
xmlNodeSetContentLen( nodePtr, "<![CDATA[\nTesting 1 < 2\n]]>", len );

However, this results in the following encoded text:

<foo><![CDATA[
Testing 1 < 2
]]></foo>

I'm thinking that perhaps there might be a CDATA-specific libxml2 API.  Or maybe I have to call something else to tell libxml2 not to automatically encode the node content?

Body:
Figured it out.  The trick is in knowing that CDATA text content is actually a child and not a part of the current node, and the critical API to call is xmlNewCDataBlock().  Using the same example as above:

nodePtr = xmlNewChild( parentPtr, NULL, "foo", NULL );
cdataPtr = xmlNewCDataBlock( doc, "Testing 1 < 2", 13 );
xmlAddChild( nodePtr, cdataPtr );

This will produce the following xml:

<foo><![CDATA[Testing 1 < 2]]></foo>


问:
Alexa ask a question and get response from external API
I have set up a simple intent

{
  "interactionModel": {
    "languageModel": {
      "invocationName": "viva bank",
      "intents": [
        ...builtin intents...{
          "name": "ask",
          "slots": [{
            "name": "question",
            "type": "AMAZON.SearchQuery"
          }],
          "samples": [
            "when {question}",
            "how to {question}",
            "what {question}"
          ]
        }
      ],
      "types": []
    }
  }
}```
</div>
</div>
</p>

<p>But when I ask a question it gives me a generic error response like this:</p>

<p>Me: alexa ask viva bank when is the late fee charged</p>

<p>Alexa: Sorry, I don't know that.</p>

<p>Here is my lambda code, but I don't think it is getting that far.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';

const Alexa = require('ask-sdk-core');
var https = require('https');
var querystring = require('querystring');

const APP_ID = 'amzn1.ask.skill.1234';

const AskIntentHandler = {
  canHandle(handlerInput) {
    return !!handlerInput.requestEnvelope.request.intent.slots['question'].value;
  },
  handle(handlerInput) {
    var question = handlerInput.requestEnvelope.request.intent.slots['question'].value;
    console.log('mydata:', question);
    var responseString = '';
    const subscription_key = 'XXXX';

    var data = {
      simplequery: question,
      channel: 'Alexa'
    };
    var get_options = {
      headers: {
        'Subscription-Key': subscription_key
      }
    };

    https.get('https://fakeapi.com/' + querystring.stringify(data), get_options, (res) => {
      console.log('statusCode:', res.statusCode);
      console.log('headers:', res.headers);

      res.on('data', (d) => {
        responseString += d;
      });

      res.on('end', function(res) {
        var json_hash = JSON.parse(responseString);
        // grab the first answer returned as text and have Alexa read it
        const speechOutput = json_hash['results'][0]['content']['text'];
        console.log('==> Answering: ', speechOutput);
        // speak the output
        return handlerInput.responseBuilder.speak(speechOutput).getResponse();
      });
    }).on('error', (e) => {
      console.error(e);
      return handlerInput.responseBuilder.speak("I'm sorry I ran into an error").getResponse();
    });
  }

};

exports.handler = (event, context) => {
  const alexa = Alexa.handler(event, context);
  alexa.APP_ID = APP_ID;
  alexa.registerHandlers(AskIntentHandler);
  alexa.execute();
};</code>```

I'm really just looking to create a very simple pass through, where a question is asked to Alexa, and then I pipe that to an external API and have Alexa read the response.

答:
You can make the question slot value as required if it is mandatory for the intent and you need to include the intent name. You can use async/await to handle the API.</p>

```<code>const Alexa = require('ask-sdk-core');
const https = require('https');
const querystring = require('querystring');
const { getSlotValue } = Alexa;

const APP_ID = 'amzn1.ask.skill.1234';

const AskIntentHandler = {
  canHandle(handlerInput) {
    return (
      handlerInput.requestEnvelope.request.type === "IntentRequest" &&
      handlerInput.requestEnvelope.request.intent.name === "AskIntent"
    );
  },
  async handle(handlerInput) {
    const question = getSlotValue(handlerInput.requestEnvelope, "question");
    console.log("question ", question);
    const data = await getAnswer(question);
    const speechText = data;
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  }
};

const getAnswer = question => {
  const subscription_key = "XXXX";
  let data = {
    simplequery: question,
    channel: "Alexa"
  };
  let get_options = {
    headers: {
      "Subscription-Key": subscription_key
    }
  };
  return new Promise((resolve, reject) => {
    https
      .get(
        "https://fakeapi.com/" + querystring.stringify(data),
        get_options,
        res => {
          console.log("statusCode:", res.statusCode);
          console.log("headers:", res.headers);
          res.on("data", d => {
            responseString += d;
          });

          res.on("end", function(res) {
            var json_hash = JSON.parse(responseString);
            // grab the first answer returned as text and have Alexa read it
            const speechOutput = json_hash["results"][0]["content"]["text"];
            console.log("==> Answering: ", speechOutput);
            resolve(speechOutput);
          });
        }
      )
      .on("error", e => {
        console.error(e);
        resolve("I'm sorry I ran into an error");
      });
  });
};
</code>```

Body:
I have set up a simple intent

{
  "interactionModel": {
    "languageModel": {
      "invocationName": "viva bank",
      "intents": [
        ...builtin intents...{
          "name": "ask",
          "slots": [{
            "name": "question",
            "type": "AMAZON.SearchQuery"
          }],
          "samples": [
            "when {question}",
            "how to {question}",
            "what {question}"
          ]
        }
      ],
      "types": []
    }
  }
}

But when I ask a question it gives me a generic error response like this:

Me: alexa ask viva bank when is the late fee charged

Alexa: Sorry, I don't know that.

Here is my lambda code, but I don't think it is getting that far.

'use strict';

const Alexa = require('ask-sdk-core');
var https = require('https');
var querystring = require('querystring');

const APP_ID = 'amzn1.ask.skill.1234';

const AskIntentHandler = {
  canHandle(handlerInput) {
    return !!handlerInput.requestEnvelope.request.intent.slots['question'].value;
  },
  handle(handlerInput) {
    var question = handlerInput.requestEnvelope.request.intent.slots['question'].value;
    console.log('mydata:', question);
    var responseString = '';
    const subscription_key = 'XXXX';

    var data = {
      simplequery: question,
      channel: 'Alexa'
    };
    var get_options = {
      headers: {
        'Subscription-Key': subscription_key
      }
    };

    https.get('https://fakeapi.com/' + querystring.stringify(data), get_options, (res) => {
      console.log('statusCode:', res.statusCode);
      console.log('headers:', res.headers);

      res.on('data', (d) => {
        responseString += d;
      });

      res.on('end', function(res) {
        var json_hash = JSON.parse(responseString);
        // grab the first answer returned as text and have Alexa read it
        const speechOutput = json_hash['results'][0]['content']['text'];
        console.log('==> Answering: ', speechOutput);
        // speak the output
        return handlerInput.responseBuilder.speak(speechOutput).getResponse();
      });
    }).on('error', (e) => {
      console.error(e);
      return handlerInput.responseBuilder.speak("I'm sorry I ran into an error").getResponse();
    });
  }

};

exports.handler = (event, context) => {
  const alexa = Alexa.handler(event, context);
  alexa.APP_ID = APP_ID;
  alexa.registerHandlers(AskIntentHandler);
  alexa.execute();
};

I'm really just looking to create a very simple pass through, where a question is asked to Alexa, and then I pipe that to an external API and have Alexa read the response.

Body:
You can make the question slot value as required if it is mandatory for the intent and you need to include the intent name. You can use async/await to handle the API.

const Alexa = require('ask-sdk-core');
const https = require('https');
const querystring = require('querystring');
const { getSlotValue } = Alexa;

const APP_ID = 'amzn1.ask.skill.1234';

const AskIntentHandler = {
  canHandle(handlerInput) {
    return (
      handlerInput.requestEnvelope.request.type === "IntentRequest" &&
      handlerInput.requestEnvelope.request.intent.name === "AskIntent"
    );
  },
  async handle(handlerInput) {
    const question = getSlotValue(handlerInput.requestEnvelope, "question");
    console.log("question ", question);
    const data = await getAnswer(question);
    const speechText = data;
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  }
};

const getAnswer = question => {
  const subscription_key = "XXXX";
  let data = {
    simplequery: question,
    channel: "Alexa"
  };
  let get_options = {
    headers: {
      "Subscription-Key": subscription_key
    }
  };
  return new Promise((resolve, reject) => {
    https
      .get(
        "https://fakeapi.com/" + querystring.stringify(data),
        get_options,
        res => {
          console.log("statusCode:", res.statusCode);
          console.log("headers:", res.headers);
          res.on("data", d => {
            responseString += d;
          });

          res.on("end", function(res) {
            var json_hash = JSON.parse(responseString);
            // grab the first answer returned as text and have Alexa read it
            const speechOutput = json_hash["results"][0]["content"]["text"];
            console.log("==> Answering: ", speechOutput);
            resolve(speechOutput);
          });
        }
      )
      .on("error", e => {
        console.error(e);
        resolve("I'm sorry I ran into an error");
      });
  });
};


问:
How to sync to codesandbox from github repo?
I created a CodeSandbox from github repo. How can I sync to CodeSandbox if there are some commits pushed to github repo? I see there is a github view on Codesandbox but it doesn't show any pull action.

答:
According to codesandbox docs

The imported repository will always stay up to date with your latest commits. This means that any change to the GitHub repository will be reflected immediately to the sandbox.


问:
How to get current date in jQuery?
I want to know how to use the Date() function in jQuery to get the current date in a yyyy/mm/dd format.

答:
This will give you current date string</p>

```<code>var today = new Date().toISOString().split('T')[0];
</code>```

Title: How to get current date in jQuery?

Body:
This will give you current date string

var today = new Date().toISOString().split('T')[0];


问:
Set dropdown button width to same as dropdown item width
I have a dropdown div and its button width is different from that of its dropdown items. I want the button and the dropdown items to have the same width.

```<code><div class="dropdown col">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>
    <ul class="dropdown-menu col-xs-12">
        <a class="dropdown-item" href="#">word</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">word</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">Very long word</a>
    </ul>
</div>
</code>```

The width of Very long word item is the same as that of word items, only the button that has a different width.

答:
I'm not sure from your tags if you're looking for a bootsrap specific answer, but one option would be to set the parent, .dropowncontainer to display: flex with flex-direction:column, expanding the child items on the flex parents primary axis.

```<code>.dropdown {
  display: flex;
  flex-direction: column;
}
</code>```

Body:
I have a dropdown div and its button width is different from that of its dropdown items. I want the button and the dropdown items to have the same width.

    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>

        word

        word

        Very long word

The width of Very long word item is the same as that of word items, only the button that has a different width.

Body:
I'm not sure from your tags if you're looking for a bootsrap specific answer, but one option would be to set the parent, .dropowncontainer to display: flex with flex-direction:column, expanding the child items on the flex parents primary axis.

.dropdown {
  display: flex;
  flex-direction: column;
}


问:
Set tab as 2 spaces in vimrc, but still set to 4 spaces when editing python files
I've set tab to equal 2 spaces in my vimrc. This works when I edit java files, but for some reason when I edit python files, tab is set to 4 spaces instead.

My vimrc:

```<code>filetype plugin indent on
syntax on

set backspace=indent,eol,start

set expandtab
set tabstop=2
set shiftwidth=2
set softtabstop=2
set showtabline=2

set number
set showcmd
set cursorline
set wildmenu
set lazyredraw
set showmatch

call plug#begin('~/.vim/plugged')

Plug 'scrooloose/nerdtree'
Plug 'drewtempelmeyer/palenight.vim'
Plug 'NLKNguyen/papercolor-theme'
Plug 'rakr/vim-one'
Plug 'morhetz/gruvbox'
Plug 'tpope/vim-commentary'
Plug 'ajh17/VimCompletesMe'
Plug 'sheerun/vim-polyglot'

call plug#end()

highlight ColorColumn ctermbg=gray
set colorcolumn=81
autocmd BufNewFile,BufRead * setlocal formatoptions=croqtn textwidth=80

set t_Co=256
set term=xterm-256color
let g:gruvbox_contrast_dark='dark'
colorscheme gruvbox
set background=dark

map <C-x> :NERDTreeToggle<CR>
noremap <TAB> <C-W>w

" autoclose matching quotes, braces and parentheses
inoremap {<CR> {<CR>}<ESC>O
inoremap {;<CR> {<CR>};<ESC>O
inoremap jj  <Esc>
inoremap <Esc> <Nop>
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
inoremap <C-y> <C-o>h
inoremap <C-u> <C-o>l
</code>```

答:
This is set automatically in filetype's python plugin.

ftplugin/python.vim

```<code>if !exists("g:python_recommended_style") || g:python_recommended_style != 0
    " As suggested by PEP8.
    setlocal expandtab shiftwidth=4 softtabstop=4 tabstop=8
endif
</code>```

So you can disable it with:

```<code>let g:python_recommended_style = 0
filetype plugin indent on
syntax on
...
</code>```

Body:
I've set tab to equal 2 spaces in my vimrc. This works when I edit java files, but for some reason when I edit python files, tab is set to 4 spaces instead.

My vimrc:

filetype plugin indent on
syntax on

set backspace=indent,eol,start

set expandtab
set tabstop=2
set shiftwidth=2
set softtabstop=2
set showtabline=2

set number
set showcmd
set cursorline
set wildmenu
set lazyredraw
set showmatch

call plug#begin('~/.vim/plugged')

Plug 'scrooloose/nerdtree'
Plug 'drewtempelmeyer/palenight.vim'
Plug 'NLKNguyen/papercolor-theme'
Plug 'rakr/vim-one'
Plug 'morhetz/gruvbox'
Plug 'tpope/vim-commentary'
Plug 'ajh17/VimCompletesMe'
Plug 'sheerun/vim-polyglot'

call plug#end()

highlight ColorColumn ctermbg=gray
set colorcolumn=81
autocmd BufNewFile,BufRead * setlocal formatoptions=croqtn textwidth=80

set t_Co=256
set term=xterm-256color
let g:gruvbox_contrast_dark='dark'
colorscheme gruvbox
set background=dark

map <C-x> :NERDTreeToggle<CR>
noremap <TAB> <C-W>w

" autoclose matching quotes, braces and parentheses
inoremap {<CR> {<CR>}<ESC>O
inoremap {;<CR> {<CR>};<ESC>O
inoremap jj  <Esc>
inoremap <Esc> <Nop>
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
inoremap <C-y> <C-o>h
inoremap <C-u> <C-o>l

Body:
This is set automatically in filetype's python plugin.

ftplugin/python.vim

if !exists("g:python_recommended_style") || g:python_recommended_style != 0
    " As suggested by PEP8.
    setlocal expandtab shiftwidth=4 softtabstop=4 tabstop=8
endif

So you can disable it with:

let g:python_recommended_style = 0
filetype plugin indent on
syntax on
...


Title: How to make a simple JavaScript call from a PHP function?

Body:
I have a simple PHP function that is being called when a form is submitted:

function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}

What I need is to be able to do a simple Google Analytics call like this:

_gaq.push(['_trackPageview', 'virtual/formSubmit']);

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?

Body:
Make your function return the output and have the output print in the GOOGLE code <script> element, will make the _gaq.push... fire off.

You can't just output that JS and expect it to fire by itself somewhere... or for PHP to make a call to Google.

PHP is SERVER SIDE

JS is CLIENT SIDE (clients browser requests from google, not your server)

So like I said, make the JS output to a function that fires onload and you are all set.
save the output:  $output = "_gaq.push(['_trackPageview', 'virtual/formSubmit']);";

and then echo it somewhere to fire it.


问:
How to render search results only when the user press search
Does anyone know how to only display search results once you have clicked the search button?

At the moment, my page is currently displaying  everything from my @flights.each. But I only want this information to become visible once they have clicked search :)

my index.html.erb

```<code><h1>Flights#index</h1>
<p>Find me in app/views/flights/index.html.erb</p>

From Airport:
<%= form_for(flights_index_path, method: :get) do %>
    <%= text_field_tag :from_airport_id, params[:from_airport_id] %>

    <%= submit_tag 'Search' %>
<% end %>

<% @flights.each do |f| %>
<br>
<br>

    Flight from <%= f.from_airport_id %>
    Arriving at <%= f.to_airport_id %>
<% end %>

</code>```

my controller

```<code>class FlightsController < ApplicationController
  def index

    if params[:from_airport_id]
      @flights = Flight.where('from_airport_id LIKE ?', "%#{params[:from_airport_id]}%")
    else
      @flights = Flight.all
    end
  end

  private
    def flights_path
      params.require(:flight).permit(:flight, :from_airport_id)
    end

end
</code>```

答:
I believe it's because you have @flights = Flight.all in the else condition. When there is no query(such as after hitting the submit button and passing over the params) it will default to show all the flights. I'd take this line out and only have

```<code>def index

    if params[:from_airport_id]
      @flights = Flight.where('from_airport_id LIKE ?', "%#{params[:from_airport_id]}%")
    else
      @flights = []
    end
  end
</code>```

Or you can look to have an AJAX request from your flights search and render the form that way.

Body:
Does anyone know how to only display search results once you have clicked the search button?

At the moment, my page is currently displaying  everything from my @flights.each. But I only want this information to become visible once they have clicked search :)

my index.html.erb

Flights#index

Find me in app/views/flights/index.html.erb

From Airport:
<%= form_for(flights_index_path, method: :get) do %>
    <%= text_field_tag :from_airport_id, params[:from_airport_id] %>

    <%= submit_tag 'Search' %>
<% end %>

<% @flights.each do |f| %>

    Flight from <%= f.from_airport_id %>
    Arriving at <%= f.to_airport_id %>
<% end %>

my controller

class FlightsController < ApplicationController
  def index

    if params[:from_airport_id]
      @flights = Flight.where('from_airport_id LIKE ?', "%#{params[:from_airport_id]}%")
    else
      @flights = Flight.all
    end
  end

  private
    def flights_path
      params.require(:flight).permit(:flight, :from_airport_id)
    end

end

Body:
I believe it's because you have @flights = Flight.all in the else condition. When there is no query(such as after hitting the submit button and passing over the params) it will default to show all the flights. I'd take this line out and only have

def index

    if params[:from_airport_id]
      @flights = Flight.where('from_airport_id LIKE ?', "%#{params[:from_airport_id]}%")
    else
      @flights = []
    end
  end

Or you can look to have an AJAX request from your flights search and render the form that way.