问:
SQL alternative to double subquery
I have a table MyTable with values that look like this:

```<code>|   id    |   name    |    type    |  category    |
---------------------------------------------------
|   1     |   Rob     |   Red      |     Rock     |
|   2     |   Rob     |   Blue     |     Rap      |
|   2     |   Rob     |   Blue     |     Rock     |
|   3     |  Jane     |   Green    |     Country  |
|   3     |  Jane     |   Green    |     Rap      |
|   4     |   Meg     |   Yellow   |     Rock     |
|   5     |  Jane     |   Blue     |     Rap      |
|   5     |  Jane     |   Blue     |     Rock     |
|   6     |  Jane     |   Red      |     Country  |
|   6     |  Jane     |   Red      |     Rock     |
|   7     |  Rob      |   Red      |     Rap      |
|   7     |  Rob      |   Red      |     Country  |
|   8     |  Meg      |   Green    |     Country  |
|   9     |  Meg      |   Blue     |     Rap      |
</code>```

Now, my issue resides in the fact that (as the data is given to me), there are duplicate ids. Each id stands for a report, so id of 1 is for report 1. In this report, there is a name, type, and category. The report can only have one type, but as many categories as it likes. Hence, the duplicate ids come from there being different categories, each constituting a new row. The end result i wish to achieve it to list the names in one row, along with all the types + count (where count is the count of the distinct types, as in one type per report) in the next row. It would look like such:

```<code>|   Rob    |  Red(2), Blue(1)             |
|   Jane   |  Green(1), Blue(1), Red(1)   |
|   Meg    |  Yellow(1), Green(1), Blue(1)|
</code>```

Now, I've developed a query that actually uses two subqueries and successfully achieves this result. It goes

```<code>   select name as firstCol, group_concat(type_counts order by countName desc           separator ', ') as secondCol from
   (select name, concat(type,' (',count(name),')') as  type_counts, count(name) as countName from
   (select name, type from
   some join stuff
   where (date_reported between '2014-11-01' and '2014-11-31')
   group by id order by type, name) a
   group by name, type order by name, count(name) desc) a
   group by name;
</code>```

This query essentially groups by id first, to remove the duplicate ids and disregard the split due to differing categories. The query wrapping it then groups by name and traffic type, concatenating the traffic type and the count of names together as "type (count)". The third groups solely by name and group concats all of the types to have a column for the name, and then a second column with all of the type+counts listed and separated by commas. I was just wondering...is there a query that could make it faster, by not having to use so many subqueries and such? Thanks.

答:
The end result i wish to achieve it to list the names in one row, along with all the types + count (where count is the count of the distinct types, as in one type per report) in the next row.

Use a subquery as an expression in the SELECT clause and another in the WHERE clause. For example:

```<code>SELECT B.Name, B.UserId AS [User Link], (SELECT Count(B2.Name) FROM Badges B2 WHERE B2.Name = B.Name) as [Total Gold, Silver, and Bronze Badges Awarded for this Tag]
FROM Badges B
WHERE Class = 2
AND TagBased = 1
AND (SELECT Count(B2.Name)
     FROM Badges B2
     WHERE B2.Name = B.Name
     AND B2.Class = 2
     AND B2.TagBased = 1) = 1
GROUP BY B.Name, B.UserId
ORDER BY B.Name
</code>```

References

Users with their own Silver Tag Badges - Stack Exchange Data Explorer

Relational Algebra and SQL (pdf)

A Gentle Introduction to SQL

Title: SQL alternative to double subquery

Body:
I have a table MyTable with values that look like this:

|   id    |   name    |    type    |  category    |
---------------------------------------------------
|   1     |   Rob     |   Red      |     Rock     |
|   2     |   Rob     |   Blue     |     Rap      |
|   2     |   Rob     |   Blue     |     Rock     |
|   3     |  Jane     |   Green    |     Country  |
|   3     |  Jane     |   Green    |     Rap      |
|   4     |   Meg     |   Yellow   |     Rock     |
|   5     |  Jane     |   Blue     |     Rap      |
|   5     |  Jane     |   Blue     |     Rock     |
|   6     |  Jane     |   Red      |     Country  |
|   6     |  Jane     |   Red      |     Rock     |
|   7     |  Rob      |   Red      |     Rap      |
|   7     |  Rob      |   Red      |     Country  |
|   8     |  Meg      |   Green    |     Country  |
|   9     |  Meg      |   Blue     |     Rap      |

Now, my issue resides in the fact that (as the data is given to me), there are duplicate ids. Each id stands for a report, so id of 1 is for report 1. In this report, there is a name, type, and category. The report can only have one type, but as many categories as it likes. Hence, the duplicate ids come from there being different categories, each constituting a new row. The end result i wish to achieve it to list the names in one row, along with all the types + count (where count is the count of the distinct types, as in one type per report) in the next row. It would look like such:

|   Rob    |  Red(2), Blue(1)             |
|   Jane   |  Green(1), Blue(1), Red(1)   |
|   Meg    |  Yellow(1), Green(1), Blue(1)|

Now, I've developed a query that actually uses two subqueries and successfully achieves this result. It goes

   select name as firstCol, group_concat(type_counts order by countName desc           separator ', ') as secondCol from
   (select name, concat(type,' (',count(name),')') as  type_counts, count(name) as countName from
   (select name, type from
   some join stuff
   where (date_reported between '2014-11-01' and '2014-11-31')
   group by id order by type, name) a
   group by name, type order by name, count(name) desc) a
   group by name;

This query essentially groups by id first, to remove the duplicate ids and disregard the split due to differing categories. The query wrapping it then groups by name and traffic type, concatenating the traffic type and the count of names together as "type (count)". The third groups solely by name and group concats all of the types to have a column for the name, and then a second column with all of the type+counts listed and separated by commas. I was just wondering...is there a query that could make it faster, by not having to use so many subqueries and such? Thanks.

Body:
The end result i wish to achieve it to list the names in one row, along with all the types + count (where count is the count of the distinct types, as in one type per report) in the next row.

Use a subquery as an expression in the SELECT clause and another in the WHERE clause. For example:

SELECT B.Name, B.UserId AS [User Link], (SELECT Count(B2.Name) FROM Badges B2 WHERE B2.Name = B.Name) as [Total Gold, Silver, and Bronze Badges Awarded for this Tag]
FROM Badges B
WHERE Class = 2
AND TagBased = 1
AND (SELECT Count(B2.Name)
     FROM Badges B2
     WHERE B2.Name = B.Name
     AND B2.Class = 2
     AND B2.TagBased = 1) = 1
GROUP BY B.Name, B.UserId
ORDER BY B.Name

References

Users with their own Silver Tag Badges - Stack Exchange Data Explorer

Relational Algebra and SQL (pdf)

A Gentle Introduction to SQL


来源: stackexchange

问:
Laravel says "Route not defined"
In my routes.php I have:

Route::patch('/preferences/{id}', 'UserController@update');
```
<p>And in the view file (account/preferences.blade.php) I have:</p>
<pre class="lang-none prettyprint-override"><code>{!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => '/preferences/' . Auth::user()->id]) !!}
</code>```

But I'm getting this error:

Route [/preferences/1] not defined

A similar error occurs when calling the route() helper directly:

route('/preferences/' . Auth::user()->id');
```

I think I'm misunderstanding the docs on this topic but I've defined a route for PATCH requests with a given parameter, and set this in the view correctly. What am I overlooking here?

答:
i had the same issue and find the solution lately.

you should check if your route is rather inside a route::group

like here:

```<code>Route::group(['prefix' => 'Auth', 'as' => 'Auth.', 'namespace' => 'Auth', 'middleware' => 'Auth']
</code>```

if so you should use it in the view file. like here:

```<code>!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => 'Auth.preferences/' . Auth::user()->id]) !!}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Laravel says "Route not defined"

Body:
In my routes.php I have:

Route::patch('/preferences/{id}', 'UserController@update');

And in the view file (account/preferences.blade.php) I have:

{!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => '/preferences/' . Auth::user()->id]) !!}

But I'm getting this error:

Route [/preferences/1] not defined

A similar error occurs when calling the route() helper directly:

route('/preferences/' . Auth::user()->id');

I think I'm misunderstanding the docs on this topic but I've defined a route for PATCH requests with a given parameter, and set this in the view correctly. What am I overlooking here?

Body:
i had the same issue and find the solution lately.

you should check if your route is rather inside a route::group

like here:

Route::group(['prefix' => 'Auth', 'as' => 'Auth.', 'namespace' => 'Auth', 'middleware' => 'Auth']

if so you should use it in the view file. like here:

!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => 'Auth.preferences/' . Auth::user()->id]) !!}

ContentLicense: CC BY-SA 3.0


问:
Bash Scripting IF Conditions
I need to check if the picture has a resolution of 900x900 pixels and the filename is not allowed to contain _thumb or _v

What I am trying to do with this line:

If the picture ist 900x900 pixels and does not contain _v or _thumb => add the word _thumb to the end of the filename before the file extension.

The Line it's all about:

```<code>if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v;
</code>```

Script:

```<code>#Change to current .sh directory
cd -P -- "$(dirname -- "$0")"
for picture in */*/Templates/*.jpg
do
    filename=${picture##*/}
    filename1=$(echo "$filename" |sed 's/.\{4\}$//')
    parent_dir="$(dirname -- "$(/usr/local/bin/realpath "$picture")")"

    #Colors
    red=`tput setaf 1`
    green=`tput setaf 2`
    magenta=`tput setaf 5`
    reset=`tput sgr0`

    if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v;
        then
            mv -v "$picture" "$parent_dir/"$filename1"_thumb.jpg"
            echo "${green} [PASS] $filename1 Thumbnail 900x900 found and renamed ${reset}"
        else
            echo "${magenta} [WARNUNG] $filename1 contains _thumb already or is a _v picture or isn't 900x900 pixels ${reset}"
        fi
</code>```

答:
do not use "file $picture | grep 900x900" because you do not know if the filename contains 900x900. I advise the use of command identify that is present in ImageMagick package like in:

```<code>if [[ "900 900" == $(identify -format '%w %h' "$picture") ]] ; then
  if [[ $picture != *_v.jpg && $picture != _thumb.jpg ]] ; then
    mv "$picture" "${picture%.jpg}_thumb.jpg"
  fi
fi
</code>```

I have slightly deviate from your spec by assuming that _v and _thumb appears just before extension. I think it is more prudent to avoid unexpected matches like best_view.jpg.

PS: always check that you scripts work when there are spaces in filenames or dirnames.

Title: Bash Scripting IF Conditions

Body:
I need to check if the picture has a resolution of 900x900 pixels and the filename is not allowed to contain _thumb or _v

What I am trying to do with this line:

If the picture ist 900x900 pixels and does not contain _v or _thumb => add the word _thumb to the end of the filename before the file extension.

The Line it's all about:

if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v;

Script:

#Change to current .sh directory
cd -P -- "$(dirname -- "$0")"
for picture in */*/Templates/*.jpg
do
    filename=${picture##*/}
    filename1=$(echo "$filename" |sed 's/.\{4\}$//')
    parent_dir="$(dirname -- "$(/usr/local/bin/realpath "$picture")")"

    #Colors
    red=`tput setaf 1`
    green=`tput setaf 2`
    magenta=`tput setaf 5`
    reset=`tput sgr0`

    if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v;
        then
            mv -v "$picture" "$parent_dir/"$filename1"_thumb.jpg"
            echo "${green} [PASS] $filename1 Thumbnail 900x900 found and renamed ${reset}"
        else
            echo "${magenta} [WARNUNG] $filename1 contains _thumb already or is a _v picture or isn't 900x900 pixels ${reset}"
        fi

Body:
do not use "file $picture | grep 900x900" because you do not know if the filename contains 900x900. I advise the use of command identify that is present in ImageMagick package like in:

if [[ "900 900" == $(identify -format '%w %h' "$picture") ]] ; then
  if [[ $picture != *_v.jpg && $picture != _thumb.jpg ]] ; then
    mv "$picture" "${picture%.jpg}_thumb.jpg"
  fi
fi

I have slightly deviate from your spec by assuming that _v and _thumb appears just before extension. I think it is more prudent to avoid unexpected matches like best_view.jpg.

PS: always check that you scripts work when there are spaces in filenames or dirnames.


问:
How to increase width of box according to page load
I am having hard time creating a progress bar which should increase its width as per the load of page.

jQuery

```<code>$(document).ready(function(){

  var startTime = window.performance.timing.domContentLoadedEventEnd;
  var endTime = window.performance.timing.navigationStart;
  var loadTime = startTime - endTime;

})
</code>```

HTML

```<code><div class="outerWidth">
    <div class="innerWidth">
    </div>
</div>
</code>```

CSS

```<code>.outerWidth {
  display: block;
  border: 1px solid #999;
  height: 10px;
  margin-top: 20px;
}

.innerWidth {
  background-color: #f00;
  display: block;
  height: 10px;
  width: 0;
}
</code>```

As per the code the width of innerWidth class is 0

Now two things I want to do.

Since I have a load time of page so how can I increase the innerWidth class width to 100% when page loads.

How can I display that time in percentage so that it should display 100% at the end of page loading is finished.

Again its a progress bar kind of program i'm looking for. which shows percentage also. But for any page load by calculating the page size or page load time. I don't know what way is correct.

Help Needed!

答:
You cannot know how much time the page will take to load. Because of that, you cannot show a percentage.

Some ideas:

Load a small, lightweight and incomplete version of your page. Use AJAX to load the full version and show a loading gif in the meantime.

Show the loading gif only and load the complete page via AJAX.

If you are worried about the time that uses a given script (client side), show a loading gif for the duration. And don't worry about the initial loading time.

Concerning a part of question, you can easily manage a progress bar with bootstrap or create one yourself. Here's an example.

```<code>function startProgress() {
    var curProg = 0;
    var interval = setInterval(function() {
        curProg = curProg + 5;
        $('#progBar').css('width', curProg + '%');
        if (curProg > 100) clearInterval(interval);
    }, 50)
}
</code>```

Body:
I am having hard time creating a progress bar which should increase its width as per the load of page.

jQuery

$(document).ready(function(){

  var startTime = window.performance.timing.domContentLoadedEventEnd;
  var endTime = window.performance.timing.navigationStart;
  var loadTime = startTime - endTime;

})

HTML

CSS

.outerWidth {
  display: block;
  border: 1px solid #999;
  height: 10px;
  margin-top: 20px;
}

.innerWidth {
  background-color: #f00;
  display: block;
  height: 10px;
  width: 0;
}

As per the code the width of innerWidth class is 0

Now two things I want to do.

Since I have a load time of page so how can I increase the innerWidth class width to 100% when page loads.

How can I display that time in percentage so that it should display 100% at the end of page loading is finished.

Again its a progress bar kind of program i'm looking for. which shows percentage also. But for any page load by calculating the page size or page load time. I don't know what way is correct.

Help Needed!

Body:
You cannot know how much time the page will take to load. Because of that, you cannot show a percentage.

Some ideas:

Load a small, lightweight and incomplete version of your page. Use AJAX to load the full version and show a loading gif in the meantime.

Show the loading gif only and load the complete page via AJAX.

If you are worried about the time that uses a given script (client side), show a loading gif for the duration. And don't worry about the initial loading time.

Concerning a part of question, you can easily manage a progress bar with bootstrap or create one yourself. Here's an example.

function startProgress() {
    var curProg = 0;
    var interval = setInterval(function() {
        curProg = curProg + 5;
        $('#progBar').css('width', curProg + '%');
        if (curProg > 100) clearInterval(interval);
    }, 50)
}


问:
When do you embed mutex in struct in Go?
NOTE: I found the word 'embed' in the title was bad choice, but I will keep it.

I see a lot of code does like this:

```<code>type A struct {
    mu sync.Mutex
    ...
}
</code>```

And use it like this:

```<code>a := &A{}

a.mu.Lock()
defer a.mu.Unlock()

a.Something()
</code>```

Is it better than local mutex or global mutex?

```<code>a := &A{}

var mu sync.Mutex
mu.Lock()
defer mu.Unlock()

a.Something()
</code>```

When should I use former, or later?

答:
It's good practice to keep the mutex close to the data it is destined to protect. If a mutex ought to protect concurrent access to fields of a struct value, it's very convenient to add the mutex as a field of that struct, so its purpose is obvious.

If in your app there is only a single "instance" of A, it's fine to make the mutex a global variable too.

If your app is to create multiple values of A, all of which needs to be protected from concurrent access (but only individually, multiple values may be accessed concurrently), then obviously a global mutex is a bad choice, it would limit the concurrent access to a single value of A in any point in time.

Adding the mutex to the struct as a field, you will naturally have a separate mutex for each distinct struct values, responsible to guard that single, wrapper struct value (or its fields).

Although adding a mutex as in your example is not embedding, it's a regular, named field. An embedded field declaration omits the field name.

It's known and used to a lesser extent, but it's also handy that you can "truly" embed a mutex in a struct, and you can call Lock() and Unlock() as if they would be part of the struct itself. It looks like this:

```<code>var hits struct {
    sync.Mutex
    n int
}

hits.Lock()
hits.n++
hits.Unlock()
</code>```

