问:
GroupIntoBatches for non-KV elements

According to the Apache Beam 2.0.0 SDK Documentation GroupIntoBatches works only with KV collections.

My dataset contains only values and there's no need for introducing keys. However, to make use of GroupIntoBatches I had to implement “fake” keys with an empty string as a key:

static class FakeKVFn extends DoFn<String, KV<String, String>> {
  @ProcessElement
  public void processElement(ProcessContext c) {
    c.output(KV.of("", c.element()));
  }
}
```

<p>So the overall pipeline looks like the following:</p>

<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {
  PipelineOptions options = PipelineOptionsFactory.create();
  Pipeline p = Pipeline.create(options);

  long batchSize = 100L;

  p.apply("ReadLines", TextIO.read().from("./input.txt"))
      .apply("FakeKV", ParDo.of(new FakeKVFn()))
      .apply(GroupIntoBatches.<String, String>ofSize(batchSize))
      .setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())))
      .apply(ParDo.of(new DoFn<KV<String, Iterable<String>>, String>() {
        @ProcessElement
        public void processElement(ProcessContext c) {
          c.output(callWebService(c.element().getValue()));
        }
      }))
      .apply("WriteResults", TextIO.write().to("./output/"));

  p.run().waitUntilFinish();
}
</code>```

Is there any way to group into batches without introducing “fake” keys?

答:
It is required to provide KV inputs to GroupIntoBatches because the transform is implemented using state and timers, which are per key-and-window.

For each key+window pair, state and timers necessarily execute serially (or observably so). You have to manually express the available parallelism by providing keys (and windows, though no runner that I know of parallelizes over windows today). The two most common approaches are:

Use some natural key like a user ID

Choose some fixed number of shards and key randomly. This can be harder to tune. You have to have enough shards to get enough parallelism, but each shard needs to include enough data that GroupIntoBatches is actually useful.

Adding one dummy key to all elements as in your snippet will cause the transform to not execute in parallel at all. This is similar to the discussion at Stateful indexing causes ParDo to be run single-threaded on Dataflow Runner.

Title: GroupIntoBatches for non-KV elements

Body:
According to the Apache Beam 2.0.0 SDK Documentation GroupIntoBatches works only with KV collections.

My dataset contains only values and there's no need for introducing keys. However, to make use of GroupIntoBatches I had to implement “fake” keys with an empty string as a key:

static class FakeKVFn extends DoFn<String, KV<String, String>> {
  @ProcessElement
  public void processElement(ProcessContext c) {
    c.output(KV.of("", c.element()));
  }
}

So the overall pipeline looks like the following:

public static void main(String[] args) {
  PipelineOptions options = PipelineOptionsFactory.create();
  Pipeline p = Pipeline.create(options);

  long batchSize = 100L;

  p.apply("ReadLines", TextIO.read().from("./input.txt"))
      .apply("FakeKV", ParDo.of(new FakeKVFn()))
      .apply(GroupIntoBatches.<String, String>ofSize(batchSize))
      .setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())))
      .apply(ParDo.of(new DoFn<KV<String, Iterable<String>>, String>() {
        @ProcessElement
        public void processElement(ProcessContext c) {
          c.output(callWebService(c.element().getValue()));
        }
      }))
      .apply("WriteResults", TextIO.write().to("./output/"));

  p.run().waitUntilFinish();
}

Is there any way to group into batches without introducing “fake” keys?


来源: stackexchange

问:
Difference between env/bin/python and env/lib/pythonX.Y (note the lib)
Sorry for the noob question - just trying to understand the flow of how python works.

Does anyone know what the difference between env/bin/python and env/lib/python3.6 is? It will be really helpful to know. (Note the different paths - bin and lib)

Thanks :)

EDIT: I only have one version of python installed in the environment. The one thing to notice here is that env/bin/python has a symbolic link to env/bin/python3.6 (which is a binary file, obviously). But there is a directory in env/lib/python3.6 in which there are directories like site-packages where the installed packages are stored.

So my questions is... when is the binary file in /env/bin used and when is the directory accessed? When I say 'python' in the shell, it goes to the bin but when I say 'import django' in the interpreter, it goes to python3.6 in lib and gets the package. Am i on the right track?

答:
/bin/python is the binary, the program that interprets python code; lib/pythonX.Y is the library that the program uses. The library is a collection of modules and packages written in C/C++ and Python.

lib/pythonX.Y/site-packages is a directory for 3rd-party modules; distutils/setuptools/pip install packages there.

Everything else in lib/pythonX.Y outside of site-packages is the standard library — modules that are always installed with python. The pages at https://docs.python.org/3/ document the standard library but not 3rd-party modules.

ContentLicense: CC BY-SA 3.0


问:
MySQL query combining sums from multiple tables
I have the following query that is trying to generate a list of all clients, their projects, time spent on each project, total invoiced amount and total number of invoices.

```<code>SELECT
    c.name as client,
    p.name as project,
    SUM(t.hours) as hours,
    SUM(ci.amount) as invoice_amount,
    COUNT(ci.id) as number_invoices
FROM
    projects p
    INNER JOIN client_master c ON c.harvest_id = p.client_id
    INNER JOIN timesheet t ON t.project_id = p.id
    LEFT OUTER JOIN projects_contracts pc ON pc.project_id = p.id
    INNER JOIN contracts_invoices ci ON ci.contract_id = pc.contract_id
GROUP BY
    c.name,
    p.name
ORDER BY
    c.name,
    p.name,
    t.hours
</code>```

When I run the query, the "hours" are being calculated correctly but the sums/counts for invoice_amount and number_invoices aren't being joined contextually to the project but to the total number of invoices in the table. If I comment out one of the sum()'s then I get the proper value but not when they're both in.

Expected Results

Client A, Project 1, 1000, $10,000, 2

Client A, Project 2, 5000, $5,000, 1

Client B, Project 1, 100, $3000, 1

Actual Results

Client A, Project 1, 1000, $150,000, 20

Client A, Project 2, 5000, $50,000, 81

Client B, Project 1, 100, $83000, 12

I've tried messing w/ the grouping and join statements but haven't found success. Is there something simple I'm overlooking or do I need a total rewrite?

答:
Since invoices are dependant on contracts, and contracts are optional (the left join),
make that join also a left join.</p>

```<code>SELECT
    c.name as client,
    p.name as project,
    SUM(t.hours) as hours,
    SUM(ci.amount) as invoice_amount,
    COUNT(ci.id) as number_invoices
FROM
    projects p
    INNER JOIN client_master c
        ON c.harvest_id = p.client_id
    INNER JOIN timesheet t
        ON t.project_id = p.id
    LEFT JOIN projects_contracts pc
        ON pc.project_id = p.id
    LEFT JOIN contracts_invoices ci
        ON ci.contract_id = pc.contract_id
GROUP BY
    c.name,
    p.name
ORDER BY
    c.name,
    p.name,
    t.hours
</code>```

Body:
I have the following query that is trying to generate a list of all clients, their projects, time spent on each project, total invoiced amount and total number of invoices.

SELECT
    c.name as client,
    p.name as project,
    SUM(t.hours) as hours,
    SUM(ci.amount) as invoice_amount,
    COUNT(ci.id) as number_invoices
FROM
    projects p
    INNER JOIN client_master c ON c.harvest_id = p.client_id
    INNER JOIN timesheet t ON t.project_id = p.id
    LEFT OUTER JOIN projects_contracts pc ON pc.project_id = p.id
    INNER JOIN contracts_invoices ci ON ci.contract_id = pc.contract_id
GROUP BY
    c.name,
    p.name
ORDER BY
    c.name,
    p.name,
    t.hours

When I run the query, the "hours" are being calculated correctly but the sums/counts for invoice_amount and number_invoices aren't being joined contextually to the project but to the total number of invoices in the table. If I comment out one of the sum()'s then I get the proper value but not when they're both in.

Expected Results

Client A, Project 1, 1000, $10,000, 2

Client A, Project 2, 5000, $5,000, 1

Client B, Project 1, 100, $3000, 1

Actual Results

Client A, Project 1, 1000, $150,000, 20

Client A, Project 2, 5000, $50,000, 81

Client B, Project 1, 100, $83000, 12

I've tried messing w/ the grouping and join statements but haven't found success. Is there something simple I'm overlooking or do I need a total rewrite?

Body:
Since invoices are dependant on contracts, and contracts are optional (the left join),
make that join also a left join.

SELECT
    c.name as client,
    p.name as project,
    SUM(t.hours) as hours,
    SUM(ci.amount) as invoice_amount,
    COUNT(ci.id) as number_invoices
FROM
    projects p
    INNER JOIN client_master c
        ON c.harvest_id = p.client_id
    INNER JOIN timesheet t
        ON t.project_id = p.id
    LEFT JOIN projects_contracts pc
        ON pc.project_id = p.id
    LEFT JOIN contracts_invoices ci
        ON ci.contract_id = pc.contract_id
GROUP BY
    c.name,
    p.name
ORDER BY
    c.name,
    p.name,
    t.hours


问:
use std::fill to populate vector with increasing numbers
I would like to fill a vector<int> using std::fill, but instead of one value, the vector should contain numbers in increasing order after.

I tried achieving this by iterating the third parameter of the function by one, but this would only give me either vectors filled with 1 or 2 (depending of the position of the ++ operator).

Example:

```<code>vector<int> ivec;
int i = 0;
std::fill(ivec.begin(), ivec.end(), i++); // elements are set to 1
std::fill(ivec.begin(), ivec.end(), ++i); // elements are set to 2
</code>```

答:
We can use generate function which exists in algorithm header file.

Code Snippet :

```<code>#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);

    vector<int>v(10);

    int n=0;

    generate(v.begin(), v.end(), [&n] { return n++;});

    for(auto item : v)
    {
      cout<<item<<" ";
    }
    cout<<endl;

    return 0;
}
</code>```

Body:
I would like to fill a vector<int> using std::fill, but instead of one value, the vector should contain numbers in increasing order after.

