问:
Do Cython extension types support class attributes?
Python classes can have class attributes:

```<code>class Foo(object):
   bar = 4
</code>```

Is there an analogous construct for defining class attributes in Cython extension types? For example, when I try to compile the following cython code

```<code>cdef class Foo:
    cdef int bar
    bar = 4
</code>```

I get this error:

```<code>thing.c:773:3: error: use of undeclared identifier 'bar'
  bar = 4;
  ^
1 error generated.
error: command 'cc' failed with exit status 1
</code>```

答:
The short answer is yes and no.

No, there is not a convenient syntactic idiom for quickly inserting a class attribute in a cdef class.  However ....

The whole point of cython is that it gives you lower level access.  The usual motive for the extra effort is performance, but you can also do C-like things with the extra freedom.  The difficulty is, there are many pitfalls, and in this case, you won't get pure python class attributes without a lot of work.  It is nevertheless pretty easy to get what you need for simple use cases.

For example, suppose I'm making some calculating engine as a class and I wish to globally set the precision of the return value for all instances.  I want a default at compile time, and from time to time I may want to adjust it lower to quickly process some trials, and then adjust it higher for my final work.  A class attribute is made to order, but you can get the functionality you need in cython as follows:

First, define at the module level the following:

```<code>cdef int _precision[1]  # storage for my class 'attribute'
_precision[0]=8         # my default value, set during compilation
</code>```

Using an array permits us to use the cython idiom precision[0] which is equivalent to the C *precision.  The cdef name precision is implicitly a pointer since the data item is an array.   This permits using cython syntactic idioms to convert from cython storage locations to python references.  If all you want is a global constant that may be accessed by cdef code in any of the classes in the module, you are done.  If you want to use it strictly as a class attribute, you must enforce that discipline - the compiler doesn't care.

Now if you also want to adjust the value from python code, you will need a pair of cdef functions that python code in the module can call to access the 'attribute':

```<code>cdef int*  get_precision(): return _precision
cdef void* set_precision(int i): _precision[0]=i
</code>```

At this point, the semantics will vary a bit from pure python, unless you really want to sweat.  You need a python setter and getter function, and I find the python descriptor protocol implemented by properties is easiest:

```<code>cdef class SomeCalculator:
  ...

  property precision:
    def __get__(self):
      """Get or set calculation precision, default == 8.
         This is like a class attribute: setting affects all instances,
         however, it also affects all subclasses."""
      return get_precision()[0]
    def __set__(self,int integer): set_precision(min(30,max(0,integer)))
</code>```

The first gets a python reference to the 'attribute'.  The second sets the 'attribute' with a python integral value, policed to fall within limits.  The cython function call and return interface automatically takes care of conversions, which are more complex than they look.

For example, get_precision returns a C-pointer.  If you did the dereferencing in get_precision you would get an error trying to return a C-int in __get__ as if it were python.  If instead you just omitted the [0] dereference in __get__ you would get an error trying to return a C-pointer as if it were a python int.  As written, automatic conversions correctly match types.  cython is very finicky about this sort of thing, and can silently return incorrect values, discoverable only at runtime.  It can take some experimentation to infer the correct incantation.

The docstring tells you not to expect a pure python class attribute.  If you want to sub-class, and have sub-classes use a different global setting, you will need to sweat a bit more.  In python, all that is done automatically.

Even so, there are other differences.  A real class attribute may be referenced on the class or on an instance.  This property may only be referenced on an instance.  Setting a real class attribute on the instance creates an instance specific copy, leaving the class attribute untouched, but invisible to the altered instance.

For the given use case, this works.  A real class attribute is unnecessary.  Since cython code is usually less abstract and compute intensive, this minimal approach is often enough.

Body:
Python classes can have class attributes:

class Foo(object):
   bar = 4

Is there an analogous construct for defining class attributes in Cython extension types? For example, when I try to compile the following cython code

cdef class Foo:
    cdef int bar
    bar = 4

I get this error:

thing.c:773:3: error: use of undeclared identifier 'bar'
  bar = 4;
  ^
1 error generated.
error: command 'cc' failed with exit status 1

Body:
The short answer is yes and no.

No, there is not a convenient syntactic idiom for quickly inserting a class attribute in a cdef class.  However ....

The whole point of cython is that it gives you lower level access.  The usual motive for the extra effort is performance, but you can also do C-like things with the extra freedom.  The difficulty is, there are many pitfalls, and in this case, you won't get pure python class attributes without a lot of work.  It is nevertheless pretty easy to get what you need for simple use cases.

For example, suppose I'm making some calculating engine as a class and I wish to globally set the precision of the return value for all instances.  I want a default at compile time, and from time to time I may want to adjust it lower to quickly process some trials, and then adjust it higher for my final work.  A class attribute is made to order, but you can get the functionality you need in cython as follows:

First, define at the module level the following:

cdef int _precision[1]  # storage for my class 'attribute'
_precision[0]=8         # my default value, set during compilation

Using an array permits us to use the cython idiom precision[0] which is equivalent to the C *precision.  The cdef name precision is implicitly a pointer since the data item is an array.   This permits using cython syntactic idioms to convert from cython storage locations to python references.  If all you want is a global constant that may be accessed by cdef code in any of the classes in the module, you are done.  If you want to use it strictly as a class attribute, you must enforce that discipline - the compiler doesn't care.

Now if you also want to adjust the value from python code, you will need a pair of cdef functions that python code in the module can call to access the 'attribute':

cdef int*  get_precision(): return _precision
cdef void* set_precision(int i): _precision[0]=i

At this point, the semantics will vary a bit from pure python, unless you really want to sweat.  You need a python setter and getter function, and I find the python descriptor protocol implemented by properties is easiest:

cdef class SomeCalculator:
  ...

  property precision:
    def __get__(self):
      """Get or set calculation precision, default == 8.
         This is like a class attribute: setting affects all instances,
         however, it also affects all subclasses."""
      return get_precision()[0]
    def __set__(self,int integer): set_precision(min(30,max(0,integer)))

The first gets a python reference to the 'attribute'.  The second sets the 'attribute' with a python integral value, policed to fall within limits.  The cython function call and return interface automatically takes care of conversions, which are more complex than they look.

For example, get_precision returns a C-pointer.  If you did the dereferencing in get_precision you would get an error trying to return a C-int in __get__ as if it were python.  If instead you just omitted the [0] dereference in __get__ you would get an error trying to return a C-pointer as if it were a python int.  As written, automatic conversions correctly match types.  cython is very finicky about this sort of thing, and can silently return incorrect values, discoverable only at runtime.  It can take some experimentation to infer the correct incantation.

The docstring tells you not to expect a pure python class attribute.  If you want to sub-class, and have sub-classes use a different global setting, you will need to sweat a bit more.  In python, all that is done automatically.

Even so, there are other differences.  A real class attribute may be referenced on the class or on an instance.  This property may only be referenced on an instance.  Setting a real class attribute on the instance creates an instance specific copy, leaving the class attribute untouched, but invisible to the altered instance.

For the given use case, this works.  A real class attribute is unnecessary.  Since cython code is usually less abstract and compute intensive, this minimal approach is often enough.


来源: stackexchange

问:
Indexing an NVARCHAR(MAX) column in SQL Server
When I define a column as NVARCHAR(MAX), I can't index that column. But I certainly can't define the column as NVARCHAR(4000) since I assume the data string will be longer sometimes.

Can anyone suggest how to index the column with NVARCHAR(MAX) data definition or is it possible to increase the length from 4000 to more?

答:
You have either nvarchar(4000) or nvarchar(max). Nothing in between

Maximum length of the index key column(s) together is 900 bytes, so you can't index nvarchar(4000) either (which is 8000 bytes)

Personally, I can't see why you need to index nvarchar(max).

Are you seriously going to search for strings up to 1GB long?

Anyway, your only option is to use HASHBYTES in a persisted computed column.

You create a hash of the column, and index the HASH.

Note, depending on what version you may not be able to hash nvarchar(max)

For SQL Server 2014 and earlier, allowed input values are limited to 8000 bytes.

SQL Server 2016 code example that also enforces uniqueness

The SHA2_512 hash gives the least chance of collision. For a sufficiently large table a weaker hash like MD4 will hit the birthday problem

```<code>CREATE TABLE dbo.HashExample (
    SomeID int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
    SomeLongText nvarchar(MAX) NULL,
    SomeHash AS HASHBYTES('SHA2_512', SomeLongText) PERSISTED
)
GO
CREATE UNIQUE INDEX UX_SomeHash ON dbo.HashExample(SomeHash) WHERE SomeLongText IS NULL
GO

INSERT dbo.HashExample (SomeLongText) VALUES ('Row 1'), ('Row 2')
GO
SELECT * FROM dbo.HashExample
GO

DECLARE @LookFor nvarchar(MAX) = 'Row 3'
SELECT * FROM dbo.HashExample WHERE SomeHash = HASHBYTES('SHA2_512', @LookFor)
SET @LookFor = 'Row 2'
SELECT * FROM dbo.HashExample WHERE SomeHash = HASHBYTES('SHA2_512', @LookFor)
GO
</code>```

Note, you can't have LIKE searches. Only = or <>

ContentLicense: CC BY-SA 4.0

Body:
You have either nvarchar(4000) or nvarchar(max). Nothing in between

Maximum length of the index key column(s) together is 900 bytes, so you can't index nvarchar(4000) either (which is 8000 bytes)

Personally, I can't see why you need to index nvarchar(max).

Are you seriously going to search for strings up to 1GB long?

Anyway, your only option is to use HASHBYTES in a persisted computed column.

You create a hash of the column, and index the HASH.

Note, depending on what version you may not be able to hash nvarchar(max)

For SQL Server 2014 and earlier, allowed input values are limited to 8000 bytes.

SQL Server 2016 code example that also enforces uniqueness

The SHA2_512 hash gives the least chance of collision. For a sufficiently large table a weaker hash like MD4 will hit the birthday problem

CREATE TABLE dbo.HashExample (
    SomeID int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
    SomeLongText nvarchar(MAX) NULL,
    SomeHash AS HASHBYTES('SHA2_512', SomeLongText) PERSISTED
)
GO
CREATE UNIQUE INDEX UX_SomeHash ON dbo.HashExample(SomeHash) WHERE SomeLongText IS NULL
GO