(This example is taken from 10 things you (probably) don't know about Go, slide #3.)

Body:
NOTE: I found the word 'embed' in the title was bad choice, but I will keep it.

I see a lot of code does like this:

type A struct {
    mu sync.Mutex
    ...
}

And use it like this:

a := &A{}

a.mu.Lock()
defer a.mu.Unlock()

a.Something()

Is it better than local mutex or global mutex?

a := &A{}

var mu sync.Mutex
mu.Lock()
defer mu.Unlock()

a.Something()

When should I use former, or later?

Body:
It's good practice to keep the mutex close to the data it is destined to protect. If a mutex ought to protect concurrent access to fields of a struct value, it's very convenient to add the mutex as a field of that struct, so its purpose is obvious.

If in your app there is only a single "instance" of A, it's fine to make the mutex a global variable too.

If your app is to create multiple values of A, all of which needs to be protected from concurrent access (but only individually, multiple values may be accessed concurrently), then obviously a global mutex is a bad choice, it would limit the concurrent access to a single value of A in any point in time.

Adding the mutex to the struct as a field, you will naturally have a separate mutex for each distinct struct values, responsible to guard that single, wrapper struct value (or its fields).

Although adding a mutex as in your example is not embedding, it's a regular, named field. An embedded field declaration omits the field name.

It's known and used to a lesser extent, but it's also handy that you can "truly" embed a mutex in a struct, and you can call Lock() and Unlock() as if they would be part of the struct itself. It looks like this:

var hits struct {
    sync.Mutex
    n int
}

hits.Lock()
hits.n++
hits.Unlock()

(This example is taken from 10 things you (probably) don't know about Go, slide #3.)


Title: Pair IP addresses in a list pulled from xlrd

Body:
I have used xlrd to pull data from a column (Data Below). I need to group together the ip addressess. So ip address that appear next together in the output belong to the same pool and single ones are in a pool of their own. For example (10.100.33.183,10.100.33.184) belong to (pool1). (Pool6 =10.100.33.89)

How do I go about achieving this all help welcome.

['', '', '', '', '', '', '', 'Pool Member IP', '', '10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)', '', '', '', '', '', '', '', '10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)', '', '', '', '', '', '', '', '10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)', '', '', '', '', '', '', '', '10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)', '', '', '', '', '', '', '', '10.100.33.90 (S56723FR6VL09)', '', '', '', '', '', '', '', '', '10.100.33.89 (S56723FR6VL0A)', '', '', '', '', '', '', '', '', '10.100.33.91 (S56723FR6VW01)', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

Body:
ip_data = ['', '', '', '', '', '', '', 'Pool Member IP', '', '10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)', '', '', '', '', '', '', '', '10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)', '', '', '', '', '', '', '', '10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)', '', '', '', '', '', '', '', '10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)', '', '', '', '', '', '', '', '10.100.33.90 (S56723FR6VL09)', '', '', '', '', '', '', '', '', '10.100.33.89 (S56723FR6VL0A)', '', '', '', '', '', '', '', '', '10.100.33.91 (S56723FR6VW01)', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
ip_pools = [[]]  # it starts as a list with an empty list at its last (and only) index
for ip_address in ip_data[ip_data.index('Pool Member IP')+1:]:
    if not ip_address:  # ip_address is ''
        if ip_pools[-1]:  # the last element of ip_pools is NOT an empty list: []
            ip_pools.append([])  # for the next ip pool
    else:  # ip_address is not empty
        # ip_pools[-1].append(ip_address)  # if you need the whole text
        ip_pools[-1].append(ip_address.partition(' ')[0])  # if you just want the number
if [] in ip_pools:
    ip_pools.remove([])  # to remove last empty list (if exists)

EDIT: Corrected the for sentence


问:
How to get slices of different dimensions from tensorflow tensor.
I have a 3D tensor x that is of type float, and a 1D tensor y that is of type int. I want to get the average of each slice of the second axis of x from 0 to the index corresponding to each element of y. In other words, if x and y were numpy arrays, I would want

```<code>In [1]: y = [1, 2, 1, 1]

In [2]: x = np.array([[[1,2],[3,4],[5,6]], [[1,2],[3,4],[5,6]], [[1,2],[3,4],[5,6]], [[1,2],[3,4],[5,6]]])

In [3]: np.array([np.mean(x[index, :item], axis=0) for index, item in enumerate(y)])
Out[22]:
array([[ 1.,  2.],
       [ 2.,  3.],
       [ 1.,  2.],
       [ 1.,  2.]])
</code>```

What is the easiest way to do this?

答:
In the general case, you could use a tf.while_loop:

```<code>import numpy as np
import tensorflow as tf

y = tf.constant([1, 2, 1, 1])
x = tf.constant([[[1,2],[3,4],[5,6]],
                 [[1,2],[3,4],[5,6]],
                 [[1,2],[3,4],[5,6]],
                 [[1,2],[3,4],[5,6]]], dtype=np.float32)

y_len = tf.shape(y)[0]
idx = tf.zeros((), dtype=tf.int32)
res = tf.zeros((0,2))
_, res = tf.while_loop(
    lambda idx, res: idx < y_len,
    lambda idx, res: (idx + 1, tf.concat([res, tf.reduce_mean(x[idx, :y[idx]], axis=0)[tf.newaxis]], axis=0)),
    [idx, res],
    shape_invariants=[idx.get_shape(), tf.TensorShape([None, 2])])

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
res.eval()

# returns
# array([[ 1.,  2.],
#        [ 2.,  3.],
#        [ 1.,  2.],
#        [ 1.,  2.]], dtype=float32)
</code>```

In the less general case where the length of y is known at graph construction time, you could spare yourself the use of a tf.while_loop and loop in python (could result in a large graph if y has many elements).

```<code>y_len = y.shape.num_elements()
res = tf.Variable(np.zeros((y_len, 2), dtype=np.float32))
res = tf.tuple([res] + [res[idx].assign(tf.reduce_mean(x[idx, :y[idx]], axis=0))
   for idx in range(y_len)])[0]
</code>```

Note that you could also simply cascade the updates, not unlike the general case with tf.while_loop:

```<code>y_len = y.shape.num_elements()
res = tf.zeros((0,2))
for idx in range(y_len):
  res = tf.concat([res, tf.reduce_mean(x[idx, :y[idx]], axis=0)[tf.newaxis]], axis=0)
</code>```

but now the updates need to happen sequentially. In the former solution, updates for each row happen are independent and can run in parallel, which I think is better.

Body:
I have a 3D tensor x that is of type float, and a 1D tensor y that is of type int. I want to get the average of each slice of the second axis of x from 0 to the index corresponding to each element of y. In other words, if x and y were numpy arrays, I would want

In [1]: y = [1, 2, 1, 1]

In [2]: x = np.array([[[1,2],[3,4],[5,6]], [[1,2],[3,4],[5,6]], [[1,2],[3,4],[5,6]], [[1,2],[3,4],[5,6]]])

In [3]: np.array([np.mean(x[index, :item], axis=0) for index, item in enumerate(y)])
Out[22]:
array([[ 1.,  2.],
       [ 2.,  3.],
       [ 1.,  2.],
       [ 1.,  2.]])

What is the easiest way to do this?

Body:
In the general case, you could use a tf.while_loop:

import numpy as np
import tensorflow as tf

y = tf.constant([1, 2, 1, 1])
x = tf.constant([[[1,2],[3,4],[5,6]],
                 [[1,2],[3,4],[5,6]],
                 [[1,2],[3,4],[5,6]],
                 [[1,2],[3,4],[5,6]]], dtype=np.float32)

y_len = tf.shape(y)[0]
idx = tf.zeros((), dtype=tf.int32)
res = tf.zeros((0,2))
_, res = tf.while_loop(
    lambda idx, res: idx < y_len,
    lambda idx, res: (idx + 1, tf.concat([res, tf.reduce_mean(x[idx, :y[idx]], axis=0)[tf.newaxis]], axis=0)),
    [idx, res],
    shape_invariants=[idx.get_shape(), tf.TensorShape([None, 2])])

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
res.eval()

# returns
# array([[ 1.,  2.],
#        [ 2.,  3.],
#        [ 1.,  2.],
#        [ 1.,  2.]], dtype=float32)

In the less general case where the length of y is known at graph construction time, you could spare yourself the use of a tf.while_loop and loop in python (could result in a large graph if y has many elements).

y_len = y.shape.num_elements()
res = tf.Variable(np.zeros((y_len, 2), dtype=np.float32))
res = tf.tuple([res] + [res[idx].assign(tf.reduce_mean(x[idx, :y[idx]], axis=0))
   for idx in range(y_len)])[0]

Note that you could also simply cascade the updates, not unlike the general case with tf.while_loop:

y_len = y.shape.num_elements()
res = tf.zeros((0,2))
for idx in range(y_len):
  res = tf.concat([res, tf.reduce_mean(x[idx, :y[idx]], axis=0)[tf.newaxis]], axis=0)

but now the updates need to happen sequentially. In the former solution, updates for each row happen are independent and can run in parallel, which I think is better.


问:
C++ SQL Sanitization Libraries or Query Builders Offering Sanitization
In a project I am working on, I need to insert data into a SQLite3 database via C++. In order to avoid a "little Bobby Tables" incident, I need to sanitize my database inputs. I would like to find a library that does this in C++ rather than rolling my own since that usually leads to issues. Since the application will be inserting ID3 data from MP3's into the database, the need for this is paramount since many artist, album, and song titles include invalid characters.

I found a SO post earlier (can't seem to find it now...) that detailed different query builder libraries for C++, but none of those libraries come straight out and say that they offer sanitization functionality. I'd hate to start implementing one to find out it doesn't have this functionality. There has to be a library out there that does this, but my searches have failed me.

My question is, what libraries are available that will sanitize database input in C++? I don't mind rolling my own, but I'd like to avoid it at all costs. Thanks everyone!

答: Short answer: do not sanitise your input. Use parameterised queries instead. They are safer and faster.</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Noah

OwnerDisplayName: 1800 INFORMATION


问:
Is there a Web Server plugin for Eclipse?
Just like the title says, are there any plugins that integrate a web server with Eclipse for quicker/easier web development?

I'm mainly looking for PHP development that can be done WITHOUT installing XAMPP or any other server software separately. Ideally, it'd work like Visual Studio - hit "Run", a Web server instance is started up and your script(s) are run, that allow you to step through code without going to the North Pole first (ok, one trip to the North Pole to set everything up is acceptable).

Am I dreaming or have I just been looking in the wrong places?

答: Yes, it absolutely exists! It's called the Eclipse Web Tools Platform (WTP for short), and it's very powerful. Furthermore, it is bundled inside the Eclipse PHP Developer Tools (PDT) distribution, which is probably what you want to be using.</p>


问:
nginx duplicate default server error
I get the following error in nginx

```<code>: a duplicate default server for 0.0.0.0:80 in /etc/nginx/sites-enabled/default:2
</code>```

My file in /etc/nginx/sites-enabled/default is:

```<code>server {
    listen 80 default_server;

    root /var/www/html;
    index index.php index.html index.htm;

    location / {
         try_files $uri $uri/ /index.php$is_args$args;
    }

    # pass the PHP scripts to FastCGI server listening on /var/run/php5-fpm.sock
    location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
</code>```

答:
you got this error because of inside sites-enabled directory multiple files  remove the by

get the directory by cd /etc/nginx/sites-enabled/ show the list of items in the directory by ls

rm ******* use this command remove multiple files.

and run this code for checking the nginx working or notsudo nginx -t

Title: nginx duplicate default server error

Body:
I get the following error in nginx

: a duplicate default server for 0.0.0.0:80 in /etc/nginx/sites-enabled/default:2

My file in /etc/nginx/sites-enabled/default is:

server {
    listen 80 default_server;

    root /var/www/html;
    index index.php index.html index.htm;

    location / {
         try_files $uri $uri/ /index.php$is_args$args;
    }

    # pass the PHP scripts to FastCGI server listening on /var/run/php5-fpm.sock
    location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }


问:
Upload file to Google Drive
I need to upload files on my google drive (pdf, word, excel), how can I do it in ASP.NET using C#? Could you explain me step by step all the passages? If it can be useful I put my last test code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPSnippets.GoogleAPI;
using System.Runtime.Serialization;
using System.IO;
using System.Web.Script.Serialization;

...

    protected void Page_Load(object sender, EventArgs e)
    {
        GoogleConnect.ClientId = "my_client_id";
        GoogleConnect.ClientSecret = "my_client_secret";
        GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
        GoogleConnect.API = EnumAPI.Drive;
        if (!string.IsNullOrEmpty(Request.QueryString["code"]))
        {
            string code = Request.QueryString["code"];
            string json = GoogleConnect.PostFile(code, (HttpPostedFile)Session["File"], Session["Description"].ToString());
            GoogleDriveFile file = (new JavaScriptSerializer()).Deserialize<GoogleDriveFile>(json);
            tblFileDetails.Visible = true;
            lblTitle.Text = file.Title;
            lblId.Text = file.Id;
            imgIcon.ImageUrl = file.IconLink;
            lblCreatedDate.Text = file.CreatedDate.ToString();
            lnkDownload.NavigateUrl = file.WebContentLink;
            if (!string.IsNullOrEmpty(file.ThumbnailLink))
            {
                rowThumbnail.Visible = true;
                imgThumbnail.ImageUrl = file.ThumbnailLink;
            }
        }
        if (Request.QueryString["error"] == "access_denied")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
        }
    }

    protected void UploadFile(object sender, EventArgs e)
    {
        Session["File"] = FileUpload1.PostedFile;
        Session["Description"] = txtDescription.Text;
        GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.file");
    }
}

public class GoogleDriveFile
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string OriginalFilename { get; set; }
    public string ThumbnailLink { get; set; }
    public string IconLink { get; set; }
    public string WebContentLink { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime ModifiedDate { get; set; }
}
</code>```

But I have this error:

That’s an error.

Error: redirect_uri_mismatch

The redirect URI in the request, http://localhost:61360/Prova.aspx,
  does not match the ones authorized for the OAuth client. Visit
  https://console.developers.google.com/apis/credentials/oauthclient/831126948299-2bopcsp3aee3harncqp5dpkq77sii3he.apps.googleusercontent.com?project=831126948299
  to update the authorized redirect URIs.

Request Details:

```<code>scope=https://www.googleapis.com/auth/drive.file
redirect_uri=http://localhost:61360/Prova.aspx
response_type=code
client_id=831126948299-2bopcsp3aee3harncqp5dpkq77sii3he.apps.googleusercontent.com
approval_prompt=auto
access_type=offline
</code>```

I've insert the redirect page but it gave me the same error.

答:
The redirect uri you add in Google developer console must exactly match what you are sending from  in your case you are sending http://localhost:61360 so should add http://localhost:61360 in your redirect URI.   Or possibly http://localhost:61360/AuthCallback

Tip: Make sure you have visual studio set to not add random port numbers.

Title: Upload file to Google Drive

Body:
I need to upload files on my google drive (pdf, word, excel), how can I do it in ASP.NET using C#? Could you explain me step by step all the passages? If it can be useful I put my last test code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPSnippets.GoogleAPI;
using System.Runtime.Serialization;
using System.IO;
using System.Web.Script.Serialization;

...

    protected void Page_Load(object sender, EventArgs e)
    {
        GoogleConnect.ClientId = "my_client_id";
        GoogleConnect.ClientSecret = "my_client_secret";
        GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
        GoogleConnect.API = EnumAPI.Drive;
        if (!string.IsNullOrEmpty(Request.QueryString["code"]))
        {
            string code = Request.QueryString["code"];
            string json = GoogleConnect.PostFile(code, (HttpPostedFile)Session["File"], Session["Description"].ToString());
            GoogleDriveFile file = (new JavaScriptSerializer()).Deserialize<GoogleDriveFile>(json);
            tblFileDetails.Visible = true;
            lblTitle.Text = file.Title;
            lblId.Text = file.Id;
            imgIcon.ImageUrl = file.IconLink;
            lblCreatedDate.Text = file.CreatedDate.ToString();
            lnkDownload.NavigateUrl = file.WebContentLink;
            if (!string.IsNullOrEmpty(file.ThumbnailLink))
            {
                rowThumbnail.Visible = true;
                imgThumbnail.ImageUrl = file.ThumbnailLink;
            }
        }
        if (Request.QueryString["error"] == "access_denied")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
        }
    }

    protected void UploadFile(object sender, EventArgs e)
    {
        Session["File"] = FileUpload1.PostedFile;
        Session["Description"] = txtDescription.Text;
        GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.file");
    }
}

public class GoogleDriveFile
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string OriginalFilename { get; set; }
    public string ThumbnailLink { get; set; }
    public string IconLink { get; set; }
    public string WebContentLink { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime ModifiedDate { get; set; }
}

But I have this error:

That’s an error.

Error: redirect_uri_mismatch

The redirect URI in the request, http://localhost:61360/Prova.aspx,
  does not match the ones authorized for the OAuth client. Visit
  https://console.developers.google.com/apis/credentials/oauthclient/831126948299-2bopcsp3aee3harncqp5dpkq77sii3he.apps.googleusercontent.com?project=831126948299
  to update the authorized redirect URIs.

Request Details:

scope=https://www.googleapis.com/auth/drive.file
redirect_uri=http://localhost:61360/Prova.aspx
response_type=code
client_id=831126948299-2bopcsp3aee3harncqp5dpkq77sii3he.apps.googleusercontent.com
approval_prompt=auto
access_type=offline

I've insert the redirect page but it gave me the same error.


问:
Android Java specific music folder
Found a tutorial to follow which displays music on my phone. Is it possible for me to look at just one folder instead of all the folders that contain music on my external?</p>

```<code>    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
    String[] proj = { MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.DISPLAY_NAME};

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    musiccursor = getContentResolver().query(uri, proj, selection, null);
</code>```

答:
selection =

```<code>Mediastore.Audio.Media.Data + " like ? ";
</code>```

Selection args =

```<code>new String[]{"%" + folder path + "%"}
</code>```

Title: Android Java specific music folder

Body:
Found a tutorial to follow which displays music on my phone. Is it possible for me to look at just one folder instead of all the folders that contain music on my external?

    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
    String[] proj = { MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.DISPLAY_NAME};

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    musiccursor = getContentResolver().query(uri, proj, selection, null);

Body:
selection =

Mediastore.Audio.Media.Data + " like ? ";

Selection args =

new String[]{"%" + folder path + "%"}


问:
Save current time as a cookie in Javascript
I am trying to get the time a user goes on a page and save it as a cookie (in JavaScript) I'm able to get the current time but I can't seem to be able to save it as a cookie.

The reason why I'm doing this is because I'd like to know how long it took my class to go from the first page to the last page of my training site. I collect the first time stamp when they load the first page, and I collect the second time stamp when they load the finale page (their are 5 pages).
I'm not sure if there is a better way of doing this with Javascript?

Here is my code: (thanks in advance)

var d = new Date();
document.getElementById("test").innerHTML = d;
docCookies.setItem("time", "test");```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <p id="test"></p></code>```

答:
Try this :-

```<code>document.cookie = "name=John Doe; expires=Tue, 01 Aug 2017 12:00:00 UTC";
</code>```

You can also go for Local Storage to store temporary data

```<code>localStorage.setItem("name", "John Doe");
</code>```

Happy Coding...

Body:
Try this :-

document.cookie = "name=John Doe; expires=Tue, 01 Aug 2017 12:00:00 UTC";

You can also go for Local Storage to store temporary data

localStorage.setItem("name", "John Doe");

Happy Coding...


问:
Performance Issues When Using Many CALayer Masks
I am trying to use CAShapeLayer to mask a CALayer in my iOS app as it takes a fraction of the CPU time to mask an image vs manually masking one in a bitmap context;

When I have several dozen or more images layered over each other, the CAShapeLayer masked UIImageView is slow to move to my touch.

Here is some example code:

```<code>UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"SomeImage.jpg" ofType:nil]];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(0.f, 0.f, image.size.width * .25, image.size.height * .25));