I tried achieving this by iterating the third parameter of the function by one, but this would only give me either vectors filled with 1 or 2 (depending of the position of the ++ operator).

Example:

vector<int> ivec;
int i = 0;
std::fill(ivec.begin(), ivec.end(), i++); // elements are set to 1
std::fill(ivec.begin(), ivec.end(), ++i); // elements are set to 2

Body:
We can use generate function which exists in algorithm header file.

Code Snippet :

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);

    vector<int>v(10);

    int n=0;

    generate(v.begin(), v.end(), [&n] { return n++;});

    for(auto item : v)
    {
      cout<<item<<" ";
    }
    cout<<endl;

    return 0;
}


问:
Why does my PHP PDO Select in while not working with page limit? Also issue with Array in select
Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code?  The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates</p>

```<code>for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
      $id2 = $row['id'];
      $name = $row['name'];
      echo 'hello';

    }
}
</code>```

答:
You should replace your limit parameter with a PHP variable:

```<code>$stmt = $conn->prepare("SELECT * FROM tman
    WHERE approve='Y' AND zip=:zipp
    ORDER BY id DESC LIMIT $limiter");
</code>```

According to the PHP PDO::prepare manual in regard to prepared statements:

Use these parameters to bind any user-input, do not include the
  user-input directly in the query.

Since preparing a statement lets you filter user input, these parameters, by design are not allowed to replace any other part of the query that is supposed to be set by a developer. For instance allowing a parameter to replace a table name would provide access to an attacker to use the privileges of the user on anything the user has access to. Likewise, in your situation, LIMIT is provided through MySQL as a query optimization. Exploiting this feature can bring down a system where massive datasets exist.

Also you should wrap your PDO query with a Try/Catch statement to prevent others from seeing your PDO exceptions when they're thrown.

```<code>//Load your IP here
$dev_ip = 'your.ip.address.here';
//Filter the user's IP
$user_ip = filter_input(INPUT_SERVER,'REMOTE_ADDR', FILTER_VALIDATE_IP);
//Set your limiting variable
$limiter = ($pageno-1)*$rows_per_page.','.$rows_per_page;
for($x = 0; $x <= $v; $x++) {
    try {
    $stmt = $conn->prepare("SELECT * FROM tman WHERE approve='Y' AND zip=:zipp ORDER BY id desc LIMIT $limiter");
    $stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
    if(array_key_exists($x, $zipcodeA)&&!empty($zipcodeA[$x])){
        echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if (array_key_exists('id', $result)&&!empty($result['id'])) {
            $id2 = $result['id'];
        } else {
            if($user_ip==$dev_ip){
             echo 'No ID';
            }
        }
        if (array_key_exists('name', $result)&&!empty($result['name'])) {
            $name = $result['name'];
        } else {
            if($user_ip==$dev_ip){
             echo 'No Name';
            }
        }
    }

    } catch(PDOException $ex) {
        echo "An Error occured!"; //user friendly message
        if($user_ip==$dev_ip){
         echo $ex->getMessage();
        }
    }
}
</code>```

Body:
Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code?  The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates

for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '
zipcode: ' . $zipcodeA[$x] . '
';
$stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
      $id2 = $row['id'];
      $name = $row['name'];
      echo 'hello';

    }
}

Body:
You should replace your limit parameter with a PHP variable:

$stmt = $conn->prepare("SELECT * FROM tman
    WHERE approve='Y' AND zip=:zipp
    ORDER BY id DESC LIMIT $limiter");

According to the PHP PDO::prepare manual in regard to prepared statements:

Use these parameters to bind any user-input, do not include the
  user-input directly in the query.

Since preparing a statement lets you filter user input, these parameters, by design are not allowed to replace any other part of the query that is supposed to be set by a developer. For instance allowing a parameter to replace a table name would provide access to an attacker to use the privileges of the user on anything the user has access to. Likewise, in your situation, LIMIT is provided through MySQL as a query optimization. Exploiting this feature can bring down a system where massive datasets exist.

Also you should wrap your PDO query with a Try/Catch statement to prevent others from seeing your PDO exceptions when they're thrown.

//Load your IP here
$dev_ip = 'your.ip.address.here';
//Filter the user's IP
$user_ip = filter_input(INPUT_SERVER,'REMOTE_ADDR', FILTER_VALIDATE_IP);
//Set your limiting variable
$limiter = ($pageno-1)*$rows_per_page.','.$rows_per_page;
for($x = 0; $x <= $v; $x++) {
    try {
    $stmt = $conn->prepare("SELECT * FROM tman WHERE approve='Y' AND zip=:zipp ORDER BY id desc LIMIT $limiter");
    $stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
    if(array_key_exists($x, $zipcodeA)&&!empty($zipcodeA[$x])){
        echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if (array_key_exists('id', $result)&&!empty($result['id'])) {
            $id2 = $result['id'];
        } else {
            if($user_ip==$dev_ip){
             echo 'No ID';
            }
        }
        if (array_key_exists('name', $result)&&!empty($result['name'])) {
            $name = $result['name'];
        } else {
            if($user_ip==$dev_ip){
             echo 'No Name';
            }
        }
    }

    } catch(PDOException $ex) {
        echo "An Error occured!"; //user friendly message
        if($user_ip==$dev_ip){
         echo $ex->getMessage();
        }
    }
}


问:
If a consumer group is subscribed to multiple topic partitions how does kafka decide which it will read first?
I am trying to build a application that can read through a kafka topic but I need it to have a "see previous" button. I know how to seek through a particular partition but is it possible to back through all the messages in a topic in the order that they were read in? I am using Java KafkaConsumer.</p>

答: Offsets are per partition and there is no ordering between messages across different partitions. You can't go back through all the messages in a topic in the order that they were read in as kafka doesn't know the order in which the consumer read in messages from different partitions (different partitions may be read from different brokers across the cluster). However, what you could do is do ordered buffering in your app as you read messages in, that would allow you to go back as far as the buffer capacity.</p>


问:
Convert Number into english Word-Meaning using XSLT
I am very much new to XSLT and have a weird requirement for which I have not found any solution. Server side we have XSLT of version 2.0.

Input number can be from Zero (0) to any value up to 8-digit number.
I need to convert this into its English Word-Meaning following specific format.

If number is of 5 digit (Example - 28651) then First three set will be of 5-Astric (*****) followed by 2-space, so total 7.

If English word of any digit contains less than 5 letter (example 6 SIX then it must be followed by 2+2=4 spaces to make it equivalent to 5 letter English WORD)

For the Last digit of the number must also followed by 2 spaces as above.

```<code>   INPUT       OUTPUT (Without Enclosing Double-Quote)

    9375 = "*****  *****  *****  *****  NINE   THREE  SEVEN  FIVE   "
    8623 = "*****  *****  *****  *****  EIGHT  SIX    TWO    THREE  "
       0 = "*****  *****  *****  *****  *****  *****  *****  ZERO   "
   28651 = "*****  *****  *****  TWO    EIGHT  SIX    FIVE   ONE    "

40378623 = "FOUR   ZERO   THREE  SEVEN  EIGHT  SIX    TWO    THREE  "
</code>```

I am not able to perform any below operation which is quite easy with Java.

1.)  Assign any value to existing variable back.
2.)  Taking the reverse of the number (345 to 543)
3.)  Fetch out each digit separately in any array or something.

This is what I was thinking for its approach.

答:
This is actually not very difficult to do in XSLT 2.0. Consider the following example:

XML

```<code><input>
    <entry>0</entry>
    <entry>12</entry>
    <entry>345</entry>
    <entry>6789</entry>
    <entry>24680</entry>
    <entry>135797</entry>
    <entry>1234567</entry>
    <entry>87654321</entry>
</input>
</code>```

XSLT 2.0

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8" />

<xsl:variable name="strings" select="('ZERO   ', 'ONE    ', 'TWO    ', 'THREE  ', 'FOUR   ', 'FIVE   ', 'SIX    ', 'SEVEN  ', 'EIGHT  ', 'NINE   ')" />

<xsl:template match="/input">
    <xsl:for-each select="entry">
        <!-- padding -->
        <xsl:for-each select="1 to 8 - string-length(.)">
            <xsl:text>*****  </xsl:text>
        </xsl:for-each>
        <!-- digits to strings   -->
        <xsl:for-each select="string-to-codepoints(.)">
            <xsl:variable name="i" select="codepoints-to-string(.) " />
            <xsl:value-of select="$strings[number($i) + 1]"/>
        </xsl:for-each>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

```<code>*****  *****  *****  *****  *****  *****  *****  ZERO
*****  *****  *****  *****  *****  *****  ONE    TWO
*****  *****  *****  *****  *****  THREE  FOUR   FIVE
*****  *****  *****  *****  SIX    SEVEN  EIGHT  NINE
*****  *****  *****  TWO    FOUR   SIX    EIGHT  ZERO
*****  *****  ONE    THREE  FIVE   SEVEN  NINE   SEVEN
*****  ONE    TWO    THREE  FOUR   FIVE   SIX    SEVEN
EIGHT  SEVEN  SIX    FIVE   FOUR   THREE  TWO    ONE
</code>```

Body:
I am very much new to XSLT and have a weird requirement for which I have not found any solution. Server side we have XSLT of version 2.0.

Input number can be from Zero (0) to any value up to 8-digit number.
I need to convert this into its English Word-Meaning following specific format.

If number is of 5 digit (Example - 28651) then First three set will be of 5-Astric (*****) followed by 2-space, so total 7.

If English word of any digit contains less than 5 letter (example 6 SIX then it must be followed by 2+2=4 spaces to make it equivalent to 5 letter English WORD)

For the Last digit of the number must also followed by 2 spaces as above.

   INPUT       OUTPUT (Without Enclosing Double-Quote)

    9375 = "*****  *****  *****  *****  NINE   THREE  SEVEN  FIVE   "
    8623 = "*****  *****  *****  *****  EIGHT  SIX    TWO    THREE  "
       0 = "*****  *****  *****  *****  *****  *****  *****  ZERO   "
   28651 = "*****  *****  *****  TWO    EIGHT  SIX    FIVE   ONE    "