INSERT dbo.HashExample (SomeLongText) VALUES ('Row 1'), ('Row 2')
GO
SELECT * FROM dbo.HashExample
GO

DECLARE @LookFor nvarchar(MAX) = 'Row 3'
SELECT * FROM dbo.HashExample WHERE SomeHash = HASHBYTES('SHA2_512', @LookFor)
SET @LookFor = 'Row 2'
SELECT * FROM dbo.HashExample WHERE SomeHash = HASHBYTES('SHA2_512', @LookFor)
GO

Note, you can't have LIKE searches. Only = or <>

ContentLicense: CC BY-SA 3.0


问:
How can I recursively copy the directory contents and exclude the source directory itself?
Using FileUtils cp_r is usually how I copy directories, but I can't seem to exclude the base directory.  This is what I wanted to work, but it doesn't:

```<code>FileUtils.cp_r "#{source_path}\\**", target_path, :verbose => true
</code>```

source_path has sub-directories I want to copy recursively.  I just don't want the actual source_path directory, just everything below it.

I tried using Dir.glob but could not get it right.

This is a Windows copy and I know I can use xcopy but want to know how to do it in Ruby.

答:
Please use the FileUtils.copy_entry utility. Provide the entire path for both source & destination. It will copy recursively from source to destination excluding the source parent directory. This method preserves file types, c.f. symlink, directory… (FIFO, device files and etc. are not supported yet)

Example usage:

```<code>src = "/path/to/source/dir"
dest = "/path/to/destination/dir"
preserve = false
dereference_root = false
remove_destination = false

FileUtils.copy_entry(src, dest, preserve, dereference_root, remove_destination)
</code>```

Both of src and dest must be a path name. src must exist, dest must not exist.

If preserve is true, this method preserves owner, group, permissions and modified time. Optional use.

If dereference_root is true, this method dereference tree root. Optional use.

If remove_destination is true, this method removes each destination file before copy. Optional use.

For more information, check out the documentation.

Body:
Using FileUtils cp_r is usually how I copy directories, but I can't seem to exclude the base directory.  This is what I wanted to work, but it doesn't:

FileUtils.cp_r "#{source_path}\\**", target_path, :verbose => true

source_path has sub-directories I want to copy recursively.  I just don't want the actual source_path directory, just everything below it.

I tried using Dir.glob but could not get it right.

This is a Windows copy and I know I can use xcopy but want to know how to do it in Ruby.

Body:
Please use the FileUtils.copy_entry utility. Provide the entire path for both source & destination. It will copy recursively from source to destination excluding the source parent directory. This method preserves file types, c.f. symlink, directory… (FIFO, device files and etc. are not supported yet)

Example usage:

src = "/path/to/source/dir"
dest = "/path/to/destination/dir"
preserve = false
dereference_root = false
remove_destination = false

FileUtils.copy_entry(src, dest, preserve, dereference_root, remove_destination)

Both of src and dest must be a path name. src must exist, dest must not exist.

If preserve is true, this method preserves owner, group, permissions and modified time. Optional use.

If dereference_root is true, this method dereference tree root. Optional use.

If remove_destination is true, this method removes each destination file before copy. Optional use.

For more information, check out the documentation.


问:
Interface Builder Accessibility Label Spanning Multiple Elements
Does anyone know of a way to have a single value for an accessibility label span across multiple elements?  I have two labels that form a single title line and the screen reader reads them separately.  I have tried selecting both and applying the setting and it doesn't work.

EDIT:

Here is a view of my storyboard...

However, when the screen readers reaches this point, it reads the first label (not using the accessibility value) and then the second label.

答:
We can group elements using UIAccessibilityElement class and provide a combined frame of the elements you want to group using accessibilityFrameInContainerSpace property.

```<code>//From Apple Docs
let profileElement = UIAccessibilityElement(accessibilityContainer: headerView)
profileElement.accessibilityLabel = profileNameLabel.text
profileElement.accessibilityValue = openPostsLabel.text
profileElement.accessibilityTraits |= UIAccessibilityTraitButton     // Tells VoiceOver to treat our new view like a button

let combinedLabelFrame = profileNameLabel.frame.union(openPostsLabel.frame)
let profileElementFrame = combinedLabelFrame.union(profileImageView.frame) //providing union of frames.
// This tells VoiceOver where the element is on screen so a user can find it as they touch around for elements
profileElement.accessibilityFrameInContainerSpace = profileElementFrame
</code>```

Check apple docs Whats new in accessibility.

Link for sample app explaining how to do it.

Body:
We can group elements using UIAccessibilityElement class and provide a combined frame of the elements you want to group using accessibilityFrameInContainerSpace property.

//From Apple Docs
let profileElement = UIAccessibilityElement(accessibilityContainer: headerView)
profileElement.accessibilityLabel = profileNameLabel.text
profileElement.accessibilityValue = openPostsLabel.text
profileElement.accessibilityTraits |= UIAccessibilityTraitButton     // Tells VoiceOver to treat our new view like a button

let combinedLabelFrame = profileNameLabel.frame.union(openPostsLabel.frame)
let profileElementFrame = combinedLabelFrame.union(profileImageView.frame) //providing union of frames.
// This tells VoiceOver where the element is on screen so a user can find it as they touch around for elements
profileElement.accessibilityFrameInContainerSpace = profileElementFrame

Check apple docs Whats new in accessibility.

Link for sample app explaining how to do it.


问:
Trying to join 2 tables and SUM() time from dates
I am trying to write an SQL query that will create a list of all the books that have been checked out in the past month, and how long each book has been checked out.

I have a books table...

```<code>library6=# SELECT * FROM books;
 isbn |                 title                 |    author
------+---------------------------------------+---------------
  111 | Harry Potter and the Sorcerer’s Stone | JK Rowlings
  222 | The Art of the Deal                   | Trump
  333 | to catch a crook                      | Robert Muller
  444 | Im a cool guy                         | Forrest Stone
  555 | rich i am                             | Bill Gates
(5 rows)
</code>```

and a transactions table with the records of when the books where checked out

```<code>library6=# SELECT * FROM transactions;
 id | checked_out_date | checked_in_date | user_id | isbn
----+------------------+-----------------+---------+------
  1 | 2016-01-01       | 2016-02-01      |       1 |  111
  2 | 2016-02-02       | 2016-03-02      |       2 |  111
  3 | 2016-03-03       | 2016-05-03      |       3 |  111
  4 | 2017-12-06       |                 |       4 |  111
  5 | 2017-11-29       | 2017-12-04      |       5 |  555
  6 | 2017-11-28       | 2017-12-05      |       1 |  333
(6 rows)
</code>```

A few of my nearer misses have been

```<code>library6=# SELECT DISTINCT  books.title, books.author  FROM books LEFT OUTER  JOIN transactions ON books.isbn = transactions.isbn ;
                 title                 |    author
---------------------------------------+---------------
 Harry Potter and the Sorcerer’s Stone | JK Rowlings
 rich i am                             | Bill Gates
 The Art of the Deal                   | Trump
 Im a cool guy                         | Forrest Stone
 to catch a crook                      | Robert Muller
(5 rows)
</code>```

答:
In mysql you could use datediff() , sum() and group by</p>

```<code>SELECT   b.title
      , b.author
      , sum(DATEDIFF(t.checked_in_date , t.checked_out_date)) num_days
FROM books b
LEFT  JOIN transactions t ON b.isbn = t.isbn
group by  b.title, b.author
</code>```

Body:
I am trying to write an SQL query that will create a list of all the books that have been checked out in the past month, and how long each book has been checked out.

I have a books table...

library6=# SELECT * FROM books;
 isbn |                 title                 |    author
------+---------------------------------------+---------------
  111 | Harry Potter and the Sorcerer’s Stone | JK Rowlings
  222 | The Art of the Deal                   | Trump
  333 | to catch a crook                      | Robert Muller
  444 | Im a cool guy                         | Forrest Stone
  555 | rich i am                             | Bill Gates
(5 rows)

and a transactions table with the records of when the books where checked out

library6=# SELECT * FROM transactions;
 id | checked_out_date | checked_in_date | user_id | isbn
----+------------------+-----------------+---------+------
  1 | 2016-01-01       | 2016-02-01      |       1 |  111
  2 | 2016-02-02       | 2016-03-02      |       2 |  111
  3 | 2016-03-03       | 2016-05-03      |       3 |  111
  4 | 2017-12-06       |                 |       4 |  111
  5 | 2017-11-29       | 2017-12-04      |       5 |  555
  6 | 2017-11-28       | 2017-12-05      |       1 |  333
(6 rows)

A few of my nearer misses have been

library6=# SELECT DISTINCT  books.title, books.author  FROM books LEFT OUTER  JOIN transactions ON books.isbn = transactions.isbn ;
                 title                 |    author
---------------------------------------+---------------
 Harry Potter and the Sorcerer’s Stone | JK Rowlings
 rich i am                             | Bill Gates
 The Art of the Deal                   | Trump
 Im a cool guy                         | Forrest Stone
 to catch a crook                      | Robert Muller
(5 rows)

Body:
In mysql you could use datediff() , sum() and group by

SELECT   b.title
      , b.author
      , sum(DATEDIFF(t.checked_in_date , t.checked_out_date)) num_days
FROM books b
LEFT  JOIN transactions t ON b.isbn = t.isbn
group by  b.title, b.author


问:
Mongodb: get only array of post comments from this object
So far I achieved is I got the array inside the object and I want the array directly.

Here is my object:

```<code>{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "description" : "My Post",
    "postLikes" : [
        {
            "likesCount" : 0,
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512631701702),
            "updatedOn" : NumberLong(0)
        }
    ],
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ],
    "createdOn" : NumberLong(0),
    "updatedOn" : NumberLong(0)
}
</code>```

My Query is:

```<code>db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1})
</code>```

and the result is:

```<code>{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
}
</code>```

What I want is:

```<code> [
        {
            "_id" : null,
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
</code>```

Also I am using MongoRepository in Spring Boot and the query there is:

```<code>@Query(value = "{'_id' : ?0}, {'postComments':1}")
</code>```

and it gave me the same result.

答:
Using find you will never be able to get the array as a result because as per definition:

the find() method “returns documents,” the method is actually
  returning a cursor to the documents.

You can apply projections to the result set but it would essentially always return you a document which unfortunately will always be a json and embeds the array as a property.

Same applies to the insert function you can not insert an array by itself it has to be a valid JSON.

```<code>> db.arrCollection.insert(["name":"myName", "age": 100]);
2017-12-08T13:02:30.492+0530 E QUERY    SyntaxError: Unexpected token :
</code>```

Body:
So far I achieved is I got the array inside the object and I want the array directly.

Here is my object:

{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "description" : "My Post",
    "postLikes" : [
        {
            "likesCount" : 0,
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512631701702),
            "updatedOn" : NumberLong(0)
        }
    ],
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ],
    "createdOn" : NumberLong(0),
    "updatedOn" : NumberLong(0)
}

My Query is:

db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1})

and the result is:

{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
}

What I want is:

 [
        {
            "_id" : null,
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]

Also I am using MongoRepository in Spring Boot and the query there is:

@Query(value = "{'_id' : ?0}, {'postComments':1}")

and it gave me the same result.

Body:
Using find you will never be able to get the array as a result because as per definition:

the find() method “returns documents,” the method is actually
  returning a cursor to the documents.

You can apply projections to the result set but it would essentially always return you a document which unfortunately will always be a json and embeds the array as a property.

Same applies to the insert function you can not insert an array by itself it has to be a valid JSON.

> db.arrCollection.insert(["name":"myName", "age": 100]);
2017-12-08T13:02:30.492+0530 E QUERY    SyntaxError: Unexpected token :


问:
Charles proxy fails on SSL Connect Method
I have Android 4.3 forced to use Charles proxy via IPTABLES.
The charles certificate is installed on the phone.
I am able to capture normal SSL traffic like https websites in the browser.
All POST and GET methods seem to work fine.
In a particular app, it fails when using the SSL CONNECT method.

URL: https://XX.XX.XXX.XXX/

Status: Failed

Failure: SSLHandshake: Received fatal alert: unknown_ca

Response Code: - Protocol: HTTP/1.0

Method: CONNECT

答:
I got the following error when I was trying to install the cert on my Nexus 6p, Android 6.0. (I followed the instructions in charles and downloaded the cert via http://chls.pro/ssl.):

Couldn't install because the certificate file couldn't be read.

The solution  to this problem was to install via:
Settings > Security > Install from storage
After navigating to the cert file and installing it everything worked as expected.


问:
Enable Strict transport security mvc
I want to enable strict transport security.
MY website is a https enable.
Below is my code to enable hsts.

```<code><system.webServer>
    <httpProtocol>
      <customHeaders>

          <add name="X-Frame-Options" value="SAMEORIGIN" />
          **<add name="Strict-Transport-Security" value="max-age=31536000"/>**
         .....
        </customHeaders>
    </httpProtocol>
</code>```

Is above setting is enough to make strict transport security enable or do i also need to add below setting ie.

```<code><rewrite>
      <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
              redirectType="Permanent" />
        </rule>
      </rules>
      <outboundRules>
        <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
          <match serverVariable="RESPONSE_Strict_Transport_Security"
              pattern=".*" />
          <conditions>
            <add input="{HTTPS}" pattern="on" ignoreCase="true" />
          </conditions>
          <action type="Rewrite" value="max-age=31536000" />
        </rule>
      </outboundRules>
    </rewrite>
</code>```

If both setting are mandatory then what is the need for rewrite
can we enable hsts by only
or by only
rewrite .

Why rewrite is required.

This site says to add rewrite alogn with

<add name="Strict-Transport-Security" value="max-age=31536000"/>

答:
This header force the browser to use HTTPS. If the application has HTTP link given somewhere or if the user tries to enter URL with HTTP, the browser will redirect him to https. To use HSTS, the site need valid SSL certificate. The rewrite is not mandatory, but its good to have. Because, if the user first enter the site with https, then whenever he comes to the site, user will be automatically redirected until expiry, also the max age updates on each visit. But if user enters once in http mode, the STS may not work until he use the site in https once. Its better to use the rewrite.

```<code><system.webServer>
<httpProtocol>
<customHeaders>
<add name="Strict-Transport-Security" value="max-age=xxxxxx"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</code>```

https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security

Title: Enable Strict transport security mvc

Body:
I want to enable strict transport security.
MY website is a https enable.
Below is my code to enable hsts.

<system.webServer>
    <httpProtocol>
      <customHeaders>

          <add name="X-Frame-Options" value="SAMEORIGIN" />
          **<add name="Strict-Transport-Security" value="max-age=31536000"/>**
         .....
        </customHeaders>
    </httpProtocol>

Is above setting is enough to make strict transport security enable or do i also need to add below setting ie.

<rewrite>
      <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
              redirectType="Permanent" />
        </rule>
      </rules>
      <outboundRules>
        <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
          <match serverVariable="RESPONSE_Strict_Transport_Security"
              pattern=".*" />
          <conditions>
            <add input="{HTTPS}" pattern="on" ignoreCase="true" />
          </conditions>
          <action type="Rewrite" value="max-age=31536000" />
        </rule>
      </outboundRules>
    </rewrite>

If both setting are mandatory then what is the need for rewrite
can we enable hsts by only
or by only
rewrite .

Why rewrite is required.

This site says to add rewrite alogn with

<add name="Strict-Transport-Security" value="max-age=31536000"/>

Body:
This header force the browser to use HTTPS. If the application has HTTP link given somewhere or if the user tries to enter URL with HTTP, the browser will redirect him to https. To use HSTS, the site need valid SSL certificate. The rewrite is not mandatory, but its good to have. Because, if the user first enter the site with https, then whenever he comes to the site, user will be automatically redirected until expiry, also the max age updates on each visit. But if user enters once in http mode, the STS may not work until he use the site in https once. Its better to use the rewrite.

<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Strict-Transport-Security" value="max-age=xxxxxx"/>
</customHeaders>
</httpProtocol>
</system.webServer>

https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security


问:
importXML from yahoo.com specific table : recentrly viewd
google sheet,
url : https://finance.yahoo.com
trying to get with IMPORTXML, specific table, named : 'recently viewed' from this site .
I tried to get all tables with :

```<code>importXML("https://finance.yahoo.com","//table")
</code>```

but got error:

Imported Xml content can not be parsed.

tried also :
importHTML("https://finance.yahoo.com","table",1) (or other index table)
got empty data

答: Recently viewed is user specific - for example when I load that page , it is empty for me - because I havent used yahoo in roughly a decade, but its blank whether im logged in or not, which means when you make the request from google sheets, your like a brand new user with no history. SO the table is empty.</p>

Body:
google sheet,
url : https://finance.yahoo.com
trying to get with IMPORTXML, specific table, named : 'recently viewed' from this site .
I tried to get all tables with :

importXML("https://finance.yahoo.com","//table")

but got error:

Imported Xml content can not be parsed.

tried also :
importHTML("https://finance.yahoo.com","table",1) (or other index table)
got empty data


问:
Draggable button in Firefox
Is it possible to make a <button> (<input type="button">) work with HTML5 drag and drop in Mozilla Firefox (while still being clickable)?

The following snippet works in Google Chrome but the button and div with button cannot be dragged Mozilla Firefox (unless the Alt key is pressed down, no idea about mobile):

document.getElementById("myDiv").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myDiv")
  }
);

document.getElementById("myButton").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myButton")
  }
);

document.getElementById("myDivWithButton").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myDivWithButton")
  }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myDiv" draggable="true">Div</div>
<button id="myButton" draggable="true">Button</button>
<div id="myDivWithButton" draggable="true"><button>Div with Button</button></div></code>```

I used draggable="true" and dataTransfer.setData, is there something I missed? Is there some sensible workaround?

(If you want to know what I need this for:  I have something which can be either dragged at a certain position or set at the default position [center of current view], my idea was to do both through the button [d&d → choose position, click → default position]. I know that I guess I could try to format a
 to make it look like a <button> or simply split the control into two elements but I'd rather not.)

答:
There is already a bug on Firefox where you can't drag a button.
https://bugzilla.mozilla.org/show_bug.cgi?id=568313

However you can drag your div containing button (which is not draggable right now) using 'after' pseudo class.
Example:

document.getElementById("myDivWithButton").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myDivWithButton")
  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.frontdrop {
   position: relative;
}

.frontdrop:after {
    content: '';
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
}</code>```