for (int i = 0; i < 200; i++) {

    SLTUIImageView *imageView = [[SLTUIImageView alloc]initWithImage:image];
    imageView.frame = CGRectMake(arc4random_uniform(CGRectGetWidth(self.view.bounds)), arc4random_uniform(CGRectGetHeight(self.view.bounds)), image.size.width * .25, image.size.height * .25);

    CAShapeLayer *shape = [CAShapeLayer layer];
    shape.path = path;
    imageView.layer.mask = shape;

    [self.view addSubview:imageView];
    [imageView release];

}
CGPathRelease(path);
</code>```

With the above code, imageView is very laggy. However, it reacts instantly if I mask it manually in a bitmap context:

```<code>UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"3.0-Pad-Classic0.jpg" ofType:nil]];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(0.f, 0.f, image.size.width * .25, image.size.height * .25));

for (int i = 0; i < 200; i++) {

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width * .25, image.size.height * .25), NO, [[UIScreen mainScreen]scale]);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextAddPath(ctx, path);
    CGContextClip(ctx);

    [image drawInRect:CGRectMake(-(image.size.width * .25), -(image.size.height * .25), image.size.width, image.size.height)];
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    SLTUIImageView *imageView = [[SLTUIImageView alloc]initWithImage:finalImage];
    imageView.frame = CGRectMake(arc4random_uniform(CGRectGetWidth(self.view.bounds)), arc4random_uniform(CGRectGetHeight(self.view.bounds)), finalImage.size.width, finalImage.size.height);

    [self.view addSubview:imageView];
    [imageView release];

}
CGPathRelease(path);
</code>```

By the way, here is the code to SLTUIImageView, it's just a simple subclass of UIImageView that responds to touches (for anyone who was wondering):

```<code>-(id)initWithImage:(UIImage *)image{

    self = [super initWithImage:image];
    if (self) {
        self.userInteractionEnabled = YES;
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.superview bringSubviewToFront:self];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    self.center = [touch locationInView:self.superview];
}
</code>```

Is it possible to somehow optimize how the CAShapeLayer is masking the UIImageView so that the  performance is improved? I have tried to find out where the bottle-neck is using the Time Profiler in Instruments, but I can't tell exactly what is causing it.

I have tried setting shouldRasterize to YES on both layer and on layer.mask but neither seem to have any effect. I'm not sure what to do.

Edit:

I have done more testing and find that if I use just a regular CALayer to mask another CALayer (layer.mask = someOtherLayer) I have the same performance issues. It seems that the problem isn't specific to CAShapeLayer—rather it is specific to the mask property of CALayer.

Edit 2:

So after learning more about using the Core Animation tool in Instruments, I learned that the view is being rendered offscreen each time it moves. Setting shouldRaster to YES when the touch begins and turning it off when the touch ends makes the view stay green (thus keeping the cache) in instruments, but performance is still terrible. I believe this is because even though the view is being cached, if it isn't opaque, than it still has to be re-rendered with each frame.

One thing to emphasize is that if there are only a few views being masked (say even around ten) the performance is pretty good. However, when you increase that to 100 or more, the performance lags. I imagine this is because when one moves over the others, they all have to be re-rendered.

My conclusion is this, I have one of two options.

First, there must be someway to permanently mask a view (render it once and call it good). I know this can be done via the graphic or bitmap context route as I show in my example code, but when a layer masks its view, it happens instantly. When I do it in a bitmap context as shown, it is quite slow (as in it almost can't even be compared how much slower it is).

Second, there must be some faster way to do it via the bitmap context route. If there is an expert in masking images or views, their help would be very much appreciated.

答: You've gotten pretty far along and I believe are almost to a solution. What I would do is simply an extension of what you've already tried. Since you say many of these layers are "ending up" in final positions that remain constant relative to the other layers, and the mask.. So simply render all those "finished" layers to a single bitmap context.  That way, every time you write out a layer to that single context, you'll have one less layer to worry about that is slowing down the animation/rendering process. </p>

Body:
I am trying to use CAShapeLayer to mask a CALayer in my iOS app as it takes a fraction of the CPU time to mask an image vs manually masking one in a bitmap context;

When I have several dozen or more images layered over each other, the CAShapeLayer masked UIImageView is slow to move to my touch.

Here is some example code:

UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"SomeImage.jpg" ofType:nil]];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(0.f, 0.f, image.size.width * .25, image.size.height * .25));

for (int i = 0; i < 200; i++) {

    SLTUIImageView *imageView = [[SLTUIImageView alloc]initWithImage:image];
    imageView.frame = CGRectMake(arc4random_uniform(CGRectGetWidth(self.view.bounds)), arc4random_uniform(CGRectGetHeight(self.view.bounds)), image.size.width * .25, image.size.height * .25);

    CAShapeLayer *shape = [CAShapeLayer layer];
    shape.path = path;
    imageView.layer.mask = shape;

    [self.view addSubview:imageView];
    [imageView release];

}
CGPathRelease(path);

With the above code, imageView is very laggy. However, it reacts instantly if I mask it manually in a bitmap context:

UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"3.0-Pad-Classic0.jpg" ofType:nil]];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(0.f, 0.f, image.size.width * .25, image.size.height * .25));

for (int i = 0; i < 200; i++) {

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width * .25, image.size.height * .25), NO, [[UIScreen mainScreen]scale]);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextAddPath(ctx, path);
    CGContextClip(ctx);

    [image drawInRect:CGRectMake(-(image.size.width * .25), -(image.size.height * .25), image.size.width, image.size.height)];
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    SLTUIImageView *imageView = [[SLTUIImageView alloc]initWithImage:finalImage];
    imageView.frame = CGRectMake(arc4random_uniform(CGRectGetWidth(self.view.bounds)), arc4random_uniform(CGRectGetHeight(self.view.bounds)), finalImage.size.width, finalImage.size.height);

    [self.view addSubview:imageView];
    [imageView release];

}
CGPathRelease(path);

By the way, here is the code to SLTUIImageView, it's just a simple subclass of UIImageView that responds to touches (for anyone who was wondering):

-(id)initWithImage:(UIImage *)image{

    self = [super initWithImage:image];
    if (self) {
        self.userInteractionEnabled = YES;
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.superview bringSubviewToFront:self];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    self.center = [touch locationInView:self.superview];
}

Is it possible to somehow optimize how the CAShapeLayer is masking the UIImageView so that the  performance is improved? I have tried to find out where the bottle-neck is using the Time Profiler in Instruments, but I can't tell exactly what is causing it.

I have tried setting shouldRasterize to YES on both layer and on layer.mask but neither seem to have any effect. I'm not sure what to do.

Edit:

I have done more testing and find that if I use just a regular CALayer to mask another CALayer (layer.mask = someOtherLayer) I have the same performance issues. It seems that the problem isn't specific to CAShapeLayer—rather it is specific to the mask property of CALayer.

Edit 2:

So after learning more about using the Core Animation tool in Instruments, I learned that the view is being rendered offscreen each time it moves. Setting shouldRaster to YES when the touch begins and turning it off when the touch ends makes the view stay green (thus keeping the cache) in instruments, but performance is still terrible. I believe this is because even though the view is being cached, if it isn't opaque, than it still has to be re-rendered with each frame.

One thing to emphasize is that if there are only a few views being masked (say even around ten) the performance is pretty good. However, when you increase that to 100 or more, the performance lags. I imagine this is because when one moves over the others, they all have to be re-rendered.

My conclusion is this, I have one of two options.

First, there must be someway to permanently mask a view (render it once and call it good). I know this can be done via the graphic or bitmap context route as I show in my example code, but when a layer masks its view, it happens instantly. When I do it in a bitmap context as shown, it is quite slow (as in it almost can't even be compared how much slower it is).

Second, there must be some faster way to do it via the bitmap context route. If there is an expert in masking images or views, their help would be very much appreciated.


问:
Build Mobile App for alexa?
Hi I have a custom skill running with alexa echo & is working fine. Now I need to build a mobile application (android native / Hybrid) that take input from my phone's mic, alexa processes this with my custom skill & return output that plays from my phone's speakers.

In short, I need an app doing all all echo is doing. Is it possible ? How ? And if yes, please provide me links that can be helpful. Any samples would be appreciated.

Thank you.

答:
Yes we are able to create the app like the alexa.

Will give you the blueprint of that.

You go through the google for the SpeechRecognizer in the android to start the app to listen to the speech and you will receive the text that is detected.

Use this text as input to the wit.ai search for the wit.ai the AI engine that will procees the context for the speech. You can attach your own alexa skills to that. The Wit.ai will return you the respected response back to the app.

Using the TextToSpeech engine of android api you can make the app to speak out to the user.

Also aditionally use the Sphinx-library that will help you to create the app that will wake up and will start recognizing with the key words like "ok- google", "alexa". You can configure your own.

Hope this would be helpful to you. Please do google for the steps.
I have created the similar app which you are looking for and have written the custom framework for maintain the context.Since it is proprietary, i cannot share it as a sample.

Title: Build Mobile App for alexa?


问:
Angular2 patchValue While Traversing Through FormGroup Controls
I am attempting to patch values into an initialized FormGroup once a component is loaded like so (where editForm is the FormGroup and editInfo is a JSON containing the information I want to patch into the form):

```<code>Object.keys(this.editForm.controls).forEach(key => {
                if ((key.includes("date") || key.includes("Date")) && this.editInfo[key] != undefined) {
                    this.editForm.patchValue({
                        key: {
                            date: {
                                year: this.editInfo[key].getFullYear(),
                                month: this.editInfo[key].getMonth() + 1,
                                day: this.editInfo[key].getDate()
                            }
                        }
                    });
                }
            });