40378623 = "FOUR   ZERO   THREE  SEVEN  EIGHT  SIX    TWO    THREE  "

I am not able to perform any below operation which is quite easy with Java.

1.)  Assign any value to existing variable back.
2.)  Taking the reverse of the number (345 to 543)
3.)  Fetch out each digit separately in any array or something.

This is what I was thinking for its approach.

Body:
This is actually not very difficult to do in XSLT 2.0. Consider the following example:

XML

<input>
    <entry>0</entry>
    <entry>12</entry>
    <entry>345</entry>
    <entry>6789</entry>
    <entry>24680</entry>
    <entry>135797</entry>
    <entry>1234567</entry>
    <entry>87654321</entry>
</input>

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8" />

<xsl:variable name="strings" select="('ZERO   ', 'ONE    ', 'TWO    ', 'THREE  ', 'FOUR   ', 'FIVE   ', 'SIX    ', 'SEVEN  ', 'EIGHT  ', 'NINE   ')" />

<xsl:template match="/input">
    <xsl:for-each select="entry">
        <!-- padding -->
        <xsl:for-each select="1 to 8 - string-length(.)">
            <xsl:text>*****  </xsl:text>
        </xsl:for-each>
        <!-- digits to strings   -->
        <xsl:for-each select="string-to-codepoints(.)">
            <xsl:variable name="i" select="codepoints-to-string(.) " />
            <xsl:value-of select="$strings[number($i) + 1]"/>
        </xsl:for-each>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Result

*****  *****  *****  *****  *****  *****  *****  ZERO
*****  *****  *****  *****  *****  *****  ONE    TWO
*****  *****  *****  *****  *****  THREE  FOUR   FIVE
*****  *****  *****  *****  SIX    SEVEN  EIGHT  NINE
*****  *****  *****  TWO    FOUR   SIX    EIGHT  ZERO
*****  *****  ONE    THREE  FIVE   SEVEN  NINE   SEVEN
*****  ONE    TWO    THREE  FOUR   FIVE   SIX    SEVEN
EIGHT  SEVEN  SIX    FIVE   FOUR   THREE  TWO    ONE


问:
How to create a list of string in nth position of every line in Python
What would be a pythonic way to create a list of (to illustrate with an example) the fifth string of every line of a text file, assuming it ressembles something like this:

12, 27.i, 3, 6.7, Hello, 438

In this case, the script would add "Hello" (without quotes) to the list.

In other words (to generalize), with an input "input.txt", how could I get a list in python that takes the nth string (n being a defined number) of every line?

Many thanks in advance!

答:
You could use the csv module to read the file, and store all items in the fifth column in a list:

```<code>import csv

with open(my_file) as f:
    lst = [row[4] for row in csv.reader(f)]
</code>```

Body:
You could use the csv module to read the file, and store all items in the fifth column in a list:

import csv

with open(my_file) as f:
    lst = [row[4] for row in csv.reader(f)]


问:
How to access Array elements in JSON object using handlebars

var express = require('express');
var router = express.Router();

var data = {

    curreny :{
         name:'United States dollars',
         abbrev:'USD'

},
tours:[
  {name: 'Hood River' , price:'100'},
  {name: 'Sri lanka' , price:'150'},
  {name: 'Hood River' , price:'178'}
],
specialsUrl:'/january-specials'

}

router.get('/detour',function(req,res){
    res.render('tours',{object:data});
})
module.exports = router;```
</div>
</div>
</p>

<p>Above is the code I used to export JSON object into handlebars. I need to access tour details in the tour array in a handlebars file. How can I access those details to make a list of tour details inside h3 tag. Following is the sample tour.handlebars file. Thanks in advance. </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-html lang-html prettyprint-override"><code><h2> Hello this is the body section</h2>
<h3>currency : {{object.curreny.name}}</h3>

<h3>tours : {{object.tours.body}}</h3></code>```

答:
You can iterate over your tours array and then use it in handlebars like this:

```<code>{{#each object.tours}}
    <h3>name: {{name}} </h3>
    <h3>price: {{price}} </h3>
{{/each}}
</code>```

Body:
var express = require('express');
var router = express.Router();

var data = {

    curreny :{
         name:'United States dollars',
         abbrev:'USD'

},
tours:[
  {name: 'Hood River' , price:'100'},
  {name: 'Sri lanka' , price:'150'},
  {name: 'Hood River' , price:'178'}
],
specialsUrl:'/january-specials'

}

router.get('/detour',function(req,res){
    res.render('tours',{object:data});
})
module.exports = router;

Above is the code I used to export JSON object into handlebars. I need to access tour details in the tour array in a handlebars file. How can I access those details to make a list of tour details inside h3 tag. Following is the sample tour.handlebars file. Thanks in advance.

 Hello this is the body section

currency : {{object.curreny.name}}

tours : {{object.tours.body}}

Body:
You can iterate over your tours array and then use it in handlebars like this:

{{#each object.tours}}
    <h3>name: {{name}} </h3>
    <h3>price: {{price}} </h3>
{{/each}}


问:
VBA-Excel : How can I verify if options->Formulas is set to automatic?
So, I'm programming a macro and I'm not very "really good" at the moment in this kind of coding.

How can I verify if in the options->formulas is set to automatic in VBA Excel?

Thanks!

QcHaxing

答:
Here you go:

```<code>Application.Calculation = xlAutomatic
</code>```

To make the calculations manual:

```<code>Application.Calculation = xlManual
</code>```

EDIT:

If you wish to "check" whether it Options->Formulas is set to automatic, you can do that.

```<code>If Application.Calculation = xlManual Then
    *** Do some action you desire, like printing "Yes" in A1, or something ***

Else
    *** Do some action you desire, like printing "No" in A1, or something ***
End If
</code>```

Or, as @Masoud suggested:

```<code>debug.print Application.Calculation
</code>```

Body:
Here you go:

Application.Calculation = xlAutomatic

To make the calculations manual:

Application.Calculation = xlManual

EDIT:

If you wish to "check" whether it Options->Formulas is set to automatic, you can do that.

If Application.Calculation = xlManual Then
    *** Do some action you desire, like printing "Yes" in A1, or something ***

Else
    *** Do some action you desire, like printing "No" in A1, or something ***
End If

Or, as @Masoud suggested:

debug.print Application.Calculation


问:
XSLT: Ignore duplicates similar values
I am working on XSLT which has a logic to ignore duplicates using (MySegment/*[not(.=preceding::*)]).

Input:

```<code><MySegment>
  <Field1>ABCD</Field1>
  <FIeld2>1</Field2>
</MySegment>
<MySegment>
  <Field1>ABCD123</Field1>
  <FIeld2>1</Field2>
</MySegment>
</code>```

Here we have two distinct values, however since ABCD123 contains ABCD as well,its being treated as a duplicate entry. Can anyone advise.

Here is how my XSLT looks like:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="/RecordsInp">

    <xsl:for-each select="ParentSegment">

      <xsl:for-each select="./MySegment/*[not(.=preceding::*)]">

        <A>
          <Field1><xsl:value-of select ="name(.)"/></Field1>
          <Field2><xsl:value-of select="."/></Field2>
        </A>

      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
</code>```

My input is:

```<code><RecordsInp>
  <ParentSegment>
    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABCDEF</Field1>
      <Field2>ABC</Field2>
    </MySegment>
  </ParentSegment>
</RecordsInp>
</code>```

What I am getting is:

```<code> <?xml version="1.0" encoding="UTF-8"?>
    <A>
      <Field1>Field1</Field1>
      <Field2>ABC</Field2>
    </A><A>
      <Field1>Field2</Field1>
      <Field2>A1</Field2>
    </A><A>
      <Field1>Field1</Field1>
      <Field2>ABCDEF</Field2>
    </A>
</code>```

Notice I am not getting Field2=ABC in the last occurrence. Since Field2 never had ABC in previous occurrences, I need below XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<A>
  <Field1>Field1</Field1>
  <Field2>ABC</Field2>
</A><A>
  <Field1>Field2</Field1>
  <Field2>A1</Field2>
</A><A>
  <Field1>Field1</Field1>
  <Field2>ABCDEF</Field2>
</A>
<A>
  <Field1>Field2</Field1>
  <Field2>ABC</Field2>
</A>
</code>```

答:
Based on your second input example, the reason your stylesheet isn't pulling <Field2>ABC</Field2> the way you expect is because ABC exists as a value in a preceding Field1.

You could also test the name against the current (current()) name in the predicate, but maybe you should try using an xsl:key (Muenchian grouping) instead of the preceding:: axis...

XML Input

```<code><RecordsInp>
    <ParentSegment>
        <MySegment>
            <Field1>ABC</Field1>
            <Field2>A1</Field2>
        </MySegment>
        <MySegment>
            <Field1>ABC</Field1>
            <Field2>A1</Field2>
        </MySegment>
        <MySegment>
            <Field1>ABCDEF</Field1>
            <Field2>ABC</Field2>
        </MySegment>
    </ParentSegment>
</RecordsInp>
</code>```

XSLT 1.0

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="fields" match="MySegment/*"
    use="concat(name(),'|',normalize-space())"/>

  <xsl:template match="MySegment">
    <xsl:for-each
      select="*[count(.|key('fields',concat(name(),'|',normalize-space()))[1])=1]">
      <A>
        <Field1><xsl:value-of select="name()"/></Field1>
        <Field2><xsl:value-of select="."/></Field2>
      </A>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>
</code>```

Output

```<code><A>
   <Field1>Field1</Field1>
   <Field2>ABC</Field2>
</A>
<A>
   <Field1>Field2</Field1>
   <Field2>A1</Field2>
</A>
<A>
   <Field1>Field1</Field1>
   <Field2>ABCDEF</Field2>
</A>
<A>
   <Field1>Field2</Field1>
   <Field2>ABC</Field2>
</A>
</code>```

ContentLicense: CC BY-SA 4.0

Title: XSLT: Ignore duplicates similar values

Body:
I am working on XSLT which has a logic to ignore duplicates using (MySegment/*[not(.=preceding::*)]).

Input:

<MySegment>
  <Field1>ABCD</Field1>
  <FIeld2>1</Field2>
</MySegment>
<MySegment>
  <Field1>ABCD123</Field1>
  <FIeld2>1</Field2>
</MySegment>

Here we have two distinct values, however since ABCD123 contains ABCD as well,its being treated as a duplicate entry. Can anyone advise.

Here is how my XSLT looks like:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="/RecordsInp">

    <xsl:for-each select="ParentSegment">

      <xsl:for-each select="./MySegment/*[not(.=preceding::*)]">

          <Field1><xsl:value-of select ="name(.)"/></Field1>
          <Field2><xsl:value-of select="."/></Field2>

      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

My input is:

<RecordsInp>
  <ParentSegment>
    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABC</Field1>
      <Field2>A1</Field2>
    </MySegment>

    <MySegment>
      <Field1>ABCDEF</Field1>
      <Field2>ABC</Field2>
    </MySegment>
  </ParentSegment>
</RecordsInp>

What I am getting is:

 <?xml version="1.0" encoding="UTF-8"?>

      <Field1>Field1</Field1>
      <Field2>ABC</Field2>

      <Field1>Field2</Field1>
      <Field2>A1</Field2>

      <Field1>Field1</Field1>
      <Field2>ABCDEF</Field2>

Notice I am not getting Field2=ABC in the last occurrence. Since Field2 never had ABC in previous occurrences, I need below XML:

<?xml version="1.0" encoding="UTF-8"?>

  <Field1>Field1</Field1>
  <Field2>ABC</Field2>

  <Field1>Field2</Field1>
  <Field2>A1</Field2>

  <Field1>Field1</Field1>
  <Field2>ABCDEF</Field2>

  <Field1>Field2</Field1>
  <Field2>ABC</Field2>

Body:
Based on your second input example, the reason your stylesheet isn't pulling <Field2>ABC</Field2> the way you expect is because ABC exists as a value in a preceding Field1.

You could also test the name against the current (current()) name in the predicate, but maybe you should try using an xsl:key (Muenchian grouping) instead of the preceding:: axis...

XML Input

<RecordsInp>
    <ParentSegment>
        <MySegment>
            <Field1>ABC</Field1>
            <Field2>A1</Field2>
        </MySegment>
        <MySegment>
            <Field1>ABC</Field1>
            <Field2>A1</Field2>
        </MySegment>
        <MySegment>
            <Field1>ABCDEF</Field1>
            <Field2>ABC</Field2>
        </MySegment>
    </ParentSegment>
</RecordsInp>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="fields" match="MySegment/*"
    use="concat(name(),'|',normalize-space())"/>

  <xsl:template match="MySegment">
    <xsl:for-each
      select="*[count(.|key('fields',concat(name(),'|',normalize-space()))[1])=1]">
      <A>
        <Field1><xsl:value-of select="name()"/></Field1>
        <Field2><xsl:value-of select="."/></Field2>
      </A>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

Output

<A>
   <Field1>Field1</Field1>
   <Field2>ABC</Field2>
</A>
<A>
   <Field1>Field2</Field1>
   <Field2>A1</Field2>
</A>
<A>
   <Field1>Field1</Field1>
   <Field2>ABCDEF</Field2>
</A>
<A>
   <Field1>Field2</Field1>
   <Field2>ABC</Field2>
</A>


答:
You might try a solution like this

```<code>trans <- list(
  Li=identity,
  Sq=function(x) x^2,
  Ps=function(x) log(x)
)

cpredict<-function(betas, datas) {
  Map(function(var, fun, coef) {
    trans[[fun]](datas[[var]])*coef
  }, betas$CovGen, betas$Form, betas$Estimate)
}

cpredict(betas, dat)
</code>```

But this won't work with your current data because there is no dat$A and you can't take the log of a negative number.

Title: manually predict with different functional forms

Body:
I have a data frame with coefficients from a glm (betas below). The data frame contains the covariate label, covariate form, and the estimate. The forms are linear (Li), squared/quadratic (Sq), and log (Ps).

betas <- structure(list(CovGen = c("A", "B", "C", "D", "E", "F", "G",
                                   "G", "H"), Form = c("Li", "Li", "Li", "Li", "Li", "Li", "Li",
                                                       "Sq", "Ps"), Estimate = c(0.0294573176934061, 0.0100315121169383,
                                                                                -0.0155864186367343, -0.00871344935814372, 0.0362538988332902,
                                                                                -0.0263072916746069, 0.0865742118052235, 0.0614689145750204,
                                                                                0.00229745713752781)), .Names = c("CovGen", "Form", "Estimate"
                                                                                ), row.names = c(NA, 9L), class = "data.frame")

betas
  CovGen Form     Estimate
1      A   Li  0.029457318
2      B   Li  0.010031512
3      C   Li -0.015586419
4      D   Li -0.008713449
5      E   Li  0.036253899
6      F   Li -0.026307292
7      G   Li  0.086574212
8      G   Sq  0.061468915
9      H   Ps  0.002297457

I trying to apply the coefficient estimates to manually predict values for a new data frame (dat included here with dput).

dat <- structure(list(B = c(-1.47218074669544, -1.46929972689195, -1.46641870708846,
                            -1.46353768728497, -1.46065666748148, -1.45777564767799), C = c(-1.09847692593512,
                                                                                -1.09375316152745, -1.08902939711978, -1.08430563271211, -1.07958186830444,
                                                                                -1.07485810389677), D = c(-1.0109875688763, -1.00407851818141,
                                                                                -0.997169467486518, -0.990260416791627, -0.983351366096736, -0.976442315401845
                                                                                ), E = c(-3.19632050296668, -3.19041566990116, -3.18451083683563,
                                                                                -3.17860600377011, -3.17270117070458, -3.16679633763906), F = c(-2.81211918021003,
                                                                                -2.80673925496675, -2.80135932972346, -2.79597940448018, -2.7905994792369,
                                                                                -2.78521955399362), G = c(-2.32916817000267, -2.32368219245727,
                                                                                -2.31819621491187, -2.31271023736647, -2.30722425982107, -2.30173828227567
                                                                                ), H = c(0.442067970883549, 0.417909464459238, 0.393750958034926,
                                                                                0.369592451610615, 0.345433945186303, 0.321275438761992)), .Names = c("B",
                                                                                "C", "D", "E", "F", "G", "H"), row.names = c(NA, 6L), class = "data.frame")                                                                                "C", "D", "E", "F", "G", "H"), row.names = c(NA, 6L), class = "data.frame")

> dat
          B         C          D         E         F         G         H
1 -1.472181 -1.098477 -1.0109876 -3.196321 -2.812119 -2.329168 0.4420680
2 -1.469300 -1.093753 -1.0040785 -3.190416 -2.806739 -2.323682 0.4179095
3 -1.466419 -1.089029 -0.9971695 -3.184511 -2.801359 -2.318196 0.3937510
4 -1.463538 -1.084306 -0.9902604 -3.178606 -2.795979 -2.312710 0.3695925
5 -1.460657 -1.079582 -0.9833514 -3.172701 -2.790599 -2.307224 0.3454339
6 -1.457776 -1.074858 -0.9764423 -3.166796 -2.785220 -2.301738 0.3212754

I am trying to multiply the new data values in the dat df by the respective betas and account for functional forms. More specifically, in the example included here, I want to apply the Sq form of the G beta to dat$G^2 and the Ps H beta to log(dat$H). All other betas and values can simply be multiplied directly without accounting for functional forms. Note that the A beta is not applied to a new value in the dat df.

I may need to work through an award ifelse statement but am wondering if there are other ideas and/or suggestions.

I am working within a larger loop and will not have a consistent form for each covariate.

The desired result would be a matrix or df with a column containing the predicted values for each beta-form combination. For example, there would be a single column containing predicted values for all betas except for G which would have predicted values for G and G^2.

Thanks in advance.

Body:
You might try a solution like this

trans <- list(
  Li=identity,
  Sq=function(x) x^2,
  Ps=function(x) log(x)
)

cpredict<-function(betas, datas) {
  Map(function(var, fun, coef) {
    trans[[fun]](datas[[var]])*coef
  }, betas$CovGen, betas$Form, betas$Estimate)
}

cpredict(betas, dat)

But this won't work with your current data because there is no dat$A and you can't take the log of a negative number.


问:
How to detect proxy requests?
I know it is popular question, and I read all topics about it. I want to put point for me in this question.

Goal: Detect proxy if user use it

Reason: If user use proxy does not show geo adv. I need to know bool result.

Decision:
 1. Use database of proxy IPs (for ex: MaxMind);
 2. Check header Connection: keep-alive because cheap proxy does not use persistent connection. But all modern browsers use it;
 3. Check other popular headers;
 4. Use JS to detect web-proxy by compare browser host and real host.

Questions:
 1. Advise database, I read about MaxMind, but some people wrote it is not effective.
 2. Check Connection-header. Is it okey?
 3. May be I missed something?

PS/ Sorry for my english... I learn it.

答:
The best way is definitely to use an API. You could use the database from MaxMind but then you need to keep downloading that database and making sure the data is kept up to date by them. And as you said there are questions about the accuracy of MaxMind data.

Personally I would recommend you try https://proxycheck.io which full disclosure is my own site, you get full access to everything for free, premium proxy detecting and blocking with 1,000 daily queries.

Title: How to detect proxy requests?


问:
Reading binary data from file in Python and passing it to a C++ function
How to pass binary data loaded by Python directly from a file to a C++ function taking data pointer and size called in a Cython module?

```<code>loadFromMemory(const void*, size_t)
</code>```

This is probably how it would look like in pure Python:

```<code>with open('file.bin', 'rb') as f:
    data = f.read()
    loadFromMemory(data, len(data))  # How to do this in Cython?
</code>```

答:
You need a two step cast first to a char* (which Cython can get easily from a string) and then second to reinterpret that as a void*:

```<code>loadFromMemory(<void*>(<char*>data), len(data))
</code>```

This does assume that loadFromMemory doesn't expect the pointer to remain valid after the function call (Cython won't manage the memory for you automatically, and it'll be freed when data is destroyed).

(Skipping the cast to char* and just casting straight to a void* will take the address of the Python object, which isn't what you want)

Body:
How to pass binary data loaded by Python directly from a file to a C++ function taking data pointer and size called in a Cython module?

loadFromMemory(const void*, size_t)

This is probably how it would look like in pure Python:

with open('file.bin', 'rb') as f:
    data = f.read()
    loadFromMemory(data, len(data))  # How to do this in Cython?

Body:
You need a two step cast first to a char* (which Cython can get easily from a string) and then second to reinterpret that as a void*:

loadFromMemory(<void*>(<char*>data), len(data))

This does assume that loadFromMemory doesn't expect the pointer to remain valid after the function call (Cython won't manage the memory for you automatically, and it'll be freed when data is destroyed).

(Skipping the cast to char* and just casting straight to a void* will take the address of the Python object, which isn't what you want)


问:
Adding www, trailing slash to URL using Apache with clean urls
I am using an .htaccess file to send all requests to index.php like so:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

I also want to have requests without www to be redirected to www.mydomain.com and most importantly add a trailing slash to all urls that don't have one.  Every time I try to do this I end up with a 500 error.  Anyone know how to do this?

Thanks for the help.

答:
```<code>RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
</code>```

there is also a webpage specially made for that reason: http://no-www.org/

cheers Simon

ContentLicense: CC BY-SA 2.5

Body:
I am using an .htaccess file to send all requests to index.php like so:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I also want to have requests without www to be redirected to www.mydomain.com and most importantly add a trailing slash to all urls that don't have one.  Every time I try to do this I end up with a 500 error.  Anyone know how to do this?

Thanks for the help.

Body:
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

there is also a webpage specially made for that reason: http://no-www.org/

cheers Simon


问:
(swift) remove "\" character from string?
I have string which contains few \ and I want to remove all of them. can anyone tell me how can I do that. I have already tried stringByReplacingOccurrencesOfString but it's not working out for me.

答:
Converted above code in to SWIFT 3</p>

```<code>    var str = "\\dagdahughuad\\dajughdaug"
    var str2 = str.replacingOccurrences(of: "\\", with: "", options:
    NSString.CompareOptions.literal, range: nil)
    print(str2)
</code>```

Body:
Converted above code in to SWIFT 3

    var str = "\\dagdahughuad\\dajughdaug"
    var str2 = str.replacingOccurrences(of: "\\", with: "", options:
    NSString.CompareOptions.literal, range: nil)
    print(str2)


问:
Tensorflow Model for Image similarity detection
I have just started playing with tensor-flow .I am searching algorithm or code in tensor-flow or any other that can help me regarding following problem.
There are 10,000 images in my folder and i want to show them in my app.I dont want the similar images to be shown. For instance i have 10 selfie at a same place so i just want to show 1 instead of 10. We can take the example of google photo app or apple photo library.I also have tried some hash algorithm but for some images they failed to show results.Thanks</p>

答: K-means is a good clustering algorithm. It would allow you to group images in clusters, so that you could only show one image from each cluster. It is availabile in sklearn.</p>


问:
Google DFP - Refresh AD slot without New Impression Count
I need to refresh all ad slots after 15 sec and load new ads to the slots without counting new impression.
** This works :

```<code>googletag.pubads().refresh([slot1], {changeCorrelator: false});
</code>```

**but when I add the set interval 30 sec.. it is not refreshing-

```<code>setInterval(function(){googletag.pubads().refresh(null, {changeCorrelator: false}, 30000)});
</code>```

Pls help..Tnx

答:
The syntax is:

```<code>setInterval(function, milliseconds)
</code>```

The code bellow should work:

```<code>setInterval(function(){
    googletag.pubads().refresh(null, {changeCorrelator: false});
}, 30000);
</code>```

Body:
I need to refresh all ad slots after 15 sec and load new ads to the slots without counting new impression.
** This works :

googletag.pubads().refresh([slot1], {changeCorrelator: false});

**but when I add the set interval 30 sec.. it is not refreshing-

setInterval(function(){googletag.pubads().refresh(null, {changeCorrelator: false}, 30000)});

Pls help..Tnx

Body:
The syntax is:

setInterval(function, milliseconds)

The code bellow should work:

setInterval(function(){
    googletag.pubads().refresh(null, {changeCorrelator: false});
}, 30000);


问:
Undefined index: user when I display notification json array in laravel
When try to display the json data it gives the Undefined index: user exception

```<code>  foreach(auth()->user()->unreadnotifications as $notifications)

       @include('frontend.common.notification.'.snake_case(class_basename($notifications->type)))

  @endforeach
</code>```

Included view code is

```<code>  <div>
    <i class="fa fa-comment fa-fw"></i>
    <img src="{{url('images/account/'.$notifications->data['user']['currentimage'])}}" height="50px" width="50"/>
    {{$notifications->data['user']['email']}} commented on your post.
    <span class="pull-right text-muted small">{{$notifications->created_at->diffForHumans()}}</span>
</div>
</code>```

Json Object is

{"comment":{"comment":"I am awesome","user_id":2,"post_id":"2","commment_rate":90,"updated_at":"2017-07-06 16:32:07","created_at":"2017-07-06 16:32:07","id":18},"user":{"id":2,"email":"test2@mail.com","currentimage":"1499004938.jpg","role":0,"verified":null,"blocked":null,"created_at":"2017-07-02 13:44:24","updated_at":"2017-07-02 14:15:38"}}

答:
After looking at your code I assume you are using foreach loop on the collection.

```<code>  <div>
<i class="fa fa-comment fa-fw"></i>
<img src="{{url('images/account/'.$notifications->user->currentimage}}" height="50px" width="50"/>
{{$notifications->user->email}} commented on your post.
<span class="pull-right text-muted small">{{$notifications->created_at->diffForHumans()}}</span>
</code>```

Body:
When try to display the json data it gives the Undefined index: user exception

  foreach(auth()->user()->unreadnotifications as $notifications)

       @include('frontend.common.notification.'.snake_case(class_basename($notifications->type)))

  @endforeach

Included view code is

    data['user']['currentimage'])}}" height="50px" width="50"/>
    {{$notifications->data['user']['email']}} commented on your post.
    {{$notifications->created_at->diffForHumans()}}

Json Object is

{"comment":{"comment":"I am awesome","user_id":2,"post_id":"2","commment_rate":90,"updated_at":"2017-07-06 16:32:07","created_at":"2017-07-06 16:32:07","id":18},"user":{"id":2,"email":"test2@mail.com","currentimage":"1499004938.jpg","role":0,"verified":null,"blocked":null,"created_at":"2017-07-02 13:44:24","updated_at":"2017-07-02 14:15:38"}}

Body:
After looking at your code I assume you are using foreach loop on the collection.

  <div>
<i class="fa fa-comment fa-fw"></i>
<img src="{{url('images/account/'.$notifications->user->currentimage}}" height="50px" width="50"/>
{{$notifications->user->email}} commented on your post.
<span class="pull-right text-muted small">{{$notifications->created_at->diffForHumans()}}</span>


问:
Issue caching images with custom collection view cell using KingFisher
I'm using Kingfisher to cache an image that is stored in Firebase. I'm retrieving the image with a url call to Firebase, then attempting to cache that image for re-use. The below logic in configureCell(with video:Video) was previously in cellForItemAt and the image caching worked just fine. However, after moving this logic to the custom cell and calling this function from cellForItemAt, the images aren't being retrieved through the cache. Every image is downloaded, then re-downloaded if it re-appears in the collection view. My code is below. Thanks for the help in advance.

```<code>class ProminentVideoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!

func configureCell(with video:Video) {
    self.timeLabel.text = video.date?.getElapsedInterval()
    let thumbnailImageView = UIImageView()
    ImageCache.default.retrieveImage(forKey: video.thumbnailurl!, options: nil) {
        image, cacheType in
        if let image = image {
            //Video thumbnail exists in cache--set it
            thumbnailImageView.image = image
            self.backgroundView = thumbnailImageView
            print("Get image \(image), cacheType: \(cacheType).")

        } else {
            //Video thumbnail does NOT exist in cache, download it
            video.downloadThumbnailFromStorage(with: { (url) in
                let resource = ImageResource(downloadURL: url, cacheKey: video.thumbnailurl!)
                let processor = BlurImageProcessor(blurRadius: 40.0) >> RoundCornerImageProcessor(cornerRadius: 20)

                thumbnailImageView.kf.setImage(with: resource, options: [.processor(processor)])
                self.backgroundView = thumbnailImageView
            })

        }
    }
}
</code>```

In my View Controller:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let currentVideo = self.selectedVideosArray.object(at: indexPath.row) as! Video
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ProminentVideoCollectionViewCell
        cell.configureCell(with: currentVideo)
        return cell
}
</code>```

答:
I added the below code to ensure the caching mechanism worked. Not entirely sure why the thumbnailImageView.kf.setImage wasn't caching the images, but adding the below code did the trick.

```<code>//Video thumbnail does NOT exist in cache, download it
            video.downloadThumbnailFromStorage(with: { (url) in
                let resource = ImageResource(downloadURL: url, cacheKey: video.thumbnailurl!)
                let processor = BlurImageProcessor(blurRadius: 40.0) >> RoundCornerImageProcessor(cornerRadius: 20)

                thumbnailImageView.kf.setImage(with: resource, options: [.processor(processor)], completionHandler: { (image, error, cacheType, url) in
                    ImageCache.default.store(image!, forKey: video.thumbnailurl!)
                    self.backgroundView = thumbnailImageView
                })
            })
</code>```

Body:
I'm using Kingfisher to cache an image that is stored in Firebase. I'm retrieving the image with a url call to Firebase, then attempting to cache that image for re-use. The below logic in configureCell(with video:Video) was previously in cellForItemAt and the image caching worked just fine. However, after moving this logic to the custom cell and calling this function from cellForItemAt, the images aren't being retrieved through the cache. Every image is downloaded, then re-downloaded if it re-appears in the collection view. My code is below. Thanks for the help in advance.

class ProminentVideoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!

func configureCell(with video:Video) {
    self.timeLabel.text = video.date?.getElapsedInterval()
    let thumbnailImageView = UIImageView()
    ImageCache.default.retrieveImage(forKey: video.thumbnailurl!, options: nil) {
        image, cacheType in
        if let image = image {
            //Video thumbnail exists in cache--set it
            thumbnailImageView.image = image
            self.backgroundView = thumbnailImageView
            print("Get image \(image), cacheType: \(cacheType).")

        } else {
            //Video thumbnail does NOT exist in cache, download it
            video.downloadThumbnailFromStorage(with: { (url) in
                let resource = ImageResource(downloadURL: url, cacheKey: video.thumbnailurl!)
                let processor = BlurImageProcessor(blurRadius: 40.0) >> RoundCornerImageProcessor(cornerRadius: 20)

                thumbnailImageView.kf.setImage(with: resource, options: [.processor(processor)])
                self.backgroundView = thumbnailImageView
            })

        }
    }
}

In my View Controller:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let currentVideo = self.selectedVideosArray.object(at: indexPath.row) as! Video
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ProminentVideoCollectionViewCell
        cell.configureCell(with: currentVideo)
        return cell
}

Body:
I added the below code to ensure the caching mechanism worked. Not entirely sure why the thumbnailImageView.kf.setImage wasn't caching the images, but adding the below code did the trick.

//Video thumbnail does NOT exist in cache, download it
            video.downloadThumbnailFromStorage(with: { (url) in
                let resource = ImageResource(downloadURL: url, cacheKey: video.thumbnailurl!)
                let processor = BlurImageProcessor(blurRadius: 40.0) >> RoundCornerImageProcessor(cornerRadius: 20)

                thumbnailImageView.kf.setImage(with: resource, options: [.processor(processor)], completionHandler: { (image, error, cacheType, url) in
                    ImageCache.default.store(image!, forKey: video.thumbnailurl!)
                    self.backgroundView = thumbnailImageView
                })
            })


问:
Query city names starting and ending with vowels
I wrote this code (db2) and it works just fine, but I'm wondering, is there a shorter way to write this?</p>
```<code>Select Distinct city
From   station
Where  city Like 'A%a'
       Or city Like 'A%e'
       Or city Like 'A%i'
       Or city Like 'A%o'
       Or city Like 'A%u'
       Or city Like 'E%a'
       Or city Like 'E%e'
       Or city Like 'E%i'
       Or city Like 'E%o'
       Or city Like 'E%u'
       Or city Like 'I%a'
       Or city Like 'I%e'
       Or city Like 'I%i'
       Or city Like 'I%o'
       Or city Like 'I%u'
       Or city Like 'O%a'
       Or city Like 'O%e'
       Or city Like 'O%i'
       Or city Like 'O%o'
       Or city Like 'O%u'
       Or city Like 'U%a'
       Or city Like 'U%e'
       Or city Like 'U%i'
       Or city Like 'U%o'
       Or city Like 'U%u';
</code>```

答:
I am not a DB2 expert but this should be fairly portable:

```<code>WHERE LEFT(city,1) IN ('A', 'E', 'I', 'O', 'U')
  AND RIGHT(city,1) IN ('a', 'e', 'i', 'o', 'u')
</code>```

You may want to normalize it all to upper case to avoid problems with cities that for some reason start with a lower case letter or end with an upper case letter.

```<code>WHERE UPPER(LEFT(city,1)) IN ('A', 'E', 'I', 'O', 'U')
  AND LOWER(RIGHT(city,1)) IN ('a', 'e', 'i', 'o', 'u')
</code>```

Body:
I wrote this code (db2) and it works just fine, but I'm wondering, is there a shorter way to write this?

Select Distinct city
From   station
Where  city Like 'A%a'
       Or city Like 'A%e'
       Or city Like 'A%i'
       Or city Like 'A%o'
       Or city Like 'A%u'
       Or city Like 'E%a'
       Or city Like 'E%e'
       Or city Like 'E%i'
       Or city Like 'E%o'
       Or city Like 'E%u'
       Or city Like 'I%a'
       Or city Like 'I%e'
       Or city Like 'I%i'
       Or city Like 'I%o'
       Or city Like 'I%u'
       Or city Like 'O%a'
       Or city Like 'O%e'
       Or city Like 'O%i'
       Or city Like 'O%o'
       Or city Like 'O%u'
       Or city Like 'U%a'
       Or city Like 'U%e'
       Or city Like 'U%i'
       Or city Like 'U%o'
       Or city Like 'U%u';

Body:
I am not a DB2 expert but this should be fairly portable:

WHERE LEFT(city,1) IN ('A', 'E', 'I', 'O', 'U')
  AND RIGHT(city,1) IN ('a', 'e', 'i', 'o', 'u')

You may want to normalize it all to upper case to avoid problems with cities that for some reason start with a lower case letter or end with an upper case letter.

WHERE UPPER(LEFT(city,1)) IN ('A', 'E', 'I', 'O', 'U')
  AND LOWER(RIGHT(city,1)) IN ('a', 'e', 'i', 'o', 'u')


问:
how to jump from signup page to the next activity on the click of the signup button
ok, so I made a signup page in my application that shows up when the app starts. I used if and else statement that if none of the fields are empty, then it shows "login successful" on the click of the sign-up button on the screen else it shows"Login unsuccessful". i want to add a code in the if portion that if none of the fields are empty, then it shows"login successful" on the click of the sign up button and proceeds to the next activity which is actually the real application supposed to be displayed after the sign up page else it shows "Login unsuccessful" but can't figure out how. and I'm a beginner in android programming too.</p>

```<code> Button mShowdialog = (Button) findViewById(R.id.btnShowDialog);

    mShowdialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
            final EditText mEmail = (EditText) mView.findViewById(R.id.edtEmail);
            final EditText mPassword = (EditText) mView.findViewById(R.id.edtPassword);
            Button mLogin = (Button) mView.findViewById(R.id.btnLogin);
            mLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!mEmail.getText().toString().isEmpty()
                            && !mPassword.getText().toString().isEmpty()) {

                        Toast.makeText(MainActivity.this,
                                R.string.Success_Login_msg,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this,
                                R.string.error_login_msg,
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    });
</code>```

答:
This is all you need inside of your onclick method:

```<code>Button mShowdialog = (Button) findViewById(R.id.btnShowDialog);

mShowdialog.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
        View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
        final EditText mEmail = (EditText) mView.findViewById(R.id.edtEmail);
        final EditText mPassword = (EditText) mView.findViewById(R.id.edtPassword);
        Button mLogin = (Button) mView.findViewById(R.id.btnLogin);
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mEmail.getText().toString().isEmpty()
                        && !mPassword.getText().toString().isEmpty()) {

                   **Context context = v.getContext();
                   context.startActivity(new Intent(context, LoggedInActivity.class));**

                    Toast.makeText(MainActivity.this,
                            R.string.Success_Login_msg,
                            Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(MainActivity.this,
                            R.string.error_login_msg,
                            Toast.LENGTH_SHORT).show();
                }

            }

        });

    }
});
</code>```

Albeit, you'll need to change "LoggedInActivity.class" to the actual name of the activity you'd like to start.

Body:
ok, so I made a signup page in my application that shows up when the app starts. I used if and else statement that if none of the fields are empty, then it shows "login successful" on the click of the sign-up button on the screen else it shows"Login unsuccessful". i want to add a code in the if portion that if none of the fields are empty, then it shows"login successful" on the click of the sign up button and proceeds to the next activity which is actually the real application supposed to be displayed after the sign up page else it shows "Login unsuccessful" but can't figure out how. and I'm a beginner in android programming too.

 Button mShowdialog = (Button) findViewById(R.id.btnShowDialog);

    mShowdialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
            final EditText mEmail = (EditText) mView.findViewById(R.id.edtEmail);
            final EditText mPassword = (EditText) mView.findViewById(R.id.edtPassword);
            Button mLogin = (Button) mView.findViewById(R.id.btnLogin);
            mLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!mEmail.getText().toString().isEmpty()
                            && !mPassword.getText().toString().isEmpty()) {

                        Toast.makeText(MainActivity.this,
                                R.string.Success_Login_msg,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this,
                                R.string.error_login_msg,
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    });

Body:
This is all you need inside of your onclick method:

Button mShowdialog = (Button) findViewById(R.id.btnShowDialog);

mShowdialog.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
        View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
        final EditText mEmail = (EditText) mView.findViewById(R.id.edtEmail);
        final EditText mPassword = (EditText) mView.findViewById(R.id.edtPassword);
        Button mLogin = (Button) mView.findViewById(R.id.btnLogin);
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mEmail.getText().toString().isEmpty()
                        && !mPassword.getText().toString().isEmpty()) {

                   **Context context = v.getContext();
                   context.startActivity(new Intent(context, LoggedInActivity.class));**

                    Toast.makeText(MainActivity.this,
                            R.string.Success_Login_msg,
                            Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(MainActivity.this,
                            R.string.error_login_msg,
                            Toast.LENGTH_SHORT).show();
                }

            }

        });

    }
});

Albeit, you'll need to change "LoggedInActivity.class" to the actual name of the activity you'd like to start.


问:
Magento2 addFieldToFilter call works with hardcoded value but not variable with same value
I'm building the admin for a Magento2 store (currently on 2.1.7, they want to use the newest version until we go live and then want to stabilize a particular version). The module in question is supposed to display all existing orders, with an actionsColumn that contains links to cancel, edit, and open a detailed overview of the purchased items associated with that order. The order detail page contains a grid view that should display all order items associated with an order number passed in the URL.

In order to filter out Order Items that don't relate to the specific Order Number, I've extended the \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult class. This works except for one weird caveat. If, in the addFieldToFilter call, I replace $ordNum with, say, '10000', it grabs the correct data. When using $ordNum to call this dynamically, however, it returns no rows at all. This despite trying all sorts of casting and === checks to ensure that there's no difference between the hardcoded and dynamic values. Is this a Magento bug? I can't at all figure out why this would be the case.

```<code><?php

class OrderItems extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{

    protected function _initSelect()
    {
        $this->filterByOrderNum();

        parent::_initSelect();

        return $this;
    }

    private function filterByOrderNum()
    {
        $request = \Magento\Framework\App\ObjectManager::getInstance()
                       ->get('Magento\Framework\App\Request\Http');

        $ordNum = $request->getParam('order_num');

        $this->addFieldToFilter('order_num', ['eq' => $ordNum]); //if I switch this to hardcoded 10000, this works. With the variable, no dice.

        return $this;
    }
}
</code>```

答:
Try this in place of the getParam statement:

```<code>$url = parse_url($request);
$path =  explode('/',$url['path']);
$ordNum = $path[3];
</code>```

Just to make sure we are on the same page, this is the full code:

```<code><?php

class OrderItems extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{

    protected function _initSelect()
    {
        $this->filterByOrderNum();

        parent::_initSelect();

        return $this;
    }

    private function filterByOrderNum()
    {
        $request = \Magento\Framework\App\ObjectManager::getInstance()
                       ->get('Magento\Framework\App\Request\Http');

        $url = parse_url($request);
        $path =  explode('/',$url['path']);
        $ordNum = $path[3];

        $this->addFieldToFilter('order_num', $ordNum); //if I switch this to hardcoded 10000, this works. With the variable, no dice.

        return $this;
    }
}
</code>```

Body:
I'm building the admin for a Magento2 store (currently on 2.1.7, they want to use the newest version until we go live and then want to stabilize a particular version). The module in question is supposed to display all existing orders, with an actionsColumn that contains links to cancel, edit, and open a detailed overview of the purchased items associated with that order. The order detail page contains a grid view that should display all order items associated with an order number passed in the URL.

In order to filter out Order Items that don't relate to the specific Order Number, I've extended the \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult class. This works except for one weird caveat. If, in the addFieldToFilter call, I replace $ordNum with, say, '10000', it grabs the correct data. When using $ordNum to call this dynamically, however, it returns no rows at all. This despite trying all sorts of casting and === checks to ensure that there's no difference between the hardcoded and dynamic values. Is this a Magento bug? I can't at all figure out why this would be the case.

<?php

class OrderItems extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{

    protected function _initSelect()
    {
        $this->filterByOrderNum();

        parent::_initSelect();

        return $this;
    }

    private function filterByOrderNum()
    {
        $request = \Magento\Framework\App\ObjectManager::getInstance()
                       ->get('Magento\Framework\App\Request\Http');

        $ordNum = $request->getParam('order_num');

        $this->addFieldToFilter('order_num', ['eq' => $ordNum]); //if I switch this to hardcoded 10000, this works. With the variable, no dice.

        return $this;
    }
}

Body:
Try this in place of the getParam statement:

$url = parse_url($request);
$path =  explode('/',$url['path']);
$ordNum = $path[3];

Just to make sure we are on the same page, this is the full code:

<?php

class OrderItems extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{

    protected function _initSelect()
    {
        $this->filterByOrderNum();

        parent::_initSelect();

        return $this;
    }

    private function filterByOrderNum()
    {
        $request = \Magento\Framework\App\ObjectManager::getInstance()
                       ->get('Magento\Framework\App\Request\Http');

        $url = parse_url($request);
        $path =  explode('/',$url['path']);
        $ordNum = $path[3];

        $this->addFieldToFilter('order_num', $ordNum); //if I switch this to hardcoded 10000, this works. With the variable, no dice.

        return $this;
    }
}


问:
TYPO3 Extbase - The configuration file "ext_emconf.php" seems to be invalid
I try to upload my extension but I get Please check your uploaded extension "my_download_plugin". The configuration file "ext_emconf.php" seems to be invalid.
What is supposed to be wrong with this configuration file?

```<code><?php

/***************************************************************
 * Extension Manager/Repository config file for ext: "my_download_plugin"
 *
 * Auto generated by Extension Builder 2017-01-30
 *
 * Manual updates:
 * Only the data in the array - anything else is removed by next write.
 * "version" and "dependencies" must not be touched!
 ***************************************************************/

$EM_CONF[$_EXTKEY] = array(
    'title' => 'my_download_plugin',
    'description' => 'Downloadlist for my Donwloadcenter',
    'category' => 'plugin',
    'author' => 'Edward Black',
    'author_email' => 'my.name@mycompany.de',
    'state' => 'beta',
    'createDirs' => '',
    'uploadfolder' => false,
    'clearCacheOnLoad' => false,
    'version' => '2.0.0',
    'constraints' => array(
        'depends' => array(
            'typo3' => '6.2.0-6.3.0',
            'static_info_tables' => '6.3.9'
        ),
        'conflicts' => array(),
        'suggests' => array()
    )
);
</code>```

I was reading the official documentation but could not find anything wrong.

答:
Your dependency to static_info_tables seems to be wrong, since you only have given the lower version number. Please add the dependency to static_info_tables like shown below:

'static_info_tables' => '6.3.9-0.0.0'

This will require a minimum version 6.3.9 of static_info_tables extension with no maximum version requirements.

Body:
I try to upload my extension but I get Please check your uploaded extension "my_download_plugin". The configuration file "ext_emconf.php" seems to be invalid.
What is supposed to be wrong with this configuration file?

<?php

/***************************************************************
 * Extension Manager/Repository config file for ext: "my_download_plugin"
 *
 * Auto generated by Extension Builder 2017-01-30
 *
 * Manual updates:
 * Only the data in the array - anything else is removed by next write.
 * "version" and "dependencies" must not be touched!
 ***************************************************************/

$EM_CONF[$_EXTKEY] = array(
    'title' => 'my_download_plugin',
    'description' => 'Downloadlist for my Donwloadcenter',
    'category' => 'plugin',
    'author' => 'Edward Black',
    'author_email' => 'my.name@mycompany.de',
    'state' => 'beta',
    'createDirs' => '',
    'uploadfolder' => false,
    'clearCacheOnLoad' => false,
    'version' => '2.0.0',
    'constraints' => array(
        'depends' => array(
            'typo3' => '6.2.0-6.3.0',
            'static_info_tables' => '6.3.9'
        ),
        'conflicts' => array(),
        'suggests' => array()
    )
);

I was reading the official documentation but could not find anything wrong.


问:
Laravel 5.3 - changing auth routes for reset password
After moving controllers for auth to my Http/Controllers/Admin/Auth directory, as well as moving views for auth to admin/auth and setting the routes file like this:

```<code>Route::group(['middleware' => 'web', 'prefix' => 'admin', 'namespace' => 'Admin'], function() {
    Auth::routes();
});
</code>```

When clicking the link in reset password email, I get an error:

NotFoundHttpException in RouteCollection.php line 161:

I have modified showResetForm method in the controller like so:

```<code>    public function showResetForm(Request $request, $token = null)
    {
        return view('admin.auth.passwords.reset')->with(
            ['token' => $token, 'email' => $request->email]
        );
    }
</code>```

This are the routes listed on php artisan route:list:

```<code>           POST      | admin/password/email             |                   | App\Http\Controllers\Admin\Auth\ForgotPasswordController@sendResetLinkEmail  | web,web,guest |
|        | POST      | admin/password/reset             |                   | App\Http\Controllers\Admin\Auth\ResetPasswordController@reset                | web,web,guest |
|        | GET|HEAD  | admin/password/reset             |                   | App\Http\Controllers\Admin\Auth\ForgotPasswordController@showLinkRequestForm | web,web,guest |
|        | GET|HEAD  | admin/password/reset/{token}     |                   | App\Http\Controllers\Admin\Auth\ResetPasswordController@showResetForm        | web,web,guest |
|        | GET|HEAD  | admin/register                   |                   | App\Http\Controllers\Admin\Auth\RegisterController@showRegistrationForm      | web,web,guest |
|        | POST      | admin/register                   |                   | App\Http\Controllers\Admin\Auth\RegisterController@register                  | web,web,guest
</code>```

The link that a user receives in a mail for password reset is still pointing to the old route without an admin prefix, how can I change that?

答:
I ran into this issue and wanted to use my own plain text email.

Add to your User model:

```<code>public function sendPasswordResetNotification($token)
{
    Mail::send(['text' => 'emails.password'], ['token' => $token], function ($message) {
        $message->subject(config('app.name').' Password Reset Link');
        $message->to($this->email);
    });
}
</code>```

Create views/emails/password.blade.php:

```<code>You are receiving this email because we received a password reset request for your account.

Click here to reset your password: {{ url('auth/password/reset/'.$token) }}

If you did not request a password reset, no further action is required.
</code>```

This will send them a plain text password reset email and will get rid of the password.reset route not found error.

Body:
After moving controllers for auth to my Http/Controllers/Admin/Auth directory, as well as moving views for auth to admin/auth and setting the routes file like this:

Route::group(['middleware' => 'web', 'prefix' => 'admin', 'namespace' => 'Admin'], function() {
    Auth::routes();
});

When clicking the link in reset password email, I get an error:

NotFoundHttpException in RouteCollection.php line 161:

I have modified showResetForm method in the controller like so:

    public function showResetForm(Request $request, $token = null)
    {
        return view('admin.auth.passwords.reset')->with(
            ['token' => $token, 'email' => $request->email]
        );
    }

This are the routes listed on php artisan route:list:

           POST      | admin/password/email             |                   | App\Http\Controllers\Admin\Auth\ForgotPasswordController@sendResetLinkEmail  | web,web,guest |
|        | POST      | admin/password/reset             |                   | App\Http\Controllers\Admin\Auth\ResetPasswordController@reset                | web,web,guest |
|        | GET|HEAD  | admin/password/reset             |                   | App\Http\Controllers\Admin\Auth\ForgotPasswordController@showLinkRequestForm | web,web,guest |
|        | GET|HEAD  | admin/password/reset/{token}     |                   | App\Http\Controllers\Admin\Auth\ResetPasswordController@showResetForm        | web,web,guest |
|        | GET|HEAD  | admin/register                   |                   | App\Http\Controllers\Admin\Auth\RegisterController@showRegistrationForm      | web,web,guest |
|        | POST      | admin/register                   |                   | App\Http\Controllers\Admin\Auth\RegisterController@register                  | web,web,guest

The link that a user receives in a mail for password reset is still pointing to the old route without an admin prefix, how can I change that?

Body:
I ran into this issue and wanted to use my own plain text email.

Add to your User model:

public function sendPasswordResetNotification($token)
{
    Mail::send(['text' => 'emails.password'], ['token' => $token], function ($message) {
        $message->subject(config('app.name').' Password Reset Link');
        $message->to($this->email);
    });
}

Create views/emails/password.blade.php:

You are receiving this email because we received a password reset request for your account.

Click here to reset your password: {{ url('auth/password/reset/'.$token) }}

If you did not request a password reset, no further action is required.

This will send them a plain text password reset email and will get rid of the password.reset route not found error.


问:
Render formatted (unminified) HTML in React (SSR with Next.js)
How can I render formatted (unminified) HTML in React (SSR with Next.js)?

Expected output:

```<code><div>
   <div>
       <input type="text" />
   </div>
</div>
</code>```

Now receiving:

```<code><div><div><input type="text"/></div></div>
</code>```

TY!

答:
You might be looking for dangerouslysetinnerhtml. It allows you to pass in a string that you want rendered as raw HTML.</p>

```<code>function createMarkup() {
  return {__html: '<div><div><input type="text"/></div></div>'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}
</code>```

Body:
How can I render formatted (unminified) HTML in React (SSR with Next.js)?

Expected output:

       <input type="text" />

Now receiving:

<input type="text"/>

TY!

Body:
You might be looking for dangerouslysetinnerhtml. It allows you to pass in a string that you want rendered as raw HTML.

function createMarkup() {
  return {__html: '<div><div><input type="text"/></div></div>'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}


问:
Java: Print a unique character in a string
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.

Here's my code:

```<code>import java.util.Scanner;
public class Sameness{
   public static void main (String[]args){
   Scanner kb = new Scanner (System.in);
     String word = "";

     System.out.println("Enter a word: ");
     word = kb.nextLine();

     uniqueCharacters(word);
}

    public static void uniqueCharacters(String test){
      String temp = "";
         for (int i = 0; i < test.length(); i++){
            if (temp.indexOf(test.charAt(i)) == - 1){
               temp = temp + test.charAt(i);
         }
      }

    System.out.println(temp + " ");

   }
}
</code>```

And here's sample output with the above code:

```<code>Enter a word:
nreena
nrea
</code>```

The expected output would be: ra

答:
```<code>import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{

Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
 try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
    }
    }
    catch(Exception e)
    {
    System.out.println("error");
    }
}
}
</code>```

Body:
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.

Here's my code:

import java.util.Scanner;
public class Sameness{
   public static void main (String[]args){
   Scanner kb = new Scanner (System.in);
     String word = "";

     System.out.println("Enter a word: ");
     word = kb.nextLine();

     uniqueCharacters(word);
}

    public static void uniqueCharacters(String test){
      String temp = "";
         for (int i = 0; i < test.length(); i++){
            if (temp.indexOf(test.charAt(i)) == - 1){
               temp = temp + test.charAt(i);
         }
      }

    System.out.println(temp + " ");

   }
}

And here's sample output with the above code:

Enter a word:
nreena
nrea

The expected output would be: ra


问:
Tensorflow transform_graph doesn't have quantize_weights
I am building Tensorflow on Windows Server 2012 R2 from git. When I build the target tensorflow/tools/graph_transforms:transform_graph, it builds correctly but the quantize_weights transform isn't available. This is the output of running transform_graph:

```<code>$ bazel-bin/tensorflow/tools/graph_transforms/transform_graph --in_graph=/c/Users/name/git-repos/project/input/file.pb --out_graph=/c/Users/name/git-repos/project/input/file_q.pb --inputs='image_tensor' --outputs='detection_boxes,detection_scores,detection_classes' --transforms='fold_constants(ignore_error=true)
fold_batch_norms
fold_old_batch_norms
quantize_weights'
2017-07-06 13:21:10.361492: I C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:263] Applying fold_constants
2017-07-06 13:21:10.476001: W C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-06 13:21:13.241688: I C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:263] Applying fold_batch_norms
2017-07-06 13:21:16.088969: I C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:263] Applying fold_old_batch_norms
2017-07-06 13:21:16.650913: E C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:209] Transform 'quantize_weights' not recognized.
2017-07-06 13:21:16.650934: E C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:210] usage: C:\Users\name\git-repos\tensorflow\bazel-bin\tensorflow\tools\graph_transforms\transform_graph.exe
Flags:
        --in_graph=""                           string  input graph file name
        --out_graph=""                          string  output graph file name
        --inputs=""                             string  inputs
        --outputs=""                            string  outputs
        --transforms=""                         string  list of transforms
        --output_as_text=false                  bool    whether to write the graph in text protobuf format