<button>Div with Button</button>
```

Title: Draggable button in Firefox

Body:
Is it possible to make a <button> (<input type="button">) work with HTML5 drag and drop in Mozilla Firefox (while still being clickable)?

The following snippet works in Google Chrome but the button and div with button cannot be dragged Mozilla Firefox (unless the Alt key is pressed down, no idea about mobile):

document.getElementById("myDiv").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myDiv")
  }
);

document.getElementById("myButton").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myButton")
  }
);

document.getElementById("myDivWithButton").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myDivWithButton")
  }
);

Div

<button id="myButton" draggable="true">Button</button>

<button>Div with Button</button>

I used draggable="true" and dataTransfer.setData, is there something I missed? Is there some sensible workaround?

(If you want to know what I need this for:  I have something which can be either dragged at a certain position or set at the default position [center of current view], my idea was to do both through the button [d&d → choose position, click → default position]. I know that I guess I could try to format a
 to make it look like a <button> or simply split the control into two elements but I'd rather not.)

Body:
There is already a bug on Firefox where you can't drag a button.
https://bugzilla.mozilla.org/show_bug.cgi?id=568313

However you can drag your div containing button (which is not draggable right now) using 'after' pseudo class.
Example:

document.getElementById("myDivWithButton").addEventListener(
  "dragstart",
  function (e) {
    e.dataTransfer.setData("Text", "myDivWithButton")
  }
);

.frontdrop {
   position: relative;
}

.frontdrop:after {
    content: '';
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
}

<div id="myDivWithButton" class="frontdrop" draggable="true"><button>Div with Button</button></div>


问:
How do I use the Eclipse debugger in an AsyncTask when developing for Android?
I'm running ADT (Android Development Tools) in Eclipse and verified that my debugger is working by putting a breakpoint in MainMenu.oncreate (class Activity). But when I put it in the first line of my AsyncTask.doInBackground, it never hits it. I know it's running because I put a Log statement in the AsyncTask and it shows up in LogCat. Any help would be appreciated as I prefer the debugger over the logging.

My versions:

```<code>Eclipse SDK Version: 3.6.1
Build id: M20100909-0800
</code>```

答:
Put the following code fragment in the beginning of doInBackground:

android.os.Debug.waitForDebugger();

Then when you set a breakpoint in that thread, eclipse will find it.

ContentLicense: CC BY-SA 2.5

Body:
I'm running ADT (Android Development Tools) in Eclipse and verified that my debugger is working by putting a breakpoint in MainMenu.oncreate (class Activity). But when I put it in the first line of my AsyncTask.doInBackground, it never hits it. I know it's running because I put a Log statement in the AsyncTask and it shows up in LogCat. Any help would be appreciated as I prefer the debugger over the logging.

My versions:

Eclipse SDK Version: 3.6.1
Build id: M20100909-0800


问:
How to make all the duplicated value in each column filled by '0'
My Question is making all the duplicated value in each column filled by '0'.

My data looks like:

Code:

df2 = df[['timestamp', 'temperature', 'humidity', 'light', 'pressure', 'speed', 'battery_voltage', 'ddp']]
df2['timestamp'] = pd.to_datetime(df['timestamp'])
df2['timestamp'] = df2['timestamp'].map(lambda x:
datetime.datetime.strftime(x,'%Y-%m-%d'))
df2 = df2.groupby('timestamp',as_index = False).sum()
df2['timestamp'] = pd.to_datetime(df2['timestamp'], format = '%Y-%m-%d')
df2.sort_values(by = ['timestamp'], ascending = [True])
df2.set_index('timestamp', inplace = True)
df2 = df2.resample('D').ffill().reset_index()
df2.duplicated(['temperature', 'humidity','light','pressure', 'speed', 'battery_voltage'])
```

I have used boolean method, it give me 'True' and 'False' back.

答:
I think that the ffill() method is the main problem. This has to be replaced with fillna(). I also simplified your code a bit:

```<code>df2 = df[['timestamp', 'temperature', 'humidity', 'light', 'pressure', 'speed', 'battery_voltage', 'ddp']]
df2['timestamp'] = pd.to_datetime(df['timestamp']).set_index('timestamp', inplace = True)
# df2 = df2.groupby(pd.Grouper(freq='D')).sum()
df2 = df2.resample('D').sum().fillna(0).reset_index()
</code>```

The line I put in comment is not needed, but you could use it, when you want to group your data by day (and don't want to resample it)

Body:
My Question is making all the duplicated value in each column filled by '0'.

My data looks like:

Code:

df2 = df[['timestamp', 'temperature', 'humidity', 'light', 'pressure', 'speed', 'battery_voltage', 'ddp']]
df2['timestamp'] = pd.to_datetime(df['timestamp'])
df2['timestamp'] = df2['timestamp'].map(lambda x:
datetime.datetime.strftime(x,'%Y-%m-%d'))
df2 = df2.groupby('timestamp',as_index = False).sum()
df2['timestamp'] = pd.to_datetime(df2['timestamp'], format = '%Y-%m-%d')
df2.sort_values(by = ['timestamp'], ascending = [True])
df2.set_index('timestamp', inplace = True)
df2 = df2.resample('D').ffill().reset_index()
df2.duplicated(['temperature', 'humidity','light','pressure', 'speed', 'battery_voltage'])

I have used boolean method, it give me 'True' and 'False' back.

Body:
I think that the ffill() method is the main problem. This has to be replaced with fillna(). I also simplified your code a bit:

df2 = df[['timestamp', 'temperature', 'humidity', 'light', 'pressure', 'speed', 'battery_voltage', 'ddp']]
df2['timestamp'] = pd.to_datetime(df['timestamp']).set_index('timestamp', inplace = True)
# df2 = df2.groupby(pd.Grouper(freq='D')).sum()
df2 = df2.resample('D').sum().fillna(0).reset_index()

The line I put in comment is not needed, but you could use it, when you want to group your data by day (and don't want to resample it)


问:
Return Object Based on Query Strings
I'm trying to return objects based on query strings.

For example, I would like api/users/{id}?fields=username,email,reputation to return an object of type User that contains only the three included properties (username, email, reputation).

On a side note, comma separated query strings are not possible by default in .NET Core.

Here's a tutorial on making that work.

Following the guide above, I have a list of strings. How can I create an object that only includes the properties that match the names of those strings?

For only a few strings I can do this (thanks Ben Hall):

```<code>List<string> listOfStrings ...; // Strings from query
User user = GetUser(id); // User from db

User newUser = new User();

if (listOfStrings.Contains("username"))
    newUser.username = user.username;
if (listOfStrings.Contains("email"))
    newUser.email = user.email;
if (listOfStrings.Contains("reputation"))
    newUser.reputation = user.reputation;
</code>```

But for a long list of strings (my user class has 30+ properties) how would I go about doing this?

For reference, Facebook Graph API does this.

答:
Turns out there is actually Middleware for this called Popcorn.

Popcorn is a communication protocol on top of a RESTful API that allows requesting clients to identify individual fields of resources to include when retrieving the resource or resource collection.

It allows for a recursive selection of fields, allowing multiple calls
  to be condensed into one.

Features:

Selective inclusion from a RESTful API

Configurable response defaults

Sorting of responses

Selective authorization and permissioning of response values

Configurable response inspectors

Factory and advanced projection support

Set relevant contexts for your API

Blind expansion f response objects

Title: Return Object Based on Query Strings

Body:
I'm trying to return objects based on query strings.

For example, I would like api/users/{id}?fields=username,email,reputation to return an object of type User that contains only the three included properties (username, email, reputation).

On a side note, comma separated query strings are not possible by default in .NET Core.

Here's a tutorial on making that work.

Following the guide above, I have a list of strings. How can I create an object that only includes the properties that match the names of those strings?

For only a few strings I can do this (thanks Ben Hall):

List<string> listOfStrings ...; // Strings from query
User user = GetUser(id); // User from db

User newUser = new User();

if (listOfStrings.Contains("username"))
    newUser.username = user.username;
if (listOfStrings.Contains("email"))
    newUser.email = user.email;
if (listOfStrings.Contains("reputation"))
    newUser.reputation = user.reputation;

But for a long list of strings (my user class has 30+ properties) how would I go about doing this?

For reference, Facebook Graph API does this.


问:
how to scroll the page to bottom whenever the page load?
Requirement-  I want to scroll the content to the bottom of the page whenever the page load.

Here is my html code

```<code><ion-content  style="background-color: #f5f8fa;">
  <p style="line-height:24px;padding-left:10px;margin-top:20px;text-transform:capitalize;font-size:16px;">{{this.TASKDESC}}</p>
 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">
      <div [style.margin]="list.TAG_FROM === loggedinuser ? '0px 0px 0px -12px':'0px -12px 0px 0px'" [style.float]="list.TAG_FROM === loggedinuser ? 'right':'left'" style="width:33px;height:33px;background-color:#818993;overflow:hidden;color:#fff;z-index:9.9999999;border-radius:50%;font-size:14px;text-align:center;padding-top:7px;" >{{list.TAG_FROM.substring(0,2)}}</div>
      </div>
    </ion-item>
  </ion-list>
</ion-content>
</code>```

Current position of the page

What i want-  The image of the page

Scroll to bottom automatically whenever the page load.

答:
The simplest method is to set the scrollDownOnLoad property to true on the ion-content.

```<code><ion-content scrollDownOnLoad="true">

</ion-content>
</code>```

Find the official documentation here

Body:
Requirement-  I want to scroll the content to the bottom of the page whenever the page load.

Here is my html code

<ion-content  style="background-color: #f5f8fa;">

{{this.TASKDESC}}

 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">

{{list.TAG_FROM.substring(0,2)}}

    </ion-item>
  </ion-list>
</ion-content>

Current position of the page

What i want-  The image of the page

Scroll to bottom automatically whenever the page load.

Body:
The simplest method is to set the scrollDownOnLoad property to true on the ion-content.

<ion-content scrollDownOnLoad="true">

</ion-content>

Find the official documentation here


问:
Check if arrays are defined and not empty in ansible
I have the following code

```<code>- set_fact:
    MY_HOSTNAME: "SOME VALUE"
    MY_SERVER: "00.00.00.00"
- name: Get MY server
  set_fact:
    MY_SERVER: "{{ groups[MY_HOSTNAME][0] }}"
  when: groups[MY_HOSTNAME] is defined
</code>```

In the above code, groups[MY_HOSTNAME] is an array. What is the best way to check that groups[MY_HOSTNAME] is defined and also that it is not empty
If it is either of that I want the value 00.00.00.00 to be assigned to MY_SERVER

答:
list | length filter returns the number of elements. If it is zero, the list is empty.

For a conditional value use if or ternary filter (example in this answer).

For a composite conditional (groups[MY_HOSTNAME]| default([])) | length.

Body:
I have the following code

- set_fact:
    MY_HOSTNAME: "SOME VALUE"
    MY_SERVER: "00.00.00.00"
- name: Get MY server
  set_fact:
    MY_SERVER: "{{ groups[MY_HOSTNAME][0] }}"
  when: groups[MY_HOSTNAME] is defined

In the above code, groups[MY_HOSTNAME] is an array. What is the best way to check that groups[MY_HOSTNAME] is defined and also that it is not empty
If it is either of that I want the value 00.00.00.00 to be assigned to MY_SERVER


问:
fix html Symbol Entities with php
I have one form for adding book to library (database) ...

Its my form:

```<code><form>
    <input type="text" name="title">
    <input type="text" name="text">
    <input type="submit">
</form>
</code>```

If I use the form 'Words', the form will not be submited

I think i want this code in php :

```<code>str_replace("'", "'", '".$_POST['title']."');
</code>```

But it very very hard for all characters

答:
You can use this statement to replace all POST items

```<code>foreach ($_POST as &$post){
    $post = htmlentities($post, ENT_QUOTES);
}
</code>```

Or use PDO quote method to escape the quotes

```<code>foreach ($_POST as &$post)
{
    $post = $your_pdo_connection->quote($post);
}
</code>```

Title: fix html Symbol Entities with php

Body:
I have one form for adding book to library (database) ...

Its my form:

<form>
    <input type="text" name="title">
    <input type="text" name="text">
    <input type="submit">
</form>

If I use the form 'Words', the form will not be submited

I think i want this code in php :

str_replace("'", "'", '".$_POST['title']."');

But it very very hard for all characters

Body:
You can use this statement to replace all POST items

foreach ($_POST as &$post){
    $post = htmlentities($post, ENT_QUOTES);
}

Or use PDO quote method to escape the quotes

foreach ($_POST as &$post)
{
    $post = $your_pdo_connection->quote($post);
}


问:
why we cannot use "=" to shared_ptr or unique_ptr?
I fount the syntax got compile error.

```<code>std::shared_ptr<int> p = new int(5);

31 41 E:\temprory (delete it if u like)\1208.cpp [Error] conversion from 'int*' to non-scalar type 'std::shared_ptr<int>' requested
</code>```

But it is O.K

```<code>std::shared_ptr<int> p(new int(5));
</code>```

The same as unique_ptr;

But I don't know why it is prohibited.

答: Imagine if you accidentally passed an int * pointer that you had to a function that took a std::shared_ptr<int>. When the function completed, the pointer would be freed. If you really want to transfer ownership, you should indicate so explicitly.

Body:
I fount the syntax got compile error.

std::shared_ptr<int> p = new int(5);

31 41 E:\temprory (delete it if u like)\1208.cpp [Error] conversion from 'int*' to non-scalar type 'std::shared_ptr<int>' requested

But it is O.K

std::shared_ptr<int> p(new int(5));

The same as unique_ptr;

But I don't know why it is prohibited.


问:
Applications resolved by Intents with Extra "EXTRA_INITIAL_INTENTS" not shown
I am trying to share file with email clients and Google Drive. Now, in following code, only Google drive is opening and email clients are not opening at all.  I can provide equivalent Java code of following code if required

```<code>    val photoURI: Uri = FileProvider.getUriForFile(this, "com.emerson.oversight.com.emerson.oversight.provider",
            File(this.cacheDir.path + "/SensorReport.pdf"))

    val emailIntent = Intent(Intent.ACTION_SENDTO)
    emailIntent.data = Uri.parse("mailto:")

    emailIntent.putExtra(Intent.EXTRA_STREAM, photoURI)
    emailIntent.putExtra(Intent.EXTRA_EMAIL, "asd@dsa.dsa")
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "dsadsada")
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

    val driveIntent = Intent()
    driveIntent.`package`= "com.google.android.apps.docs"
    driveIntent.action = Intent.ACTION_VIEW

    val fileID = File(this.cacheDir.path + "/SensorReport.pdf")
    val url = "https://docs.google.com/file/d/" + fileID

    driveIntent.data = Uri.parse(url)

        val openInChooser = Intent.createChooser(driveIntent, getString(R.string.share_using))
        openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayListOf(emailIntent))
        startActivity(openInChooser)
</code>```

Please help

答:
You were almost there, the only missing piece in the puzzle is the getPackageManager().queryIntentActivities method that will return all activities that can handle your email intent. With the ResolveInfo returned you can build an intent for each email option to be displayed in the chooser. Then you can pass the array of those intents as Intent.EXTRA_INITIAL_INTENTS. You could even exclude certain packages if you like here. So the final part of your code would look something like this:

```<code>        val openInChooser = Intent.createChooser(driveIntent, getString(R.string.share_using))

        val emailOptionIntents = mutableListOf<Intent>()
        val resInfo = getPackageManager().queryIntentActivities(emailIntent, 0)
        if (!resInfo.isEmpty()) {
            for (resolveInfo in resInfo) {
                val emailOptionIntent = Intent(Intent.ACTION_SENDTO)
                emailOptionIntent.data = Uri.parse("mailto:")

                emailOptionIntent.putExtra(Intent.EXTRA_STREAM, photoURI)
                emailOptionIntent.putExtra(Intent.EXTRA_EMAIL, "asd@dsa.dsa")
                emailOptionIntent.putExtra(Intent.EXTRA_SUBJECT, "dsadsada")
                emailOptionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

                emailOptionIntent.`package` = resolveInfo.activityInfo.packageName
                emailOptionIntents.add(emailOptionIntent)
            }
        }

        openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailOptionIntents.toTypedArray())
        startActivity(openInChooser)
</code>```

Body:
I am trying to share file with email clients and Google Drive. Now, in following code, only Google drive is opening and email clients are not opening at all.  I can provide equivalent Java code of following code if required

    val photoURI: Uri = FileProvider.getUriForFile(this, "com.emerson.oversight.com.emerson.oversight.provider",
            File(this.cacheDir.path + "/SensorReport.pdf"))

    val emailIntent = Intent(Intent.ACTION_SENDTO)
    emailIntent.data = Uri.parse("mailto:")

    emailIntent.putExtra(Intent.EXTRA_STREAM, photoURI)
    emailIntent.putExtra(Intent.EXTRA_EMAIL, "asd@dsa.dsa")
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "dsadsada")
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

    val driveIntent = Intent()
    driveIntent.`package`= "com.google.android.apps.docs"
    driveIntent.action = Intent.ACTION_VIEW

    val fileID = File(this.cacheDir.path + "/SensorReport.pdf")
    val url = "https://docs.google.com/file/d/" + fileID

    driveIntent.data = Uri.parse(url)

        val openInChooser = Intent.createChooser(driveIntent, getString(R.string.share_using))
        openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayListOf(emailIntent))
        startActivity(openInChooser)