</code>```

For some reason, this is not patching any of the values. The if statement is running when it is supposed to, and all of the .getFullYear(), .getMonth(), and .getDate() values (all of these key values are Date objects) are defined and correct. When I replace

```<code>this.editForm.patchValue({
                            key: {
                                date: {
</code>```

with

```<code>this.editForm.patchValue({
                            'specificKey': {
                                date: {
</code>```

that key is patched correctly. Is there any reason why not specifying the key would cause this not to work? This is the module I am using for my datepickers (the values I am trying to patch above) if that is of any use.

答:
Found my answer through this link (Is there a way to use variable keys in a JavaScript object literal?) provided by Ankit Saroch. The solution is to put [] around key when patching the value, like so:

```<code>this.editForm.patchValue({
                            [key]: {
                                date: {
</code>```

With the brackets, the keys are interpreted like computed property names.

Body:
I am attempting to patch values into an initialized FormGroup once a component is loaded like so (where editForm is the FormGroup and editInfo is a JSON containing the information I want to patch into the form):

Object.keys(this.editForm.controls).forEach(key => {
                if ((key.includes("date") || key.includes("Date")) && this.editInfo[key] != undefined) {
                    this.editForm.patchValue({
                        key: {
                            date: {
                                year: this.editInfo[key].getFullYear(),
                                month: this.editInfo[key].getMonth() + 1,
                                day: this.editInfo[key].getDate()
                            }
                        }
                    });
                }
            });

For some reason, this is not patching any of the values. The if statement is running when it is supposed to, and all of the .getFullYear(), .getMonth(), and .getDate() values (all of these key values are Date objects) are defined and correct. When I replace

this.editForm.patchValue({
                            key: {
                                date: {

with

this.editForm.patchValue({
                            'specificKey': {
                                date: {

that key is patched correctly. Is there any reason why not specifying the key would cause this not to work? This is the module I am using for my datepickers (the values I am trying to patch above) if that is of any use.

Body:
Found my answer through this link (Is there a way to use variable keys in a JavaScript object literal?) provided by Ankit Saroch. The solution is to put [] around key when patching the value, like so:

this.editForm.patchValue({
                            [key]: {
                                date: {

With the brackets, the keys are interpreted like computed property names.


问:
Is there a shorter way to make a unit converter program in C?
i am making a unit convert program, but my code is too long and just go on forever, here is the first part of my code :

```<code>int measure;
int from;
int to;
float input;
float output;

printf("Choose measurement :\n1 : Length\n2 : Area\n3 : Temparture\n");
measure = getch();

switch(measure){
    case '1' :
        printf("\nYou want to change from :\n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        from = getch();
        printf("\nTo : \n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        to = getch();

        printf("Enter number : ");   scanf("%f", &input);

        switch(from){
            case '1' :
                switch(to){
                    case '1' : output = input;                printf("%f mm = %f mm", input, output);   break;
                    case '2' : output = input/10;             printf("%f mm = %f cm", input, output);   break;
                    case '3' : output = input/1000;           printf("%f mm = %f dm", input, output);   break;
                    case '4' : output = input/10000;          printf("%f mm = %f m", input, output);   break;
                    case '5' : output = input/100000;         printf("%f mm = %f dcm", input, output);   break;
                    case '6' : output = input/1000000;        printf("%f mm = %f hm", input, output);   break;
                    case '7' : output = input/10000000;       printf("%f mm = %f km", input, output);   break;
                }
                break;

            case '2' :
                 switch(to){
                    case '1' : output = input*10;           printf("%f cm = %f mm", input, output);   break;
                    case '2' : output = input;              printf("%f cm = %f cm", input, output);   break;
                    case '3' : output = input/10;           printf("%f cm = %f dm", input, output);   break;
                    case '4' : output = input/100;          printf("%f cm = %f m", input, output);   break;
                    case '5' : output = input/1000;         printf("%f cm = %f dcm", input, output);   break;
                    case '6' : output = input/10000;        printf("%f cm = %f hm", input, output);   break;
                    case '7' : output = input/100000;       printf("%f cm = %f km", input, output);   break;
                }
                break;
</code>```

and it will go on case 3,4,5, ... until the kilometer, not including the area and the temparture measurement, and other thing i want to add

Is there any shorter way to do this ? Thanks :)

答:
You can do this trivially if you pick an Intermediate unit (arbitrarily?) which is the one you use internally. (I always use SI units for that.)

Then your conversions are always of the form

Input Unit -> Intermediate Unit -> Output Unit.

Since Unit -> Intermediate Unit is the reciprocal of Intermediate Unit -> Unit you only need to maintain a single-column table.

Body:
i am making a unit convert program, but my code is too long and just go on forever, here is the first part of my code :

int measure;
int from;
int to;
float input;
float output;

printf("Choose measurement :\n1 : Length\n2 : Area\n3 : Temparture\n");
measure = getch();

switch(measure){
    case '1' :
        printf("\nYou want to change from :\n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        from = getch();
        printf("\nTo : \n1 : mm\n2 : cm\n3 : dm\n4 : m\n5 : dcm\n6 : hm\n7 : km\n");
        to = getch();

        printf("Enter number : ");   scanf("%f", &input);

        switch(from){
            case '1' :
                switch(to){
                    case '1' : output = input;                printf("%f mm = %f mm", input, output);   break;
                    case '2' : output = input/10;             printf("%f mm = %f cm", input, output);   break;
                    case '3' : output = input/1000;           printf("%f mm = %f dm", input, output);   break;
                    case '4' : output = input/10000;          printf("%f mm = %f m", input, output);   break;
                    case '5' : output = input/100000;         printf("%f mm = %f dcm", input, output);   break;
                    case '6' : output = input/1000000;        printf("%f mm = %f hm", input, output);   break;
                    case '7' : output = input/10000000;       printf("%f mm = %f km", input, output);   break;
                }
                break;

            case '2' :
                 switch(to){
                    case '1' : output = input*10;           printf("%f cm = %f mm", input, output);   break;
                    case '2' : output = input;              printf("%f cm = %f cm", input, output);   break;
                    case '3' : output = input/10;           printf("%f cm = %f dm", input, output);   break;
                    case '4' : output = input/100;          printf("%f cm = %f m", input, output);   break;
                    case '5' : output = input/1000;         printf("%f cm = %f dcm", input, output);   break;
                    case '6' : output = input/10000;        printf("%f cm = %f hm", input, output);   break;
                    case '7' : output = input/100000;       printf("%f cm = %f km", input, output);   break;
                }
                break;

and it will go on case 3,4,5, ... until the kilometer, not including the area and the temparture measurement, and other thing i want to add

Is there any shorter way to do this ? Thanks :)


问:
How to perform actions on time basis in android?
In my application I want the user to auto log out after 10 PM and can login after 10 AM only .Now I am picking the current time but I don't know how to this for my scenario ,If the application is not in background then also it should work(I should work in background) .</p>

答:
You can use AlarmManager to schedule repeating actions.
Something like this:

myAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute


问:
Error: Opening Robot Framework log failed
If I open any .html file that generated by Robot Framework and try to convert it in any other format(for example, docx formate) using either any python code or inbuilt command line tool that are available. I am getting below error,

Opening Robot Framework log failed

•          Verify that you have JavaScript enabled in your browser.

•          Make sure you are using a modern enough browser. Firefox 3.5, IE 8, or equivalent is required, newer browsers are recommended.

•          Check are there messages in your browser's JavaScript error log. Please report the problem if you suspect you have encountered a bug.

·      I am getting this error even though I have already enabled JavaScript in my browser.I am using Mozilla Firefox version 45.0.2 on mac.

Can anyone please help me to solve this issue?

答:
Running below code in Script Console of Manage Jenkins will work

```<code>System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;")
</code>```

But whenever you start Jenkins then you have to execute this every time. Instead of this if you use this when you are starting Jenkins by using of batch file with below code then it will be better than this process

```<code>java -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;" -jar jenkins.war
</code>```

Body:
Running below code in Script Console of Manage Jenkins will work

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;")

But whenever you start Jenkins then you have to execute this every time. Instead of this if you use this when you are starting Jenkins by using of batch file with below code then it will be better than this process

java -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;" -jar jenkins.war


问:
:host selector for angular-material dialog
I'm using an dialog component from angular-material where I want to style the popup dialog.

I know there is some built-in support for styling through the generating component:

```<code>let dialogRef = dialog.open(MyDialogComponent, {
  height: '400px',
  width: '600px',
  panelClass: 'some-class'
});
</code>```

But this causes the style definition to split up in the dialog component style and the generation definition. What I would like to do is adjust the dialog style itself for all dialogs of this type. A logical step would be to use :host on the component css:

```<code>:host {
    width: 600px;
    padding: 0px;
}
</code>```

Plunker to illustrate my point.

Is this in any way possible?

答:
Plunker example

I added display: block

```<code>:host { /* This is not working as expected */
  width: 800px;
  padding: 0px;
  display: block;
}
</code>```

and changed this part in PlunkerAppModule

```<code>  declarations: [DialogOverviewExample, DialogOverviewExampleDialog],
  bootstrap: [DialogOverviewExample],
  entryComponents: [DialogOverviewExampleDialog],
  providers: []
})
</code>```

Body:
I'm using an dialog component from angular-material where I want to style the popup dialog.

I know there is some built-in support for styling through the generating component:

let dialogRef = dialog.open(MyDialogComponent, {
  height: '400px',
  width: '600px',
  panelClass: 'some-class'
});

But this causes the style definition to split up in the dialog component style and the generation definition. What I would like to do is adjust the dialog style itself for all dialogs of this type. A logical step would be to use :host on the component css:

:host {
    width: 600px;
    padding: 0px;
}

Plunker to illustrate my point.

Is this in any way possible?

Body:
Plunker example

I added display: block

:host { /* This is not working as expected */
  width: 800px;
  padding: 0px;
  display: block;
}

and changed this part in PlunkerAppModule

  declarations: [DialogOverviewExample, DialogOverviewExampleDialog],
  bootstrap: [DialogOverviewExample],
  entryComponents: [DialogOverviewExampleDialog],
  providers: []
})


问:
how to redirect external link in webview in android
I have a problem with webview. I get url in onCreate method. In that page i have a login screen after click submit button user should redirect another, different website url and also go new tab. How can i do that? It cant perform any thing now.

```<code>@Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

        if (getArguments() != null) {
            tvScreenTitle.setText(getArguments().getString(CONTENT_TITLE));
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {

                int logoMarginY = (int) (rlScreenHeader.getHeight() * 0.6f);
                int logoMarginX = (int) (rlScreenHeader.getWidth() * 0.3f);

                UIHelper.setMarginTop(btnBack, logoMarginY - btnBack.getHeight() / 2);
                UIHelper.setMarginTop(tvScreenTitle, logoMarginY - tvScreenTitle.getHeight() / 2);
                UIHelper.setMarginLeft(tvScreenTitle, logoMarginX);
            }
        });

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportMultipleWindows(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg)
            {
                webView.loadUrl(url);
                return true;
            }
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        webView.setWebViewClient(webViewClient);

        webView.loadUrl(this.url);
    }
</code>```

This is my onCreateView;

```<code>@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_app_browser, container, false);
        ButterKnife.bind(this, view);

        UIHelper.setTypeface(rootFragment, GlobalApplication.getInstance().getTypeface());
        return view;
    }

    boolean loadingFinished = true;
    boolean redirect = false;

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!loadingFinished) {
                redirect = true;
            }
            loadingFinished = false;
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loadingFinished = false;

            AppBrowserFragment.this.url = url;
            tvAddressBarTitle.setText(url);

            progressAddressBar.setVisibility(View.VISIBLE);
            rlAddressBar.setVisibility(View.VISIBLE);
            btnRefresh.setImageResource(R.drawable.browsericon_reloadover);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if(!redirect){
                loadingFinished = true;
            }

            if(loadingFinished && !redirect){
                AppBrowserFragment.this.url = url;

                if (StringUtils.isNotNullOrWhitespace(title)) {
                    tvAddressBarTitle.setText(title);
                }
                else {
                    tvAddressBarTitle.setText(view.getTitle());
                }

                progressAddressBar.setVisibility(View.INVISIBLE);
                rlAddressBar.setVisibility(View.GONE);

                btnRefresh.setImageResource(R.drawable.browsericon_reload);

                btnBackBrowser.setImageResource(webView.canGoBack() ? R.drawable.browsericon_back : R.drawable.browsericon_backover);
                btnForward.setImageResource(webView.canGoForward() ? R.drawable.browsericon_forward : R.drawable.browsericon_forwardover);

            }
            else {
                redirect = false;
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.cancel();
        }
    };
</code>```

答:
Use condition vice versa what ever you want </p>

```<code>@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.contains("/shuffle")) {
        mWebView.loadUrl(url);
        return false;
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
        return true;
    }
}
</code>```

Body:
I have a problem with webview. I get url in onCreate method. In that page i have a login screen after click submit button user should redirect another, different website url and also go new tab. How can i do that? It cant perform any thing now.

@Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

        if (getArguments() != null) {
            tvScreenTitle.setText(getArguments().getString(CONTENT_TITLE));
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {

                int logoMarginY = (int) (rlScreenHeader.getHeight() * 0.6f);
                int logoMarginX = (int) (rlScreenHeader.getWidth() * 0.3f);

                UIHelper.setMarginTop(btnBack, logoMarginY - btnBack.getHeight() / 2);
                UIHelper.setMarginTop(tvScreenTitle, logoMarginY - tvScreenTitle.getHeight() / 2);
                UIHelper.setMarginLeft(tvScreenTitle, logoMarginX);
            }
        });

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportMultipleWindows(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg)
            {
                webView.loadUrl(url);
                return true;
            }
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        webView.setWebViewClient(webViewClient);

        webView.loadUrl(this.url);
    }

This is my onCreateView;

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_app_browser, container, false);
        ButterKnife.bind(this, view);

        UIHelper.setTypeface(rootFragment, GlobalApplication.getInstance().getTypeface());
        return view;
    }

    boolean loadingFinished = true;
    boolean redirect = false;

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!loadingFinished) {
                redirect = true;
            }
            loadingFinished = false;
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loadingFinished = false;

            AppBrowserFragment.this.url = url;
            tvAddressBarTitle.setText(url);

            progressAddressBar.setVisibility(View.VISIBLE);
            rlAddressBar.setVisibility(View.VISIBLE);
            btnRefresh.setImageResource(R.drawable.browsericon_reloadover);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if(!redirect){
                loadingFinished = true;
            }

            if(loadingFinished && !redirect){
                AppBrowserFragment.this.url = url;

                if (StringUtils.isNotNullOrWhitespace(title)) {
                    tvAddressBarTitle.setText(title);
                }
                else {
                    tvAddressBarTitle.setText(view.getTitle());
                }

                progressAddressBar.setVisibility(View.INVISIBLE);
                rlAddressBar.setVisibility(View.GONE);

                btnRefresh.setImageResource(R.drawable.browsericon_reload);

                btnBackBrowser.setImageResource(webView.canGoBack() ? R.drawable.browsericon_back : R.drawable.browsericon_backover);
                btnForward.setImageResource(webView.canGoForward() ? R.drawable.browsericon_forward : R.drawable.browsericon_forwardover);

            }
            else {
                redirect = false;
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.cancel();
        }
    };

Body:
Use condition vice versa what ever you want

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.contains("/shuffle")) {
        mWebView.loadUrl(url);
        return false;
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
        return true;
    }
}


问:
Read the embed PDF file in Excel using Aspose.Cells
I'm trying to read PDF files in Excel and save it to local using Aspose.Cells for C#,
but when I read the PDF's ObjectSourceFullName , it's "*. bin", and other attributes also not show anything identify it's PDF.
How this happened and how to solve this?
Please help me,  Thanks!!!

答:
You can identify the type of OLE object with its ClassIdentifier property. It is a 16-bytes number. Convert it to GUID and then check what this GUID means inside the Windows Registry.

```<code>Guid guid = new Guid(wb.Worksheets[0].OleObjects[0].ClassIdentifier);
</code>```

The following screenshot explains that {b801ca65-a1fc-11d0-85ad-444553540000} actually means Adobe Acrobat Document.

Note: I am working as Developer Evangelist at Aspose

Body:
You can identify the type of OLE object with its ClassIdentifier property. It is a 16-bytes number. Convert it to GUID and then check what this GUID means inside the Windows Registry.

Guid guid = new Guid(wb.Worksheets[0].OleObjects[0].ClassIdentifier);

The following screenshot explains that {b801ca65-a1fc-11d0-85ad-444553540000} actually means Adobe Acrobat Document.

Note: I am working as Developer Evangelist at Aspose


问:
How to clear basic authentication details in chrome
I'm working on a site that uses basic authentication. Using Chrome I've logged in using the basic auth. I now want to remove the basic authentication details from the browser and try a different login.

How do you clear the current basic authentication details when using Chrome?

答:
This isn't exactly what the question is asking for but in case you accidentally saved basic auth credentials and want to clear them or update them:

https://support.google.com/accounts/answer/6197437

Open Chrome.

At the top right, click More > and then Settings.

At the bottom, click Advanced.

Under "Passwords and forms," click Manage passwords.

Under "Saved Passwords", click Remove on the site you want to clear saved basic auth credentials.

Steps 1-4 can be quickly navigated with this link: chrome://settings/passwords

This worked in Chrome Version 59.0.3071.115


问:
Angular HTTP get response not the same as what network tab shows
I'm having an intermittent issue in that when I make a call via the Angular HTTP service:

```<code>        return $http({
        url: '/campaign/' + campaignId,
        method: 'GET'
    }).then(
        function(response) {
            response.data.hardcode = dfltValues.hardcode;

            response.data.endDate = new Date(response.data.endDate).toISOString();
            response.data.startDate = new Date(response.data.startDate).toISOString();

            return response;
        },
        function(err) {
            console.log(err);
            return false;
        }
    );
</code>```

What's weird is that every 10th time or so when I refresh the page some of the values are coming back as undefined, yet the network tab says that all the values came through correctly. Also this seems to only be happening on Chrome. I haven't been able to reproduce in FF/IE/Safari. Any help would be appreciated!

Thanks!

答: I found the issue to be a plugin I was using called angularjs-slider, I threw a watcher on the variables that were affected and found that they were defined correctly coming in, but then right away were set to undefined. I switched out the plugin to just use the standard input type of "range" and everything is working now.</p>

Body:
I'm having an intermittent issue in that when I make a call via the Angular HTTP service:

        return $http({
        url: '/campaign/' + campaignId,
        method: 'GET'
    }).then(
        function(response) {
            response.data.hardcode = dfltValues.hardcode;

            response.data.endDate = new Date(response.data.endDate).toISOString();
            response.data.startDate = new Date(response.data.startDate).toISOString();

            return response;
        },
        function(err) {
            console.log(err);
            return false;
        }
    );

What's weird is that every 10th time or so when I refresh the page some of the values are coming back as undefined, yet the network tab says that all the values came through correctly. Also this seems to only be happening on Chrome. I haven't been able to reproduce in FF/IE/Safari. Any help would be appreciated!

Thanks!


问:
awk to add specific fields to file based on match in field
I am trying to use awk to add the $4,$5,$6 fields and the header in the tab-delimeted file2 to the lines that in file2 $2 there is a matching $3 value in file1. I added comments to each line as well as to my understanding of whats going on. Thank you :).

file1  tab-delimeted

```<code>ID  Name    Number
0-0 A,A 123456
2-2 B,B 789123
4-4 C,C 456789
</code>```

file2  tab-delimeted

```<code>ID  Number  Name    Info1   Info2   Info3   Info4
0-0 123456  A,A aaaaa   bbbbb   ccccc   eeeee
1-1 111111  Z,Z aaa bbb ccc eee
2-2 789123  B,B aaaaa   bb,bbb  ccccc   eeeee
3-3 222222  Y,Y aaa bb,bb   cc  e
4-4 456789  C,C aaa bb  ccc eeee
</code>```

desired output  tab-delimeted

```<code>ID  Name    Number  Info1   Info2   Info3
0-0 A,A 123456  aaaaa   bbbbb   ccccc
2-2 B,B 789123  aaaaa   bb,bbb  ccccc
4-4 C,C 456789  aaa bb  ccc
</code>```

awk

```<code>awk -F"\t" '$3 in a{  # read $3 value of file1 into array a
 a[$3]=a[$2];   # match $3 array a from file1 with $2 value in file2
  next   # process next line
 }  # close block
  { print $1,$2,a[$2],$4,$5,$6  # print desired output
 }  # close block
    END {  # start block
 for ( i in a) {   # create for loop i to print
     print a[i]  # print for each matching line in i
  }  # close block
}' file1 file2
</code>```

答:
```<code>$ awk -v OFS="\t" 'NR==FNR{a[$3]=$0;next}$2 in a{print a[$2],$4,$5,$6}' file1 file2
ID      Name    Number  Info1   Info2   Info3
0-0     A,A     123456  aaaaa   bbbbb   ccccc
2-2     B,B     789123  aaaaa   bb,bbb  ccccc
4-4     C,C     456789  aaa     bb      ccc
</code>```

Explained:

```<code>$ awk -v OFS="\t" '         # tab as OFS also
NR==FNR{                    # for file1
    a[$3]=$0                # hash $0 to a using $3 as key
    next                    # no further processing for this record
}
$2 in a {                   # if $2 found in a
    print a[$2],$4,$5,$6    # output as requested
}' file1 file2              # mind the file order
</code>```

Body:
I am trying to use awk to add the $4,$5,$6 fields and the header in the tab-delimeted file2 to the lines that in file2 $2 there is a matching $3 value in file1. I added comments to each line as well as to my understanding of whats going on. Thank you :).

file1  tab-delimeted

ID  Name    Number
0-0 A,A 123456
2-2 B,B 789123
4-4 C,C 456789

file2  tab-delimeted

ID  Number  Name    Info1   Info2   Info3   Info4
0-0 123456  A,A aaaaa   bbbbb   ccccc   eeeee
1-1 111111  Z,Z aaa bbb ccc eee
2-2 789123  B,B aaaaa   bb,bbb  ccccc   eeeee
3-3 222222  Y,Y aaa bb,bb   cc  e
4-4 456789  C,C aaa bb  ccc eeee

desired output  tab-delimeted

ID  Name    Number  Info1   Info2   Info3
0-0 A,A 123456  aaaaa   bbbbb   ccccc
2-2 B,B 789123  aaaaa   bb,bbb  ccccc
4-4 C,C 456789  aaa bb  ccc

awk

awk -F"\t" '$3 in a{  # read $3 value of file1 into array a
 a[$3]=a[$2];   # match $3 array a from file1 with $2 value in file2
  next   # process next line
 }  # close block
  { print $1,$2,a[$2],$4,$5,$6  # print desired output
 }  # close block
    END {  # start block
 for ( i in a) {   # create for loop i to print
     print a[i]  # print for each matching line in i
  }  # close block
}' file1 file2

Body:
$ awk -v OFS="\t" 'NR==FNR{a[$3]=$0;next}$2 in a{print a[$2],$4,$5,$6}' file1 file2
ID      Name    Number  Info1   Info2   Info3
0-0     A,A     123456  aaaaa   bbbbb   ccccc
2-2     B,B     789123  aaaaa   bb,bbb  ccccc
4-4     C,C     456789  aaa     bb      ccc

Explained:

$ awk -v OFS="\t" '         # tab as OFS also
NR==FNR{                    # for file1
    a[$3]=$0                # hash $0 to a using $3 as key
    next                    # no further processing for this record
}
$2 in a {                   # if $2 found in a
    print a[$2],$4,$5,$6    # output as requested
}' file1 file2              # mind the file order


问:
I want my Game to be at the bottom not at the top?
I have a school project where i want to programm a Gaming site but the game i copied from another website is always at the top can you help me to bring it down ?
I want the Game to be in the Center of the Website under the Hotbar :)
HTML CODE:

```<code> <!DOCTYPE html>
    <html>
    <head>
        <title>Games</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <link rel="stylesheet" href="css/nav.css">
        <style>
    canvas {
        border:1px solid #d3d3d3;
        background-color: #f1f1f1;
    }
    </style>
    </head>
    <body onload="startGame()">
         <div class="nav">
            <ul>
                <li><a href="">Aventure Games</a></li>
                <li><a href="">1vs1 Games</a></li>
                <li id="logo"><img src="src/logogif.gif" style="width:300px;"></li>
                <li><a href="">Other Categories</a></li>
                <li><a href="">About us</a></li>
            </ul>
        </div>
        <article>
            <h1>Games</h1>
            <p>content bla bla</p>
        </article>

        <p class="flappybird">
        <script>

    var myGamePiece;
    var myObstacles = [];
    var myScore;

    function startGame() {
        myGamePiece = new component(30, 30, "red", 10, 120);
        myGamePiece.gravity = 0.05;
        myScore = new component("30px", "Consolas", "black", 280, 40, "text");
        myGameArea.start();
    }

    var myGameArea = {
        canvas : document.createElement("canvas"),
        start : function() {
            this.canvas.width = 480;
            this.canvas.height = 270;
            this.context = this.canvas.getContext("2d");
            document.body.insertBefore(this.canvas, document.body.childNodes[0]);
            this.frameNo = 0;
            this.interval = setInterval(updateGameArea, 20);
            },
        clear : function() {
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
    }

    function component(width, height, color, x, y, type) {
        this.type = type;
        this.score = 0;
        this.width = width;
        this.height = height;
        this.speedX = 0;
        this.speedY = 0;
        this.x = x;
        this.y = y;
        this.gravity = 0;
        this.gravitySpeed = 0;
        this.update = function() {
            ctx = myGameArea.context;
            if (this.type == "text") {
                ctx.font = this.width + " " + this.height;
                ctx.fillStyle = color;
                ctx.fillText(this.text, this.x, this.y);
            } else {
                ctx.fillStyle = color;
                ctx.fillRect(this.x, this.y, this.width, this.height);
            }
        }
        this.newPos = function() {
            this.gravitySpeed += this.gravity;
            this.x += this.speedX;
            this.y += this.speedY + this.gravitySpeed;
            this.hitBottom();
        }
        this.hitBottom = function() {
            var rockbottom = myGameArea.canvas.height - this.height;
            if (this.y > rockbottom) {
                this.y = rockbottom;
                this.gravitySpeed = 0;
            }
        }
        this.crashWith = function(otherobj) {
            var myleft = this.x;
            var myright = this.x + (this.width);
            var mytop = this.y;
            var mybottom = this.y + (this.height);
            var otherleft = otherobj.x;
            var otherright = otherobj.x + (otherobj.width);
            var othertop = otherobj.y;
            var otherbottom = otherobj.y + (otherobj.height);
            var crash = true;
            if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
                crash = false;
            }
            return crash;
        }
    }

    function updateGameArea() {
        var x, height, gap, minHeight, maxHeight, minGap, maxGap;
        for (i = 0; i < myObstacles.length; i += 1) {
            if (myGamePiece.crashWith(myObstacles[i])) {
                return;
            }
        }
        myGameArea.clear();
        myGameArea.frameNo += 1;
        if (myGameArea.frameNo == 1 || everyinterval(150)) {
            x = myGameArea.canvas.width;
            minHeight = 20;
            maxHeight = 200;
            height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
            minGap = 50;
            maxGap = 200;
            gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
            myObstacles.push(new component(10, height, "green", x, 0));
            myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
        }
        for (i = 0; i < myObstacles.length; i += 1) {
            myObstacles[i].x += -1;
            myObstacles[i].update();
        }
        myScore.text="SCORE: " + myGameArea.frameNo;
        myScore.update();
        myGamePiece.newPos();
        myGamePiece.update();
    }

    function everyinterval(n) {
        if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
        return false;
    }

    function accelerate(n) {
        myGamePiece.gravity = n;
    }
    </script>
    <br>
    <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
    <p>Use the ACCELERATE button to stay in the air</p>
    <p>How long can you stay alive?</p>
    </body>
    </html>
</code>```

CSS CODE:

```<code>*{

        margin: 0px;
        background-color:darkred;
    }
    .nav{
        height: 100px;
    }

    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        text-align: center;
        /*padding-left: 30%;
        padding-right: 30%;*/
        /*overflow: hidden;*/
        background-color: gray;
        height:70px;
    }

    li {
        /*float: left;*/
        display: inline-block;
        vertical-align: top;
        margin: 0 -2px;

    }

    li a {
        display: block;
        font-family: Verdana, Helvetica, sans-serif;
        color: white;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
        background-color: darkred;
    }
    #logo {
        /*display: block;*/
        font-family: Verdana, Helvetica, sans-serif;
        background-color: black;
        text-align: center;
        padding: 10px;
        text-decoration: none;
    }
    #logo img{
        display: block;
    }

    li a:hover {
        background-color: black;
        color: white;
    }

    }
    p{font-family:Tahoma;}

    article {
        padding-left: 12px;
    }
</code>```

答:
You've got to define the correct place you want to insert your new element, in your case the canvas.
In your code snippet below, you tell the canvas to be placed before the first child node of the document body.

```<code>document.body.insertBefore(this.canvas, document.body.childNodes[0]);
</code>```

You need to specify an element to place it before, below it's looking for the first element with the class name flappybird.

```<code>document.body.insertBefore(this.canvas, document.getElementsByClassName("flappybird")[0]);
</code>```

Body:
I have a school project where i want to programm a Gaming site but the game i copied from another website is always at the top can you help me to bring it down ?
I want the Game to be in the Center of the Website under the Hotbar :)
HTML CODE:

 <!DOCTYPE html>

        <title>Games</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <link rel="stylesheet" href="css/nav.css">

Aventure Games

1vs1 Games

Other Categories

About us

Games

content bla bla

    <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>

Use the ACCELERATE button to stay in the air

How long can you stay alive?

CSS CODE:

*{

        margin: 0px;
        background-color:darkred;
    }
    .nav{
        height: 100px;
    }

    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        text-align: center;
        /*padding-left: 30%;
        padding-right: 30%;*/
        /*overflow: hidden;*/
        background-color: gray;
        height:70px;
    }

    li {
        /*float: left;*/
        display: inline-block;
        vertical-align: top;
        margin: 0 -2px;

    }

    li a {
        display: block;
        font-family: Verdana, Helvetica, sans-serif;
        color: white;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
        background-color: darkred;
    }
    #logo {
        /*display: block;*/
        font-family: Verdana, Helvetica, sans-serif;
        background-color: black;
        text-align: center;
        padding: 10px;
        text-decoration: none;
    }
    #logo img{
        display: block;
    }

    li a:hover {
        background-color: black;
        color: white;
    }

    }
    p{font-family:Tahoma;}

    article {
        padding-left: 12px;
    }

Body:
You've got to define the correct place you want to insert your new element, in your case the canvas.
In your code snippet below, you tell the canvas to be placed before the first child node of the document body.

document.body.insertBefore(this.canvas, document.body.childNodes[0]);

You need to specify an element to place it before, below it's looking for the first element with the class name flappybird.

document.body.insertBefore(this.canvas, document.getElementsByClassName("flappybird")[0]);


问:
RandomStringGenerator to generate alphanumeric strings
Can I use Apache's common-text RandomStringGenerator to generate random alphanumeric strings (numbers and lowercase/uppercase letters)?

答:
I use this:

```<code>static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's',
        'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A',
        'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' };

private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        stringBuilder.append(chars[new Random().nextInt(chars.length)]);
    }
    return stringBuilder.toString();
}
</code>```

or

```<code>private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        switch (new Random().nextInt(3)) {
            case 0:
                stringBuilder.append((char) (new Random().nextInt(9) + 48));
                break;
            case 1:
                stringBuilder.append((char) (new Random().nextInt(25) + 65));
                break;
            case 2:
                stringBuilder.append((char) (new Random().nextInt(25) + 97));
                break;
            default:
                break;
        }
    }
    return stringBuilder.toString();
}
</code>```

Body:
I use this:

static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's',
        'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A',
        'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' };

private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        stringBuilder.append(chars[new Random().nextInt(chars.length)]);
    }
    return stringBuilder.toString();
}

or

private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        switch (new Random().nextInt(3)) {
            case 0:
                stringBuilder.append((char) (new Random().nextInt(9) + 48));
                break;
            case 1:
                stringBuilder.append((char) (new Random().nextInt(25) + 65));
                break;
            case 2:
                stringBuilder.append((char) (new Random().nextInt(25) + 97));
                break;
            default:
                break;
        }
    }
    return stringBuilder.toString();
}