Transforms are:
add_default_attributes
backport_concatv2
backport_tensor_array_v3
fold_batch_norms
fold_constants
fold_old_batch_norms
freeze_requantization_ranges
fuse_pad_and_conv
fuse_resize_and_conv
fuse_resize_pad_and_conv
insert_logging
obfuscate_names
remove_attribute
remove_device
remove_nodes
rename_attribute
rename_op
set_device
sort_by_execution_order
sparsify_gather
strip_unused_nodes
</code>```

Why aren't all the transforms available? I've tried rebuilding with bazel clean as well.

答: I think this is an issue with the Windows builds of TensorFlow unfortunately. There are problems compiling the https://github.com/google/gemmlowp library that the quantization parts of TF rely on, so anything that relies on them (like quantize_weights) is disabled in cmake. It would be worth filing a bug on this at https://github.com/tensorflow/tensorflow/issues</p>

Body:
I am building Tensorflow on Windows Server 2012 R2 from git. When I build the target tensorflow/tools/graph_transforms:transform_graph, it builds correctly but the quantize_weights transform isn't available. This is the output of running transform_graph:

$ bazel-bin/tensorflow/tools/graph_transforms/transform_graph --in_graph=/c/Users/name/git-repos/project/input/file.pb --out_graph=/c/Users/name/git-repos/project/input/file_q.pb --inputs='image_tensor' --outputs='detection_boxes,detection_scores,detection_classes' --transforms='fold_constants(ignore_error=true)
fold_batch_norms
fold_old_batch_norms
quantize_weights'
2017-07-06 13:21:10.361492: I C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:263] Applying fold_constants
2017-07-06 13:21:10.476001: W C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-06 13:21:13.241688: I C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:263] Applying fold_batch_norms
2017-07-06 13:21:16.088969: I C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:263] Applying fold_old_batch_norms
2017-07-06 13:21:16.650913: E C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:209] Transform 'quantize_weights' not recognized.
2017-07-06 13:21:16.650934: E C:\tools\msys64\tmp\_bazel_name\avtc4yfu\execroot\tensorflow\tensorflow\tools\graph_transforms\transform_graph.cc:210] usage: C:\Users\name\git-repos\tensorflow\bazel-bin\tensorflow\tools\graph_transforms\transform_graph.exe
Flags:
        --in_graph=""                           string  input graph file name
        --out_graph=""                          string  output graph file name
        --inputs=""                             string  inputs
        --outputs=""                            string  outputs
        --transforms=""                         string  list of transforms
        --output_as_text=false                  bool    whether to write the graph in text protobuf format

Transforms are:
add_default_attributes
backport_concatv2
backport_tensor_array_v3
fold_batch_norms
fold_constants
fold_old_batch_norms
freeze_requantization_ranges
fuse_pad_and_conv
fuse_resize_and_conv
fuse_resize_pad_and_conv
insert_logging
obfuscate_names
remove_attribute
remove_device
remove_nodes
rename_attribute
rename_op
set_device
sort_by_execution_order
sparsify_gather
strip_unused_nodes

Why aren't all the transforms available? I've tried rebuilding with bazel clean as well.


问:
iPod Touch 4G thinks it's an iPad
I have a universal app built that runs and works perfectly on an iPad, iPhone 4G, 3GS & 3G, but when run on an iPod Touch 4G it won't run properly.

I don't have a iPod Touch to test, but I have been told by a beta tester that it installs on the device fine, but when run it shows the Default.png from the iPad version of the app squashed into the screen when launched, then just goes black from there.  When the app is force quit (using the app switcher) and re-launched it does the same thing again.

I have double checked that the Targeted Device Family is iPhone/iPad and done a clean build etc. but still no dice.

答:
So after some trial and error I worked out what the problem was (actually two separate but related problems):

In my info.plist I was using two keys to assign the different MainWindow files:

Main nib file base name (iPad)

and

Main nib file base name (iPhone)

I mistakenly thought the second key would apply to the iPod Touch also as there is no Main nib file base name (iPodTouch) key.  Turns out this is wrong and the iPod Touch actually looks for the Main nib file base name key.  So now I have it setup like this:

..and it's working fine in 3.1.3 & 4.2.  (Note that application:didFinishLaunchingWithOptions is not called if the device can't find a MainWindow to use, that's how I worked out the problem).

I suspect the same will apply to the Launch image (iPad), Launch image (iPhone) and Launch image keys, which would explain why the iPod Touch is using the iPad launch image but haven't been able to try it yet.

Title: iPod Touch 4G thinks it's an iPad