Please help

Body:
You were almost there, the only missing piece in the puzzle is the getPackageManager().queryIntentActivities method that will return all activities that can handle your email intent. With the ResolveInfo returned you can build an intent for each email option to be displayed in the chooser. Then you can pass the array of those intents as Intent.EXTRA_INITIAL_INTENTS. You could even exclude certain packages if you like here. So the final part of your code would look something like this:

        val openInChooser = Intent.createChooser(driveIntent, getString(R.string.share_using))

        val emailOptionIntents = mutableListOf<Intent>()
        val resInfo = getPackageManager().queryIntentActivities(emailIntent, 0)
        if (!resInfo.isEmpty()) {
            for (resolveInfo in resInfo) {
                val emailOptionIntent = Intent(Intent.ACTION_SENDTO)
                emailOptionIntent.data = Uri.parse("mailto:")

                emailOptionIntent.putExtra(Intent.EXTRA_STREAM, photoURI)
                emailOptionIntent.putExtra(Intent.EXTRA_EMAIL, "asd@dsa.dsa")
                emailOptionIntent.putExtra(Intent.EXTRA_SUBJECT, "dsadsada")
                emailOptionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

                emailOptionIntent.`package` = resolveInfo.activityInfo.packageName
                emailOptionIntents.add(emailOptionIntent)
            }
        }

        openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailOptionIntents.toTypedArray())
        startActivity(openInChooser)


问:
jquery ui draggable stop function on clone
i have 2 lists, one draggable(#object) and one sortable(#target).
i would like to drag a clone to the sortable list and then do some things to the clone once it is in the sortable list.

i've got something up on jsfiddle: http://jsfiddle.net/d8nieldonaldson/smYeh/3/

here's some of the code:

```<code>$("#object li").draggable({
    connectToSortable: "#target",
    opacity: 0.5,
    helper: "clone",
    revert: "invalid",
    stop: function(e , ui) {
        ui.helper.css("width" , "140px");
    }
});
</code>```

any help would be greatly appreciated.

thanks!

答:
You are resizing the li element and not the img!

Anyway, even doing so will resize the helper (using stop) but when inserted the element to the list it'll return to the original, so I've modified the code and added animate to a better user experience ;-) :

```<code>(function($) {

    $("#target").sortable({
        revert: true,
        update: function(e, ui) {
            if (ui.item.hasClass('ui-draggable')) ui.item.find('img').animate({
                width: "140px"
            })
        }
    });
    $("#object li").draggable({
        connectToSortable: "#target",
        opacity: 0.5,
        helper: "clone",
        revert: "invalid"
    });
    $("ul, li").disableSelection();
})(window.jQuery);
</code>```

Example link.

Body:
i have 2 lists, one draggable(#object) and one sortable(#target).
i would like to drag a clone to the sortable list and then do some things to the clone once it is in the sortable list.

i've got something up on jsfiddle: http://jsfiddle.net/d8nieldonaldson/smYeh/3/

here's some of the code:

$("#object li").draggable({
    connectToSortable: "#target",
    opacity: 0.5,
    helper: "clone",
    revert: "invalid",
    stop: function(e , ui) {
        ui.helper.css("width" , "140px");
    }
});

any help would be greatly appreciated.

thanks!

Body:
You are resizing the li element and not the img!

Anyway, even doing so will resize the helper (using stop) but when inserted the element to the list it'll return to the original, so I've modified the code and added animate to a better user experience ;-) :

(function($) {

    $("#target").sortable({
        revert: true,
        update: function(e, ui) {
            if (ui.item.hasClass('ui-draggable')) ui.item.find('img').animate({
                width: "140px"
            })
        }
    });
    $("#object li").draggable({
        connectToSortable: "#target",
        opacity: 0.5,
        helper: "clone",
        revert: "invalid"
    });
    $("ul, li").disableSelection();
})(window.jQuery);

Example link.


答: C++ doesn't allow copy-initialisation of a  shared_ptr from a raw pointer because shared_ptr would be too easy to end up with an accidental implicit conversion from some arbitrary raw pointer into a shared_ptr that doesn't actually manage it.

Title: why we cannot use "=" to shared_ptr or unique_ptr?


问:
Update the multiple value and display using AngularJS and laravel
```<code>[{"user_id":78936,"social_id":null,"type":2,"name":"Get Raj","first_name":"Get","last_name":"Raj","email":"test1@yopmail.com"},

{"user_id":78937,"social_id":null,"type":2,"name":"James thomas","first_name":"James","last_name":"thomas","email":"jamesthoms@yopmail.com"}]

<div ng-repeat="user in profiles">
    <div class="col-sm-5 col-ie-5">
    <input
      type="text"
      name="entry_{{user.user_id}}"
      ng-model="update.entry"
      ng-change="save(user, update)"
      >
    </div>

    <div class="col-sm-5 col-ie-5">
    <input
      type="text"
      name="info_{{user.user_id}}"
      ng-model="update.info"
      ng-change="save(user, update)"
      >
    </div>

    <div class="col-sm-5 col-ie-5">
    <input
      type="text"
      name="textual_{{user.user_id}}"
      ng-model="update.textual"
      ng-change="save(user, update)"
      >
    </div>
</div>

function makeOrderItemUrl(user_id, order_id){
       return 'v1/update/' + user_id + '/order_id/' + order_id;
    }

$scope.save = function (person, update) {

     var person = person;
     var order = null,
     matchCount = 0;

        for (var i = 0; i < $scope.order.items.length; i++) {
                if ($scope.order.items[i].user_id == person.user_id) {
                  order = $scope.order.items[i];
                  matchCount++;
                }
              }

      if(order){
          $http.post(makeOrderItemUrl(person.user_id, order.order_id), update)
          .success(function(res){
            $scope.update = res.data;
          }).error(function () {
            notify.message('There was an issue saving your changes, please try again later.');
          });
      }

    };
</code>```

Since we have two users so we will get twice input fields i.e ng-model="update.entry" two times then whenever I type in the first textbox it get reflected the same value in the second textbox as well because of the same model they are using how can I set different models and value to be saved into the database and display respectively.

```<code>Laravel

$orderItem =  OrderItem::firstOrNew([
                    'user_id' => $user_id,
                    'order_id' => $order_id
                    ]);

if($orderItem->exists){
            $orderItem->entry = Input::get('entry');
            $orderItem->save();
        }
</code>```

//This is working fine but it's hard to display.

答:
Make update a deeper object where the user id's are used as first level keys

```<code><input
      type="text"
      name="entry_{{user.user_id}}"
      ng-model="update[user.user_id].entry"
      ng-change="save(user, update[user.user_id])"
      >
</code>```

Then $scope.update would look like:

```<code>{
  id1: {
    textual: '...',
    entry: '...',
    info: '...'
  },
  id2: {
    textual: '...',
    entry: '...',
    info: '...'
  }
}
</code>```

Body:
[{"user_id":78936,"social_id":null,"type":2,"name":"Get Raj","first_name":"Get","last_name":"Raj","email":"test1@yopmail.com"},

{"user_id":78937,"social_id":null,"type":2,"name":"James thomas","first_name":"James","last_name":"thomas","email":"jamesthoms@yopmail.com"}]

    <input
      type="text"
      name="entry_{{user.user_id}}"
      ng-model="update.entry"
      ng-change="save(user, update)"
      >

    <input
      type="text"
      name="info_{{user.user_id}}"
      ng-model="update.info"
      ng-change="save(user, update)"
      >

    <input
      type="text"
      name="textual_{{user.user_id}}"
      ng-model="update.textual"
      ng-change="save(user, update)"
      >

function makeOrderItemUrl(user_id, order_id){
       return 'v1/update/' + user_id + '/order_id/' + order_id;
    }

$scope.save = function (person, update) {

     var person = person;
     var order = null,
     matchCount = 0;

        for (var i = 0; i < $scope.order.items.length; i++) {
                if ($scope.order.items[i].user_id == person.user_id) {
                  order = $scope.order.items[i];
                  matchCount++;
                }
              }

      if(order){
          $http.post(makeOrderItemUrl(person.user_id, order.order_id), update)
          .success(function(res){
            $scope.update = res.data;
          }).error(function () {
            notify.message('There was an issue saving your changes, please try again later.');
          });
      }

    };

Since we have two users so we will get twice input fields i.e ng-model="update.entry" two times then whenever I type in the first textbox it get reflected the same value in the second textbox as well because of the same model they are using how can I set different models and value to be saved into the database and display respectively.

Laravel

$orderItem =  OrderItem::firstOrNew([
                    'user_id' => $user_id,
                    'order_id' => $order_id
                    ]);

if($orderItem->exists){
            $orderItem->entry = Input::get('entry');
            $orderItem->save();
        }

//This is working fine but it's hard to display.

Body:
Make update a deeper object where the user id's are used as first level keys

<input
      type="text"
      name="entry_{{user.user_id}}"
      ng-model="update[user.user_id].entry"
      ng-change="save(user, update[user.user_id])"
      >

Then $scope.update would look like:

{
  id1: {
    textual: '...',
    entry: '...',
    info: '...'
  },
  id2: {
    textual: '...',
    entry: '...',
    info: '...'
  }
}


问:
Angular injector error on component downgrading from v5 or v4 to angularJS
I've created simple angular5 component HelloComponent:

```<code>var HelloComponent = function () {
};

HelloComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-world',
    template: 'Hello World!'
  })
];
</code>```

Next I tried to use this component in my angularJS directive like:

```<code>angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))
</code>```

But on running this script I getting this error:

Error: [$injector:unpr] Unknown provider: $$angularLazyModuleRefProvider <- $$angularLazyModuleRef
  http://errors.angularjs.org/1.6.5/$injector/unpr?p0=%24%24angularLazyModuleRefProvider%20%3C-%20%24%24angularLazyModuleRef

See simple example with angular 5 and angularJS: http://plnkr.co/edit/dQJ2tgV2MuInT41ucjq1

How to fix this ?

ADDITIONAL INFO

Example for downgrading component from v4 to v1 also exists: https://hackernoon.com/angular-v4-hybrid-upgrade-application-73d5afba1e01

But when I trying to remake my app with this post, im getting another error:

Unknown provider: $$angularInjectorProvider

See example for v4: http://plnkr.co/edit/9Oxy0QeSg1FYve0cjGYw

Same example for v5 returns old error:

Unknown provider: $$angularLazyModuleRefProvider

See example for v5: http://plnkr.co/edit/eZScm8U41mGuuHJMjApV

答:
You need to set dependency to $$UpgradeModule in your app module

Change

```<code>angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))
</code>```

To

```<code>var app=angular.module("app", ['$$UpgradeModule']).directive("helloWorld", ng.upgrade.static.downgradeComponent({component:HelloComponent}));
</code>```

Working plunker

Body:
I've created simple angular5 component HelloComponent:

var HelloComponent = function () {
};

HelloComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-world',
    template: 'Hello World!'
  })
];

Next I tried to use this component in my angularJS directive like:

angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))

But on running this script I getting this error:

Error: [$injector:unpr] Unknown provider: $$angularLazyModuleRefProvider <- $$angularLazyModuleRef
  http://errors.angularjs.org/1.6.5/$injector/unpr?p0=%24%24angularLazyModuleRefProvider%20%3C-%20%24%24angularLazyModuleRef

See simple example with angular 5 and angularJS: http://plnkr.co/edit/dQJ2tgV2MuInT41ucjq1

How to fix this ?

ADDITIONAL INFO

Example for downgrading component from v4 to v1 also exists: https://hackernoon.com/angular-v4-hybrid-upgrade-application-73d5afba1e01

But when I trying to remake my app with this post, im getting another error:

Unknown provider: $$angularInjectorProvider

See example for v4: http://plnkr.co/edit/9Oxy0QeSg1FYve0cjGYw

Same example for v5 returns old error:

Unknown provider: $$angularLazyModuleRefProvider

See example for v5: http://plnkr.co/edit/eZScm8U41mGuuHJMjApV

Body:
You need to set dependency to $$UpgradeModule in your app module

Change

angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))

To

var app=angular.module("app", ['$$UpgradeModule']).directive("helloWorld", ng.upgrade.static.downgradeComponent({component:HelloComponent}));

Working plunker


问:
Can a PHP class property be equal to another class property?
I want to do this:

```<code>class MyClass {
   var $array1 = array(3,4);
   var $array2 = self::$array1;
}
</code>```

and $array2 doesn't work.

Do you have a solution/trick to make a class property equal to another class property?

答:
I'm new to PHP, but the answer from Paolo seems to be just initializing the values to be the same in the constructor, but that doesn't actually make both variables reference the same content.  How about this:

```<code>class MyClass {
    var $array1 = array(3,4);
    var $array2 = array();

    function MyClass() {
        $this->array2 = &$this->array1;
    }
}

$myclass = new MyClass();
print_r($myclass->array1); // outputs Array ( [0] => 3 [1] => 4 )
print_r($myclass->array2); // outputs Array ( [0] => 3 [1] => 4 )
echo "<br />";
$myclass->array1[0] = 1;
$myclass->array2[1] = 2;
print_r($myclass->array1); // outputs Array ( [0] => 1 [1] => 2 )
print_r($myclass->array2); // outputs Array ( [0] => 1 [1] => 2 )
</code>```

With the addition of the reference, both class property values change when either is changed.  Am I missing something?

OwnerDisplayName: Stemar

LastEditorDisplayName: Stemar

Body:
I want to do this:

class MyClass {
   var $array1 = array(3,4);
   var $array2 = self::$array1;
}

and $array2 doesn't work.

Do you have a solution/trick to make a class property equal to another class property?

Body:
I'm new to PHP, but the answer from Paolo seems to be just initializing the values to be the same in the constructor, but that doesn't actually make both variables reference the same content.  How about this:

class MyClass {
    var $array1 = array(3,4);
    var $array2 = array();

    function MyClass() {
        $this->array2 = &$this->array1;
    }
}

$myclass = new MyClass();
print_r($myclass->array1); // outputs Array ( [0] => 3 [1] => 4 )
print_r($myclass->array2); // outputs Array ( [0] => 3 [1] => 4 )
echo "<br />";
$myclass->array1[0] = 1;
$myclass->array2[1] = 2;
print_r($myclass->array1); // outputs Array ( [0] => 1 [1] => 2 )
print_r($myclass->array2); // outputs Array ( [0] => 1 [1] => 2 )

With the addition of the reference, both class property values change when either is changed.  Am I missing something?

OwnerDisplayName: notruthless


问:
How to make Google Assistant reply
I got the Google Assistant running on a Raspberry. Everything is working fine but there is one thing that I cannot figure out.

I know that ifttt.com has the ability to make the Google Assistant reply with spoken language using text that you can predefine.

How can I do that using Python? I cannot find anything about that subject on the      Google Assistant SDK page. How can I make the Google Assistant talk back? Is there documentation about this subject?

Example:

If I tell the Assistant:

"Light's out."

I want it to reply:

"Yes sir, the lights are out."

答: By hosting your backend fulfillment from your Raspberry Pi you can build an action in Google Assistant which can control both your GPIO pins and can send out custom replies as you wanted above. I used flask and ngrok to host from my Raspberry Pi and create a webhook. </p>

Title: How to make Google Assistant reply


问:
Change Transparent Shader to Color Black (Unity)
What I'm trying to do here is that i want to make this hair  to be black . I changed the Color tint on the inspector but still did not work.

Here is my code so far for my hair shader:

```<code>Shader "Custom/Paul/Hair" {
Properties {
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
_Color ("Color Tint", Color) = (1,1,1,1)
}

SubShader {
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    LOD 100

    ZWrite off
    Lighting Off
    Blend SrcAlpha OneMinusSrcAlpha
    Cull back

    Pass {
        CGPROGRAM

             #pragma vertex vert
             #pragma fragment frag
             #pragma multi_compile_fog

             #include "UnityCG.cginc"

             struct appdata_t {
                 float4 vertex : POSITION;
                 float2 texcoord : TEXCOORD0;
             };

             struct v2f {
                 float4 vertex : SV_POSITION;
                 half2 texcoord : TEXCOORD0;
                 UNITY_FOG_COORDS(1)
                 half4 color: COLOR;
             };

             sampler2D _MainTex;
             float4 _MainTex_ST;

             v2f vert (appdata_t v)
             {
                 v2f o;
                 o.vertex = UnityObjectToClipPos(v.vertex);
                 o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                 UNITY_TRANSFER_FOG(o,o.vertex);
                 return o;
             }

             fixed4 frag (v2f i) : SV_Target
             {
                 fixed4 col = tex2D(_MainTex, i.texcoord);
                 //fixed4 col = tex2D(_MainTex, i.texcoord) * _Color;
                 UNITY_APPLY_FOG(i.fogCoord, col);
                 return col;
             }
        ENDCG
    }
  }
}
</code>```

I tried changing the color tint color in the properties but it doesn't change the color of the hair. Is there a way to change the hair color dynamically in the shader properties, even not in the shader properties even just on the code only . Sorry for my bad english.

And one more thing . I don't get any errors.

答:
I ended up doing this instead.

```<code>Shader "Custom/Paul/Hair" {

Properties
{
    _MainTex ("Texture", 2D) = "white" {}
    _Color("Color", Color) = (1,1,1,1)
}
SubShader
{
    Tags{ "Queue" = "AlphaTest" "RenderType" = "TransparentCutout" "IgnoreProjector" = "True" }
    LOD 100

    Blend SrcAlpha OneMinusSrcAlpha
    ZWrite off
    Lighting Off
    Cull back

    Pass
    {
        CGPROGRAM

        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float4 vertex : SV_POSITION;
            half2 uv : TEXCOORD0;
        };

        float4 _MainTex_ST;
        sampler2D _MainTex;
        fixed4 _Color;

        v2f vert (appdata v)
        {
            v2f o = (v2f)0;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.uv = TRANSFORM_TEX(v.uv, _MainTex);
            o.uv = v.uv;
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            fixed4 col = tex2D(_MainTex, i.uv) * _Color;
            return col;
        }
        ENDCG
    }
}
</code>```

This might help to other people who faces the same problem as mine.

Body:
What I'm trying to do here is that i want to make this hair  to be black . I changed the Color tint on the inspector but still did not work.

Here is my code so far for my hair shader:

Shader "Custom/Paul/Hair" {
Properties {
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
_Color ("Color Tint", Color) = (1,1,1,1)
}

SubShader {
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    LOD 100

    ZWrite off
    Lighting Off
    Blend SrcAlpha OneMinusSrcAlpha
    Cull back

    Pass {
        CGPROGRAM

             #pragma vertex vert
             #pragma fragment frag
             #pragma multi_compile_fog

             #include "UnityCG.cginc"

             struct appdata_t {
                 float4 vertex : POSITION;
                 float2 texcoord : TEXCOORD0;
             };

             struct v2f {
                 float4 vertex : SV_POSITION;
                 half2 texcoord : TEXCOORD0;
                 UNITY_FOG_COORDS(1)
                 half4 color: COLOR;
             };

             sampler2D _MainTex;
             float4 _MainTex_ST;

             v2f vert (appdata_t v)
             {
                 v2f o;
                 o.vertex = UnityObjectToClipPos(v.vertex);
                 o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                 UNITY_TRANSFER_FOG(o,o.vertex);
                 return o;
             }

             fixed4 frag (v2f i) : SV_Target
             {
                 fixed4 col = tex2D(_MainTex, i.texcoord);
                 //fixed4 col = tex2D(_MainTex, i.texcoord) * _Color;
                 UNITY_APPLY_FOG(i.fogCoord, col);
                 return col;
             }
        ENDCG
    }
  }
}

I tried changing the color tint color in the properties but it doesn't change the color of the hair. Is there a way to change the hair color dynamically in the shader properties, even not in the shader properties even just on the code only . Sorry for my bad english.

And one more thing . I don't get any errors.

Body:
I ended up doing this instead.

Shader "Custom/Paul/Hair" {

Properties
{
    _MainTex ("Texture", 2D) = "white" {}
    _Color("Color", Color) = (1,1,1,1)
}
SubShader
{
    Tags{ "Queue" = "AlphaTest" "RenderType" = "TransparentCutout" "IgnoreProjector" = "True" }
    LOD 100

    Blend SrcAlpha OneMinusSrcAlpha
    ZWrite off
    Lighting Off
    Cull back

    Pass
    {
        CGPROGRAM

        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float4 vertex : SV_POSITION;
            half2 uv : TEXCOORD0;
        };

        float4 _MainTex_ST;
        sampler2D _MainTex;
        fixed4 _Color;

        v2f vert (appdata v)
        {
            v2f o = (v2f)0;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.uv = TRANSFORM_TEX(v.uv, _MainTex);
            o.uv = v.uv;
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            fixed4 col = tex2D(_MainTex, i.uv) * _Color;
            return col;
        }
        ENDCG
    }
}

This might help to other people who faces the same problem as mine.


问:
Android application: FB login re authentication issue
We have developed application which supports Facebook login. Our application is already there on playstore.

For some reason, our Facebook developer account is blocked. So we have created new Facebook developer account and created new application in it.

Using this new Facebook application ID, we have rebuild our Android application n roll out it in Beta.

After application UPGRADE from old to updated one, Its working fine on devices which does not have Facebook native application. Users are able to do Facebook login using updated application.

But its giving issue Invalid key hash...... to users who have Facebook native application installed on their phones.

Facebook developer blog says The Android and iOS SDKs don't currently
  support re-authentication.

So any idea, how can I logout from Facebook problematically and application asks for re entering user name and password

答:
Have you update the Release Hash Key on the developer.facebook.com

your FB developer account may be block as it username doesn't matches with the real person name. It the policy of FB to disable FB account whos anme doesn't seen to be real name.

For the Invalid Key hash problem, upate your Release Hash Key on developer account your problem will be save.

Used this command in CMD to find the Release Hash Key.

```<code>keytool -exportcert -alias "Release_alias_name" -keystore "Release_Key_Store" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64
</code>```

Body:
Have you update the Release Hash Key on the developer.facebook.com

your FB developer account may be block as it username doesn't matches with the real person name. It the policy of FB to disable FB account whos anme doesn't seen to be real name.

For the Invalid Key hash problem, upate your Release Hash Key on developer account your problem will be save.

Used this command in CMD to find the Release Hash Key.

keytool -exportcert -alias "Release_alias_name" -keystore "Release_Key_Store" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64


问:
Recursive HTML Divs in handlerbars.js templates
I'm trying to figure out how to create recursive units strictly out of divs.

The root template would be (1). The (2) diagram is the expansion of the red rectangle in (1).

How would it be possible to accomplish this using html/css and no bootstrap? Thanks.

答:
Here you go. </p>

```<code><div>
    <div id="first" class="main">
        <div class="box small"></div>
        <div class="box small"></div>
        <div class="clear"></div>
        <div class="box large"></div>
    </div>

    <div id="second" class="main">
        <div class="box large"></div>
        <div class="clear"></div>
        <div class="box small"></div>
        <div class="box small"></div>
    </div>
</div>
<style>
.main{height: auto; margin-bottom:40px;}
#first{border:1px solid #000; }
#second{border:1px solid red;}
.clear{clear:both;}
.box{margin: 10px; min-height: 50px;}
.small{width:48%; float:left; border:1px solid #000;}
.large{width:98%; border:1px solid red;}
</style>
</code>```

Body:
Here you go.

<div>
    <div id="first" class="main">
        <div class="box small"></div>
        <div class="box small"></div>
        <div class="clear"></div>
        <div class="box large"></div>
    </div>

    <div id="second" class="main">
        <div class="box large"></div>
        <div class="clear"></div>
        <div class="box small"></div>
        <div class="box small"></div>
    </div>
</div>
<style>
.main{height: auto; margin-bottom:40px;}
#first{border:1px solid #000; }
#second{border:1px solid red;}
.clear{clear:both;}
.box{margin: 10px; min-height: 50px;}
.small{width:48%; float:left; border:1px solid #000;}
.large{width:98%; border:1px solid red;}
</style>


问:
What's the "average" requests per second for a production web application?
I have no frame of reference in terms of what's considered "fast"; I'd always wondered this but have never found a straight answer...</p>

答:
Not sure anyone is still interested, but this information was posted about Twitter (and here too):

The Stats

Over 350,000 users. The actual numbers are as always, very super super top secret.

600 requests per second.

Average 200-300 connections per second. Spiking to 800 connections per second.

MySQL handled 2,400 requests per second.

180 Rails instances. Uses Mongrel as the "web" server.

1 MySQL Server (one big 8 core box) and 1 slave. Slave is read only for statistics and reporting.

30+ processes for handling odd jobs.

8 Sun X4100s.

Process a request in 200 milliseconds in Rails.

Average time spent in the database is 50-100 milliseconds.

Over 16 GB of memcached.

OwnerDisplayName: jcapote


问:
Iterate in jquery to get values of input text
I have three rows of which I want to get the values of all the text by looping them all, so I tried something like this.

```<code>var collection = $(".vendorDaterow");
collection.each(function() {});
</code>```

But while debugging i didn't find the value in any of the property.

Below is my html

```<code><tr>
  <td>
    <div class="row noPadding vendorForm">
      <div class="vendorDaterow">
        <div class="vendorName" id="dvVendorNameData">
          <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName" /></span>
        </div>
        <div class="vendorFromDate">
          <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
        <div class="vendorToDate">
          <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
      </div>
      <div class="add">
        <i class="fa fa-plus" aria-hidden="true"></i>
      </div>
      <i class="max"><label>(Maximum 5 Vendors)</label></i>
    </div>
  </td>
</tr>
</code>```

What should I do to get the values of the input text of all the element

答:
This is walking down the tree method. You can make it shorter but it is self-explanetory.

```<code>var collection = $(".vendorDaterow");

collection[0].childNodes.forEach((element)=>{
  if (element.tagName == 'DIV'){
     //console.log(element.childNodes)
     element.childNodes.forEach((element) => {
       if(element.tagName == 'SPAN') {
          //console.log(element.childNodes);
          element.childNodes.forEach((element) => {
            if(element.tagName == 'INPUT'){
              console.log(element.value)
            }
          })
       }
     });
  }
})
</code>```

It iterates and finds the proper elements, assuming that the structure will remain the same. You can remove comment tags to get the flow.

Attempt no2.

```<code>function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        // This is our input so we do something with it
        if($currentElement[0].tagName == 'INPUT') {
           console.log(" the values are: " + $currentElement[0].value)
        }
        //////////// Loop her children
        recursiveEach($currentElement);
    });
}

//////////// Parent div
recursiveEach($(".vendorDaterow"));
</code>```

The syntax is more bit jquery-esk, but it has nice recursive form of iteration.

Body:
I have three rows of which I want to get the values of all the text by looping them all, so I tried something like this.

var collection = $(".vendorDaterow");
collection.each(function() {});

But while debugging i didn't find the value in any of the property.

Below is my html

          SP Vender Name<input type="text" name="nmVendorData" id="txtVendorName" />

          From Date<input type="text" name="spFromDate" id="spFromDate" class="dateClass" />

          To Date<input type="text" name="spToDate" id="spToDate" class="dateClass1" />

      (Maximum 5 Vendors)

What should I do to get the values of the input text of all the element

Body:
This is walking down the tree method. You can make it shorter but it is self-explanetory.

var collection = $(".vendorDaterow");

collection[0].childNodes.forEach((element)=>{
  if (element.tagName == 'DIV'){
     //console.log(element.childNodes)
     element.childNodes.forEach((element) => {
       if(element.tagName == 'SPAN') {
          //console.log(element.childNodes);
          element.childNodes.forEach((element) => {
            if(element.tagName == 'INPUT'){
              console.log(element.value)
            }
          })
       }
     });
  }
})

It iterates and finds the proper elements, assuming that the structure will remain the same. You can remove comment tags to get the flow.

Attempt no2.

function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        // This is our input so we do something with it
        if($currentElement[0].tagName == 'INPUT') {
           console.log(" the values are: " + $currentElement[0].value)
        }
        //////////// Loop her children
        recursiveEach($currentElement);
    });
}

//////////// Parent div
recursiveEach($(".vendorDaterow"));

The syntax is more bit jquery-esk, but it has nice recursive form of iteration.


问:
How to calculate length of string in a tuple in scala
Given a list of tuples, where the 1st element of the tuple is an integer and the second element is a string,

```<code>scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))
</code>```

I want to print the numbers where the corresponding string length is 4.

Can this be done in one line ?

答:
Using a for comprehension as follows,

```<code>for ((i,s) <- tuple2 if s.size == 4) yield i
</code>```

which for the example above delivers

```<code>List(2, 4, 5)
</code>```

Note we pattern match and extract the elements in each tuple and filter by string size. To print a list consider for instance aList.foreach(println).

Body:
Given a list of tuples, where the 1st element of the tuple is an integer and the second element is a string,

scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

I want to print the numbers where the corresponding string length is 4.

Can this be done in one line ?

Body:
Using a for comprehension as follows,

for ((i,s) <- tuple2 if s.size == 4) yield i

which for the example above delivers

List(2, 4, 5)

Note we pattern match and extract the elements in each tuple and filter by string size. To print a list consider for instance aList.foreach(println).


问:
Xcode 9 rebuilding issue?
I updated my Xcode to Xcode 9 and working on swift 4, but my project get build again and again as I minorly change my code. Now I am quite new to swift so i don't know that this is due to swift or Xcode 9 and how to stop this, because it makes working process very slow. any help ?</p>

答:
I also faced such issue in my recent project. Try the following</p>

```<code>1. Main StoryBoard - Editor - Disable "Automatic Refresh Views"
2. Go to Preferences -> General and disable Show Live Issues.
3. Comment any @IBDesignables used in your project
</code>```

Title: Xcode 9 rebuilding issue?

Body:
I also faced such issue in my recent project. Try the following

1. Main StoryBoard - Editor - Disable "Automatic Refresh Views"
2. Go to Preferences -> General and disable Show Live Issues.
3. Comment any @IBDesignables used in your project


问:
Compatible, active, open-source jQuery Gallery
I am looking for a jQuery gallery and want to be sure that this is compatible with all major browsers, well-documented, and preferably evolving as jQuery evolves. So preferably well-established, larger projects. I have found many galleries, but it is difficult to find the ones that comply with this. Many I have seen have not been changed since 2009. So my question is which are the larger, more established jQuery gallery projects?

Thanks!

答: Very recommendable is 'Galleria' IMO. It's well documented, works nicely and the last commit on Github is from January 10th. </p>


问:
Why does Spring get circular dependency issues on one machine and not another?
I have a problem getting a Spring Data based application to run in my environment. I am running Debian, but my co-workers are either using Mac or Ubuntu. I have nothing special set up in my environment variables, and am using the exact same version of Java as others.

I have seen this in the logs, suggesting that it is a circular reference problem that is leading to the instantiation failure:

```<code>nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'flyway.CONFIGURATION_PROPERTIES':
Initialization of bean failed;
...
nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'flyway': Requested bean is currently in
creation: Is there an unresolvable circular reference?
</code>```

So the problem appears to be that flyway needs some dependencies and they need flyway.

The question is, why does this only happen on my environment not anyone elses? Even on the tests using H2 in memory, I see the problem, so its not my database that is at fault.

Is it possible that Spring autowiring is confused somehow, and tries to do things in the wrong order, so that the repository is null when it tries to set it?

Does Spring have a badly implemented topological sort for ordering dependencies?

Why would it misbehave on my environment?

Could ordering of the classpath influence its behaviour?

======================

The application will not start with this error:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contentItemRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Repository interface must not be null on initialization!
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:127)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:251)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1127)
</code>```

============================

The ContentItemRepository signature is:

```<code>@Repository
@Transactional
public interface ContentItemRepository extends JpaRepository<ContentItem, String>, JpaSpecificationExecutor<ContentItem> {
</code>```

============================

This used to work for me, and I was able to identify the commit that broke the build, by iterating through all commits, doing a mvn clean install, and trying to start the server, until I found the delta that broke it.

The 'contentItemRepository' that cannot be null is this one:

```<code>@Component
+public class UrlAliasRequestConverter implements Mapper<UrlAliasRequest, UrlAlias> {
+
+    /**
+     * The content item contentItemType repository.
+     */
+    @Autowired
+    private ContentItemRepository contentItemRepository;
</code>```

答:
I got the same problem yesterday. I don't know why, but I found a way to solve the problem: mark all the beans involved in the circular dependency tree as lazy-init. Not only the ones directly circular dependent to each other, but all the beans that reference them!

The project is an old one thus it only uses spring 3. I am not sure whether the later versions of spring still get this problem.

Body:
I have a problem getting a Spring Data based application to run in my environment. I am running Debian, but my co-workers are either using Mac or Ubuntu. I have nothing special set up in my environment variables, and am using the exact same version of Java as others.

I have seen this in the logs, suggesting that it is a circular reference problem that is leading to the instantiation failure:

nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'flyway.CONFIGURATION_PROPERTIES':
Initialization of bean failed;
...
nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'flyway': Requested bean is currently in
creation: Is there an unresolvable circular reference?

So the problem appears to be that flyway needs some dependencies and they need flyway.

The question is, why does this only happen on my environment not anyone elses? Even on the tests using H2 in memory, I see the problem, so its not my database that is at fault.

Is it possible that Spring autowiring is confused somehow, and tries to do things in the wrong order, so that the repository is null when it tries to set it?

Does Spring have a badly implemented topological sort for ordering dependencies?

Why would it misbehave on my environment?

Could ordering of the classpath influence its behaviour?

======================

The application will not start with this error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contentItemRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Repository interface must not be null on initialization!
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:127)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:251)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1127)

============================

The ContentItemRepository signature is:

@Repository
@Transactional
public interface ContentItemRepository extends JpaRepository<ContentItem, String>, JpaSpecificationExecutor<ContentItem> {

============================

This used to work for me, and I was able to identify the commit that broke the build, by iterating through all commits, doing a mvn clean install, and trying to start the server, until I found the delta that broke it.

The 'contentItemRepository' that cannot be null is this one:

@Component
+public class UrlAliasRequestConverter implements Mapper<UrlAliasRequest, UrlAlias> {
+
+    /**
+     * The content item contentItemType repository.
+     */
+    @Autowired
+    private ContentItemRepository contentItemRepository;