问:
Var declaration in Lazarus
I have encountered a strange behavior on the declaration of variables in lazaus (2.0.6)

If I declare variables using the following sequence, the program stops execution by giving SIGSEGV error, the error pops up, if I assign initial value into second field of TabCellContent var

```<code>TabReadActive: Boolean;
ShCol: Array[0..6] of Boolean;
TabCellContent: Array [0..6] of Array [1..50] of TCellContent;
</code>```

But if I place the "TabReadActive" below the declaration of Array's the program is working normally without error

```<code>ShCol: Array[0..6] of Boolean;
TabCellContent: Array [0..6] of Array [1..50] of TCellContent;
TabReadActive: Boolean;
</code>```

Is there someone who encountered same behavior? And what is the reason for this?

答:
The reason is that the code that access the variables access out of bounds. Accessing arrays out of bounds leads to undefined behaviour. It is just a coincidence that the order in which you declare the variables changes that behaviour. But that's the nature of undefined behaviour. It is, well, undefined.

Enable range checking in your compiler options, and run your program through the debugger. This will identify the point in your code where you access the array out of bounds.

Title: Var declaration in Lazarus

Body:
I have encountered a strange behavior on the declaration of variables in lazaus (2.0.6)

If I declare variables using the following sequence, the program stops execution by giving SIGSEGV error, the error pops up, if I assign initial value into second field of TabCellContent var

TabReadActive: Boolean;
ShCol: Array[0..6] of Boolean;
TabCellContent: Array [0..6] of Array [1..50] of TCellContent;

But if I place the "TabReadActive" below the declaration of Array's the program is working normally without error

ShCol: Array[0..6] of Boolean;
TabCellContent: Array [0..6] of Array [1..50] of TCellContent;
TabReadActive: Boolean;

Is there someone who encountered same behavior? And what is the reason for this?


来源: stackexchange

问:
Split SQL Server Column value
I have a SQL Server table which name is AbundanceImpact.

```<code>Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95
</code>```

So I want the all integer values only with SUM.

答:
You can use charindex() :

```<code>select t.col, substring(t.col, charindex('~', t.col) + 1, len(t.col)) as val
from table t;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Split SQL Server Column value

Body:
I have a SQL Server table which name is AbundanceImpact.

Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95

So I want the all integer values only with SUM.

Body:
You can use charindex() :

select t.col, substring(t.col, charindex('~', t.col) + 1, len(t.col)) as val
from table t;


问:
Karate - Exception raises for invalid jsonpath
I have a Json response like below. The difference here is my Json body has a number as the parent node.

```<code>    def response =
"""
{
  "22388043":[
    {
      "firstName":"Romin",
      "lastName":"Irani",
      "phoneNumber":"408-1234567",
      "emailAddress":"romin.k.irani@gmail.com"
    }
  ]
}
"""
</code>```

I want to return the mobileNumber attribute value from the response body. In this scenario I don't have that attribute in my response. So here I want to get a null value.

So when I use * def mobile = $.22388043[0].mobileNumber, I'm getting below error.

No results for path: $['22388043'][0]['mobileNumber']

Please advise on this.

答:
Karate does give you a way to get the values of JSON keys.

Hopefully this example answers all your other questions as well:

```<code>* def response =
"""
{
  "22388043":[
    {
      "firstName":"Romin",
      "lastName":"Irani",
      "phoneNumber":"408-1234567",
      "emailAddress":"romin.k.irani@gmail.com"
    }
  ]
}
"""
* def id = karate.keysOf(response)[0]
* match id == '22388043'
* def person = response[id][0]
* match person contains { firstName: 'Romin', lastName: 'Irani' }
* match person.mobileNumber == '#notpresent'
</code>```

Body:
I have a Json response like below. The difference here is my Json body has a number as the parent node.

    def response =
"""
{
  "22388043":[
    {
      "firstName":"Romin",
      "lastName":"Irani",
      "phoneNumber":"408-1234567",
      "emailAddress":"romin.k.irani@gmail.com"
    }
  ]
}
"""

I want to return the mobileNumber attribute value from the response body. In this scenario I don't have that attribute in my response. So here I want to get a null value.

So when I use * def mobile = $.22388043[0].mobileNumber, I'm getting below error.

No results for path: $['22388043'][0]['mobileNumber']

Please advise on this.

Body:
Karate does give you a way to get the values of JSON keys.

Hopefully this example answers all your other questions as well:

* def response =
"""
{
  "22388043":[
    {
      "firstName":"Romin",
      "lastName":"Irani",
      "phoneNumber":"408-1234567",
      "emailAddress":"romin.k.irani@gmail.com"
    }
  ]
}
"""
* def id = karate.keysOf(response)[0]
* match id == '22388043'
* def person = response[id][0]
* match person contains { firstName: 'Romin', lastName: 'Irani' }
* match person.mobileNumber == '#notpresent'


问:
What is global anguar CLI and local angular CLI?
When I do ng build --prod --aot, I get something like:

```<code>Your global Angular CLI version (8.3.19) is greater than your local version (8.3.2). The local Angular CLI version is used.
</code>```

I resolved the above warning. But, I want to know what is global angular CLI actually is and what is local angular CLI? I've searched it. But, couldn't make myself clear.

答: Your global angular version is that of the version you've installed systemwide with the -g flag. Your local angular version is the one you've installed inside your project folder.

Body:
When I do ng build --prod --aot, I get something like:

Your global Angular CLI version (8.3.19) is greater than your local version (8.3.2). The local Angular CLI version is used.

I resolved the above warning. But, I want to know what is global angular CLI actually is and what is local angular CLI? I've searched it. But, couldn't make myself clear.


问:
How to set rolling window size by size of each group?
I have a data frame like below:

```<code>>df

ID    Value
---------------
1       1.0
1       2.0
1       3.0
1       4.0
2       6.0
2       7.0
2       8.0
3       2.0
</code>```

I want to calculate min/max/sum/mean/var on 'value' field of last int(group size /2) records of each group instead of fix number of records.

For ID =1, apply min/max/sum/mean/var on 'value' field of last 4/2=2 records

For ID =2, apply min/max/sum/mean/var on 'value' field of last 3/2=1 records.

For ID =3, apply min/max/sum/mean/var on 'value' field of last 1 records since it only have one records in the group.

so the output should be

```<code>             Value
ID    min   max  sum  mean  var
----------------------------------
1     3.0   4.0  7.0  3.5    0.5 # the last 4/2 rows for group with ID =1
2     7.0   7.0  7.0  7.0    0.5 # the last 3/2 rows for group with ID =2
3     2.0   2.0  2.0  2.0    Nan # the last 1 rows for group with ID =3
</code>```

I am thinking to use the rolling function like below:

```<code>df_group=df.groupby('ID')
           .apply(lambda x: x \
                           .sort_values(by=['ID'])
                           .rolling(window=int(x.size/2),min_periods=1)
                           .agg({'Value':['min','max','sum','mean','var']})
                           .tail(1)
                  )
</code>```

but the result turns out to be as below

```<code>                Value
        min max sum    mean  var
ID
------------------------------------------------
1   3   1.0 4.0 10.0    2.5 1.666667
2   6   6.0 8.0 21.0    7.0 1.000000
3   7   2.0 2.0 2.0     2.0 NaN
</code>```

it seems the x.size does not work at all.

Is there any way to set the rolling size based on group size?

答:
A possible solution, with :

```<code>import pandas as pd
df = pd.DataFrame(dict(ID=[1,1,1,1,2,2,2,3],
                      Value=[1,2,3,4,6,7,8,2]))

print(df)
##
   ID  Value
0   1      1
1   1      2
2   1      3
3   1      4
4   2      6
5   2      7
6   2      8
7   3      2
</code>```

Loop over groups as below

```<code>#Object to store the result
stats = []

#Group over ID
for ID, Values in df.groupby('ID'):
    # tail : to get last n values, with n max between 1 and group length / 2
    # describe : to get the statistics
    _stat = Values.tail(max(1,int(len(Values)/2)))['Value'].describe()
    #Add group ID to the result
    _stat.loc['ID'] = ID
    #Store the result
    stats.append(_stat)

#Create the new dataframe
pd.DataFrame(stats).set_index('ID')
</code>```

Result

```<code>     count  mean       std  min   25%  50%   75%  max
ID
1.0    2.0   3.5  0.707107  3.0  3.25  3.5  3.75  4.0
2.0    1.0   8.0       NaN  8.0  8.00  8.0  8.00  8.0
3.0    1.0   2.0       NaN  2.0  2.00  2.0  2.00  2.0
</code>```

Links :

How to loop over grouped Pandas dataframe?

Series Describe

Body:
I have a data frame like below:

>df

ID    Value
---------------
1       1.0
1       2.0
1       3.0
1       4.0
2       6.0
2       7.0
2       8.0
3       2.0

I want to calculate min/max/sum/mean/var on 'value' field of last int(group size /2) records of each group instead of fix number of records.

For ID =1, apply min/max/sum/mean/var on 'value' field of last 4/2=2 records

For ID =2, apply min/max/sum/mean/var on 'value' field of last 3/2=1 records.

For ID =3, apply min/max/sum/mean/var on 'value' field of last 1 records since it only have one records in the group.

so the output should be

             Value
ID    min   max  sum  mean  var
----------------------------------
1     3.0   4.0  7.0  3.5    0.5 # the last 4/2 rows for group with ID =1
2     7.0   7.0  7.0  7.0    0.5 # the last 3/2 rows for group with ID =2
3     2.0   2.0  2.0  2.0    Nan # the last 1 rows for group with ID =3

I am thinking to use the rolling function like below:

df_group=df.groupby('ID')
           .apply(lambda x: x \
                           .sort_values(by=['ID'])
                           .rolling(window=int(x.size/2),min_periods=1)
                           .agg({'Value':['min','max','sum','mean','var']})
                           .tail(1)
                  )

but the result turns out to be as below

                Value
        min max sum    mean  var
ID
------------------------------------------------
1   3   1.0 4.0 10.0    2.5 1.666667
2   6   6.0 8.0 21.0    7.0 1.000000
3   7   2.0 2.0 2.0     2.0 NaN

it seems the x.size does not work at all.

Is there any way to set the rolling size based on group size?

Body:
A possible solution, with :

import pandas as pd
df = pd.DataFrame(dict(ID=[1,1,1,1,2,2,2,3],
                      Value=[1,2,3,4,6,7,8,2]))

print(df)
##
   ID  Value
0   1      1
1   1      2
2   1      3
3   1      4
4   2      6
5   2      7
6   2      8
7   3      2

Loop over groups as below

#Object to store the result
stats = []

#Group over ID
for ID, Values in df.groupby('ID'):
    # tail : to get last n values, with n max between 1 and group length / 2
    # describe : to get the statistics
    _stat = Values.tail(max(1,int(len(Values)/2)))['Value'].describe()
    #Add group ID to the result
    _stat.loc['ID'] = ID
    #Store the result
    stats.append(_stat)

#Create the new dataframe
pd.DataFrame(stats).set_index('ID')

Result

     count  mean       std  min   25%  50%   75%  max
ID
1.0    2.0   3.5  0.707107  3.0  3.25  3.5  3.75  4.0
2.0    1.0   8.0       NaN  8.0  8.00  8.0  8.00  8.0
3.0    1.0   2.0       NaN  2.0  2.00  2.0  2.00  2.0

Links :

How to loop over grouped Pandas dataframe?

Series Describe


问:
UUID.randomUUID() vs SecureRandom
I am trying to understand the advantages of using UUID.randomUUID() over SecureRandom generator as the former uses securerandom internally.</p>

答: Thanks for all the provided technical answers. I, myself, was also baffled by the difference between the two which led me here. But then, a thought dawned on me: If you only call the function once, then there is no difference as both method generates a number that could not be pre-calculated. But if call the function several times, then they differ here because a statistical normal distribution is a property of a random number generator whereas this is not a property of a UUID. UUID strives for uniqueness and in fact it derives the provided number using your computer's MAC hardware address, the current epoch seconds etc. And eventually, if you for-loop call the UUID values it will not be statistically normally distributed.</p>

ContentLicense: CC BY-SA 3.0

Title: UUID.randomUUID() vs SecureRandom


问:
display data from more than one table
I am learning cakephp and doing an example.I have many tables in my database such as User,Post,Comment,Friend,Photo and each table has a foreign key user_id.Now I want to display user's photo,his/her friend's posts, comments on those posts,user's friends etc like any social networking site after successfull login.can any one please suggest me how to do that.

Thanks in advance.

答:
You want to use the Containable Behavior to pull back a nested object graph that will have all of those fields.

http://book.cakephp.org/view/1323/Containable

You'll get back results like this (...pulled from the cakephp book)

```<code>[0] => Array
    (
        [Post] => Array
            (
                [id] => 1
                [title] => First article
                [content] => aaa
                [created] => 2008-05-18 00:00:00
            )
        [Comment] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [post_id] => 1
                        [author] => Daniel
                        [email] => dan@example.com
                        [website] => http://example.com
                        [comment] => First comment
                        [created] => 2008-05-18 00:00:00
                    )
                [1] => Array
                    (
                        [id] => 2
                        [post_id] => 1
                        [author] => Sam
                        [email] => sam@example.net
                        [website] => http://example.net
                        [comment] => Second comment
                        [created] => 2008-05-18 00:00:00
                    )
            )
        [Tag] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [name] => Awesome
                    )
                [1] => Array
                    (
                        [id] => 2
                        [name] => Baking
                    )
            )
    )
</code>```

Title: display data from more than one table

Body:
You want to use the Containable Behavior to pull back a nested object graph that will have all of those fields.

http://book.cakephp.org/view/1323/Containable

You'll get back results like this (...pulled from the cakephp book)

[0] => Array
    (
        [Post] => Array
            (
                [id] => 1
                [title] => First article
                [content] => aaa
                [created] => 2008-05-18 00:00:00
            )
        [Comment] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [post_id] => 1
                        [author] => Daniel
                        [email] => dan@example.com
                        [website] => http://example.com
                        [comment] => First comment
                        [created] => 2008-05-18 00:00:00
                    )
                [1] => Array
                    (
                        [id] => 2
                        [post_id] => 1
                        [author] => Sam
                        [email] => sam@example.net
                        [website] => http://example.net
                        [comment] => Second comment
                        [created] => 2008-05-18 00:00:00
                    )
            )
        [Tag] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [name] => Awesome
                    )
                [1] => Array
                    (
                        [id] => 2
                        [name] => Baking
                    )
            )
    )


问:
Generate all combinations of an unknown number of variables
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

```<code>variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
</code>```

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

```<code>"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.
</code>```

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

```<code>a  b  c
x  y  z
x  y  z
x  y  z
x  y  z
</code>```

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

```<code>[
  (x, y, z)
  (x, y, z)
]
...
</code>```

答:
Try:</p>

```<code>import numpy as np
lst = [np.arange(v[0], v[1]+1, v[2]) for k,v in variables.items()]
np.array(np.meshgrid(*lst)).T.reshape(-1,len(lst))
</code>```

Body:
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

a  b  c
x  y  z
x  y  z
x  y  z
x  y  z

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

[
  (x, y, z)
  (x, y, z)
]
...

Body:
Try:

import numpy as np
lst = [np.arange(v[0], v[1]+1, v[2]) for k,v in variables.items()]
np.array(np.meshgrid(*lst)).T.reshape(-1,len(lst))


问:
Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?
Why do I get this error

Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.

when I try to use sp_executesql?

答: I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.</p>


问:
Reason why deep and shallow copy differences between "primitive" and "non-primitive" objects?
I know the difference between shallow and deep copy in Python, and the question is not about when to use one or the other. However I find this trivial example pretty amusing and non-intuitive

```<code>from copy import deepcopy

 a=0
 b=deepcopy(a)
 c=a
 a+=1
 print(a,b,c)
</code>```

output: 1 0 0

```<code> from copy import deepcopy
 a=[0]
 b=deepcopy(a)
 c=a
 a[0]+=1
 print(a,b,c)
</code>```

output: [1] 0 [1]

I would like to know the reason why this design choice was made, since the two snippets of code are in my opinion quite equivalent however their output is completely different. To make myself more explicit I wonder why = is a deepcopy in the case of a "primitive" variable  and a shallow copy in the case of a "non-primitive" (but still part of the basic language) variable like a list? I personally find this behavior counter-intuitive
Note: I used python 3

答:
c = a is neither a shallow copy nor a deep copy, no matter what a refers to. It's even shallower than that - it only copies a reference. Both c and a hold references to the same object after this assignment.

It is not possible to modify the value of an int in Python. When you use += on an int, Python assigns a (reference to a) new int to wherever you retrieved the original int from.

For the first case, a += 1 reassigns the a variable, while b and c continue to refer to the ints they referred to before the assignment.

For the second case, a[0] += 1 reassigns cell 0 of the list a refers to. b continues to refer to the copy, which is unchanged, and c continues to refer to the same list a refers to. Since this list has changed state, the change is visible through the c variable.

Incidentally, deepcopy is designed to produce a deep copy, in the sense that (arbitrarily deep) modifications to the return value will not modify the argument, and vice versa. Since it is not possible to modify the value of an int in Python, an int counts as a (deep) copy of itself, and indeed, the deepcopy implementation simply returns its argument if its argument is an int.

```<code>>>> x = 1000
>>> copy.deepcopy(x) is x
True
</code>```

Body:
I know the difference between shallow and deep copy in Python, and the question is not about when to use one or the other. However I find this trivial example pretty amusing and non-intuitive

from copy import deepcopy

 a=0
 b=deepcopy(a)
 c=a
 a+=1
 print(a,b,c)

output: 1 0 0

 from copy import deepcopy
 a=[0]
 b=deepcopy(a)
 c=a
 a[0]+=1
 print(a,b,c)

output: [1] 0 [1]

I would like to know the reason why this design choice was made, since the two snippets of code are in my opinion quite equivalent however their output is completely different. To make myself more explicit I wonder why = is a deepcopy in the case of a "primitive" variable  and a shallow copy in the case of a "non-primitive" (but still part of the basic language) variable like a list? I personally find this behavior counter-intuitive
Note: I used python 3

Body:
c = a is neither a shallow copy nor a deep copy, no matter what a refers to. It's even shallower than that - it only copies a reference. Both c and a hold references to the same object after this assignment.

It is not possible to modify the value of an int in Python. When you use += on an int, Python assigns a (reference to a) new int to wherever you retrieved the original int from.

For the first case, a += 1 reassigns the a variable, while b and c continue to refer to the ints they referred to before the assignment.

For the second case, a[0] += 1 reassigns cell 0 of the list a refers to. b continues to refer to the copy, which is unchanged, and c continues to refer to the same list a refers to. Since this list has changed state, the change is visible through the c variable.

Incidentally, deepcopy is designed to produce a deep copy, in the sense that (arbitrarily deep) modifications to the return value will not modify the argument, and vice versa. Since it is not possible to modify the value of an int in Python, an int counts as a (deep) copy of itself, and indeed, the deepcopy implementation simply returns its argument if its argument is an int.

>>> x = 1000
>>> copy.deepcopy(x) is x
True


问:
NativeQuery mapping with @SqlResultSetMapping with multiple @Entity classes, is it possible?
I have a situation where I have a single native query which contains data of 2 entity classes, how can I map that data to the entity classes by @SqlResultSetMapping?
For Example

```<code>Native query:- select customer.name, address.area from customer, address where customer.id=address.custid;
</code>```

2 Entity Classes like customer and address with name as a variable in customer and area as a variable in the address entity class.

```<code>Customer class:
@Entity
public class Customer {
    @Id
    private String name;
    getters and setters
.....
.....
.....
}

Address Class entity:
@Entity
public class Address{
    @Id
    private String area;
    getters and setters
.....
.....
.....
}
</code>```

To map the native query with the entity class it can be done by giving @SqlResultSetMapping in entity and give the name of the mapping in the nativeQuery

```<code>Query query = entityManager.createNativeQuery(sbQuery, "checkInfoMapping");
</code>```

it will check the mapping name and map to the respective entity class, this can be done for a single entity class.

Can it be done if I have data from the native query of 2 entity classes, if yes how can I map it to the entity class with native query?

答:
You should do something like this:

@SqlResultSetMapping(
   name = "checkInfoMapping",
   classes = {
      @ConstructorResult(targetClass = ResultInfo.class,
         columns = {
            @ColumnResult(name = "cust_name", type = String.class),
            @ColumnResult(name = "adr_area", type = String.class)
         }
      )
   }
)
@Entity
@Table(name = "TST_CUSTOMER")
public class Customer {

    @Id
    @Column(name = "cust_id")
    private Long id;

    @Column(name = "cust_name")
    private String name;

    ...
}

@Entity
@Table(name = "TST_ADDRESS")
public class Address{

    @Column(name = "adr_area")
    private String area;

    @ManyToOne
    @JoinColumn(name = "adr_cust_id")
    private Customer customer;
    ...
}

// this is not entity, just dto class
public class ResultInfo
{
   private String name;
   private String area;

   public ResultInfo(String name, String area)
   {
      this.name = name;
      this.area = area;
   }
   // ...
}
```

<p>And the query:</p>

<pre class="lang-java prettyprint-override"><code>List<ResultInfo> resultList = entityManager.createNativeQuery(
   "select cust_name, adr_area from TST_CUSTOMER, TST_ADDRESS where TST_CUSTOMER.cust_id = TST_ADDRESS.adr_cust_id",
   "checkInfoMapping")
   .getResultList();
</code>```

Body:
I have a situation where I have a single native query which contains data of 2 entity classes, how can I map that data to the entity classes by @SqlResultSetMapping?
For Example

Native query:- select customer.name, address.area from customer, address where customer.id=address.custid;

2 Entity Classes like customer and address with name as a variable in customer and area as a variable in the address entity class.

Customer class:
@Entity
public class Customer {
    @Id
    private String name;
    getters and setters
.....
.....
.....
}

Address Class entity:
@Entity
public class Address{
    @Id
    private String area;
    getters and setters
.....
.....
.....
}

To map the native query with the entity class it can be done by giving @SqlResultSetMapping in entity and give the name of the mapping in the nativeQuery

Query query = entityManager.createNativeQuery(sbQuery, "checkInfoMapping");

it will check the mapping name and map to the respective entity class, this can be done for a single entity class.

Can it be done if I have data from the native query of 2 entity classes, if yes how can I map it to the entity class with native query?

Body:
You should do something like this:

@SqlResultSetMapping(
   name = "checkInfoMapping",
   classes = {
      @ConstructorResult(targetClass = ResultInfo.class,
         columns = {
            @ColumnResult(name = "cust_name", type = String.class),
            @ColumnResult(name = "adr_area", type = String.class)
         }
      )
   }
)
@Entity
@Table(name = "TST_CUSTOMER")
public class Customer {

    @Id
    @Column(name = "cust_id")
    private Long id;

    @Column(name = "cust_name")
    private String name;

    ...
}

@Entity
@Table(name = "TST_ADDRESS")
public class Address{

    @Column(name = "adr_area")
    private String area;

    @ManyToOne
    @JoinColumn(name = "adr_cust_id")
    private Customer customer;
    ...
}

// this is not entity, just dto class
public class ResultInfo
{
   private String name;
   private String area;

   public ResultInfo(String name, String area)
   {
      this.name = name;
      this.area = area;
   }
   // ...
}

And the query:

List<ResultInfo> resultList = entityManager.createNativeQuery(
   "select cust_name, adr_area from TST_CUSTOMER, TST_ADDRESS where TST_CUSTOMER.cust_id = TST_ADDRESS.adr_cust_id",
   "checkInfoMapping")
   .getResultList();


问:
Java "Formatter" vs. "FileOutputStream": Very simple explanation desired of when to use which
I am learning the basics of Java IO and cannot find what I would think would be covered in basic discussions of IO in java: without getting into subtleties or complexities (unless necessary), what is the very basic explanation of when you would choose one vs. when you would choose the other for output to a file (Formatter vs. FileOutputStream)?

I assume the same explanation will hold for Scanner vs. FileInputStream.

答: The Formatter and Scanner constructors that take file specifications as arguments are just a convenience for combining a file output or input stream with a Formatter or Scanner that operates on a stream. Use them whenever you were going to wrap your stream in a Formatter or Scanner anyway and you have no separate need for the stream object.</p>


问:
Updating pandas dataframe with new column
I want to create a new column with all the distinct values across the rows. Each value in a row is a string(not list).

This is how dataframe looks like:

```<code>+-----------------------------+-------------------------+---------------------------------------------+
|         first               |            second       |           third                             |
+-----------------------------+-------------------------+---------------------------------------------+
|['able', 'shovel', 'door']   |['shovel raised']        |['shovel raised', 'raised', 'door', 'shovel']|
|['grade control']            |['grade']                |['grade']                                    |
|['light telling', 'love']    |['would love', 'closed'] |['closed', 'light']                          |
+-----------------------------+-------------------------+---------------------------------------------+
</code>```

This is how the dataframe should look like after creating a new column with distinct values.

df = pd.DataFrame({'first': "['able', 'shovel', 'door']" , 'second': "['shovel raised']", 'third': "['shovel raised', 'raised', 'door', 'shovel']", "Distinct_set": "['able', 'shovel', 'door', 'shovel raised', 'raised']" }, index = [0])```

How can I do it?

答:
How about this:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame([[['able', 'shovel', 'door'], ['shovel raised'], ['shovel raised', 'raised', 'door', 'shovel']], [['grade control'], ['grade'], ['grade']], [['light telling', 'love'], ['would love', 'closed'], ['closed', 'light']]], columns=['first', 'second', 'third'])

df.apply(lambda row: [np.unique(np.hstack(row))], raw=True, axis=1)
</code>```

The last command produces:

```<code>0        [[able, door, raised, shovel, shovel raised]]
1                             [[grade, grade control]]
2    [[closed, light, light telling, love, would lo...
</code>```

which can be saved in a new column of the dataframe:

```<code>df['Distinct_set'] = df.apply(lambda row: [np.unique(np.hstack(row))], raw=True, axis=1)
</code>```

Body:
I want to create a new column with all the distinct values across the rows. Each value in a row is a string(not list).

This is how dataframe looks like:

+-----------------------------+-------------------------+---------------------------------------------+
|         first               |            second       |           third                             |
+-----------------------------+-------------------------+---------------------------------------------+
|['able', 'shovel', 'door']   |['shovel raised']        |['shovel raised', 'raised', 'door', 'shovel']|
|['grade control']            |['grade']                |['grade']                                    |
|['light telling', 'love']    |['would love', 'closed'] |['closed', 'light']                          |
+-----------------------------+-------------------------+---------------------------------------------+

This is how the dataframe should look like after creating a new column with distinct values.

df = pd.DataFrame({'first': "['able', 'shovel', 'door']" , 'second': "['shovel raised']", 'third': "['shovel raised', 'raised', 'door', 'shovel']", "Distinct_set": "['able', 'shovel', 'door', 'shovel raised', 'raised']" }, index = [0])

How can I do it?

Body:
How about this:

import pandas as pd
import numpy as np

df = pd.DataFrame([[['able', 'shovel', 'door'], ['shovel raised'], ['shovel raised', 'raised', 'door', 'shovel']], [['grade control'], ['grade'], ['grade']], [['light telling', 'love'], ['would love', 'closed'], ['closed', 'light']]], columns=['first', 'second', 'third'])

df.apply(lambda row: [np.unique(np.hstack(row))], raw=True, axis=1)

The last command produces:

0        [[able, door, raised, shovel, shovel raised]]
1                             [[grade, grade control]]
2    [[closed, light, light telling, love, would lo...

which can be saved in a new column of the dataframe:

df['Distinct_set'] = df.apply(lambda row: [np.unique(np.hstack(row))], raw=True, axis=1)


问:
Angular PatchValue of nested arrays
I Want to patch a value of an array inside another array, I can achieve it by using

this.myForm.value.array1[index1].array2[index2].type = type;

although it doesn't update the forms value on the screen only in the form values in code, I the code below to patch values in the first array and it updates the values on the screen i just cant write it to be able to reach the second array

(<FormArray>this.myForm.controls['array1']).at(index1).get("type").patchValue(type);

thanks :)

答:
If you not use setValue, Angular change the value but Angular not reflect in the input, don't mark the input as touched...

So

```<code>((this.myForm.get('array1') as FormArray)
       .at(index1).get('array2') as FormArray)
       .at(index2).get("type").patchValue(type);
</code>```

or

```<code>this.form.get('array1.'+index1+'.array2.'+index2+'.type').patchValue(type)
</code>```

NOTE1: using get to access at element of an array is the way array1.index, so array1.0 get the first element of the array, array1.1 the second one...

NOTE2: is recomended use the method get(name) vs controls[name]

Update I don't know yours requeriments, but If you want simple control an array of arrays of an object you can use a FormArray of FormArrays of FormGroup.

Well, some like

```<code>formArray=new FormArray([
      new FormArray([
        new FormGroup({
           type:new FormControl('uno')
        }),
        new FormGroup({
           type:new FormControl('dos')
        }),
      ]),
      new FormArray([
        new FormGroup({
           type:new FormControl('tres')
        }),
        new FormGroup({
           type:new FormControl('cuatro')
        }),
      ])
    ])
</code>```

Can be mannage in an html as

```<code><div *ngFor="let array of formArray.controls">
  <div *ngFor="let group of array.controls" [formGroup]="group">
    <input formControlName="type">
  </div>
</div>
</code>```

In this case use

```<code>(this.form.at(0) as FormArray).at(1).get('type').patchValue('new');
</code>```

see stackblitz

Title: Angular PatchValue of nested arrays

Body:
If you not use setValue, Angular change the value but Angular not reflect in the input, don't mark the input as touched...

So

((this.myForm.get('array1') as FormArray)
       .at(index1).get('array2') as FormArray)
       .at(index2).get("type").patchValue(type);

or

this.form.get('array1.'+index1+'.array2.'+index2+'.type').patchValue(type)

NOTE1: using get to access at element of an array is the way array1.index, so array1.0 get the first element of the array, array1.1 the second one...

NOTE2: is recomended use the method get(name) vs controls[name]

Update I don't know yours requeriments, but If you want simple control an array of arrays of an object you can use a FormArray of FormArrays of FormGroup.

Well, some like

formArray=new FormArray([
      new FormArray([
        new FormGroup({
           type:new FormControl('uno')
        }),
        new FormGroup({
           type:new FormControl('dos')
        }),
      ]),
      new FormArray([
        new FormGroup({
           type:new FormControl('tres')
        }),
        new FormGroup({
           type:new FormControl('cuatro')
        }),
      ])
    ])

Can be mannage in an html as

<div *ngFor="let array of formArray.controls">
  <div *ngFor="let group of array.controls" [formGroup]="group">
    <input formControlName="type">
  </div>
</div>

In this case use

(this.form.at(0) as FormArray).at(1).get('type').patchValue('new');

see stackblitz


问:
How to drop privileges in bash script between pipes?

dbus-monitor --system --profile interface=org.freedesktop.login1.Session,type=signal,member={Lock,Unlock} |
  egrep --line-buffered -o 'Lock|Unlock' |
  while read SIGNAL; do
    case "${SIGNAL}" in
      Lock)
        for i in "$(systemd-path user-shared)/watchlock/lock.d/"*; do
          "${i}"
        done
        ;;
      Unlock)
        for i in "$(systemd-path user-shared)/watchlock/unlock.d/"*; do
          "${i}"
        done
        ;;
    esac
  done
```

I've made this script and I want to execute it as a regular user but dbus-monitor only works as root. Is there a way to execute dbus-monitor as root and the rest of the pipes as a regular user? Adding sudo before dbus-monitor is not an option as it is just a workaround, I could intend to execute the script as root and it would escalate privileges once again for no reason. I would also want to make use of polkit, pkexec for example. Thanks!

答:
Just like this:

```<code>cmd_a | sudo -u "${USER}" cmd_b
</code>```

If the script is started as root, cmd_a will run as root and cmd_b will run as $USER.

Body:
dbus-monitor --system --profile interface=org.freedesktop.login1.Session,type=signal,member={Lock,Unlock} |
  egrep --line-buffered -o 'Lock|Unlock' |
  while read SIGNAL; do
    case "${SIGNAL}" in
      Lock)
        for i in "$(systemd-path user-shared)/watchlock/lock.d/"*; do
          "${i}"
        done
        ;;
      Unlock)
        for i in "$(systemd-path user-shared)/watchlock/unlock.d/"*; do
          "${i}"
        done
        ;;
    esac
  done

I've made this script and I want to execute it as a regular user but dbus-monitor only works as root. Is there a way to execute dbus-monitor as root and the rest of the pipes as a regular user? Adding sudo before dbus-monitor is not an option as it is just a workaround, I could intend to execute the script as root and it would escalate privileges once again for no reason. I would also want to make use of polkit, pkexec for example. Thanks!

Body:
Just like this:

cmd_a | sudo -u "${USER}" cmd_b

If the script is started as root, cmd_a will run as root and cmd_b will run as $USER.


问:
Plotting two figures side by side
As title says, I am struggling to plot two plots together, side by side. Conceptually,  the code is the following:

```<code>def my_func(arr):
    plt.scatter(arr[:, 0], arr[:, 1])

fig, ax = plt.subplots(1, 2, sharex='col', sharey='row')

arr1 = np.array([[1, 2], [2, 2], [4, 3], [6, 4], [5, 6]])

for i in range(2):
   my_func(arr1 + i)
</code>```

The issue here is to plot two plots together using my_func - a function that creates a plot (using multiple parameters, so it is should to be a separate function). The problem here is that two plots that were supposed to be plotted in two different boxes are plotted in the same box. How to fix it?

答:
You need to pass the respective axis objects to your function for plotting

```<code>def my_func(arr, ax):
    ax.scatter(arr[:, 0], arr[:, 1])

fig, ax = plt.subplots(1, 2, sharex='col', sharey='row')

arr1 = np.array([[1, 2], [2, 2], [4, 3], [6, 4], [5, 6]])

for i in range(2):
   my_func(arr1 + i, ax[i])
</code>```

Title: Plotting two figures side by side

Body:
As title says, I am struggling to plot two plots together, side by side. Conceptually,  the code is the following:

def my_func(arr):
    plt.scatter(arr[:, 0], arr[:, 1])

fig, ax = plt.subplots(1, 2, sharex='col', sharey='row')

arr1 = np.array([[1, 2], [2, 2], [4, 3], [6, 4], [5, 6]])

for i in range(2):
   my_func(arr1 + i)

The issue here is to plot two plots together using my_func - a function that creates a plot (using multiple parameters, so it is should to be a separate function). The problem here is that two plots that were supposed to be plotted in two different boxes are plotted in the same box. How to fix it?

Body:
You need to pass the respective axis objects to your function for plotting

def my_func(arr, ax):
    ax.scatter(arr[:, 0], arr[:, 1])

fig, ax = plt.subplots(1, 2, sharex='col', sharey='row')

arr1 = np.array([[1, 2], [2, 2], [4, 3], [6, 4], [5, 6]])

for i in range(2):
   my_func(arr1 + i, ax[i])


问:
google maps api v3 no smooth dragging
I started implementing my software using maps api v3. Unfortunatelly i found out that v3 API has some serious issues which draws me back from bying a bussiness licence.

My clients use monitors with HD resolution which is 1920x1080 and the map takes 90% of the screen space. Unfortunatelly here comes the problem i am talking about. When i click with the mouse on the map and start dragging it it is not smootly and it is really annoying. All the fun goes away.

I tried some different scenarious using windows XP, windows 7 and Windows 8. The browsers i am working with are the latest versions of Firefox, Chrome and IE.
Here are the results when i try to drag the map:

Small screen resolution 320x240: Firefox, Chrome and IE handle it very well. It is impossible to notice that the dragging is not smooth.

Small screen resolution 320x240 with 10 polylines on the map: Chrome and IE handle it kind of well but if you have experience with v2 API you will notice a difference. Firefox - nightmare, dragging is not smooth at all.

Medium screen resolution 1024x768. Firefox - there is some incosistent lagging. Chrome and IE - kind of smooth dragging but if you move the mouse fast things get worse.

Medium screen resolution 1024x768 with 10 polylines on the map. Firefox - nightmare. Chrome and IE - you start to notice that there is some delay but at the same time it looks kind of smooth.

High screen resolution 1920x1080. Firefox - huge lagging. Chrome and IE - a little better but still there is a noticeble lagging.
6) High screen resolution 1920x1080 with polylines on the map: Firefox, Chrome ad IE - NIGHTMARE. It is almost impossible to drag the map.

Interesting facts:

The problem described above does not exists with v2 API of google maps.

The problem described above does not exists when the mouse is moved less than 50-60 pixels per second. Dragging is really smooth. When the mouse is beeing moved fast the lagging appears.

On http://maps.google.com the problem does not exists at all BUT when i open some of the code samples on developers guide the problem is there. Here is an example: https://google-developers.appspot.com/maps/documentation/javascript/examples/full/circle-simple.

I think that i described the problem as deep as possible and no matter how hard i tried to bypass it i could not find any solution.

I will be glad if somebody shares their opinion on this problem.

P.S. Unfortunatelly i do not have a key for v2 so i can not create an example where you can view the map outside my localhost but i found a web site where there is a side by side comparison (v2 and v3). Try dragging the maps to see the VERY difference.

http://www.wolfpil.de/v2-v3-sidebyside.html

The resolution of the maps is very small and most probably unexperienced users may not see the difference so i will give you also the seperate links to the maps and you just have to use firebug or a similar debuger to make the canvas resolution bigger. Then you will see what i am talking about.

map v2: http://www.wolfpil.de/v2.html

map v3: http://www.wolfpil.de/v3.html

答:
We had issue that we had CSS3 transition added to all elements..

So remove transition and its worked fine..

See example:

#map * {
  -moz-transition: none;
  -webkit-transition: none;
  -o-transition: all 0s ease;
  transition: none;
}```

Title: google maps api v3 no smooth dragging


问:
What Jacobians does MATLAB's bvp4c evaluate?
I am trying to debug my "singular Jacobian" issues with MATLAB'S bvp4c. The question that I have is: which Jacobians are being evaluated? We have the nonlinear system of ODE's y' = f(x, y). I assume that the derivatives of f_i with respect to y_j are put into a matrix and evaluated at some values of y. Maybe this matrix should be invertible for the bvp4c algorithm, although I have found the algorithm to converge when this is not the case.

What about the residuals for the boundary conditions g(ya,yb) = 0? I assume the derivatives of g_i with respect to ya_j are taken. This gives a matrix. Also, the derivative of g_i with respect to yb_j can taken. This also gives a matrix. Does bvp4c evaluate these Jacobians? If so, then they would always be singular if any of the g_i's don't contain a ya or a yb.
Can someone point me to some theory that will illuminate the singular Jacobian error? Thank you.

答:
Yes to all of that. The solver puts all the step equations and the boundary conditions into a large non-linear system and applies some Newton or Newton-like method to it. In a very simplified version, you could use trapezoidal steps in the middle, so that your system is

```<code>left_bc(x[0],y[0])=0
y[1]-y[0] - 0.5*( x[1]-x[0]) * ( f(x[0],y[0]) + f(x[1],y[1]) ) = 0
...
y[N]-y[N-1] - 0.5*( x[N]-x[N-1]) * ( f(x[N-1],y[N-1]) + f(x[N],y[N]) ) = 0
right_bc(x[N],y[N])=0
</code>```

As you can see, the Jacobians of f wrt. y are blocks in the Jacobian of that system. As with any large non-linear system, the solution process depends critically on the initial point.

BVP4c uses a 4th order collocation method instead of the 2nd order trapezoidal steps (which is also in the class of collocation methods).

Body:
Yes to all of that. The solver puts all the step equations and the boundary conditions into a large non-linear system and applies some Newton or Newton-like method to it. In a very simplified version, you could use trapezoidal steps in the middle, so that your system is

left_bc(x[0],y[0])=0
y[1]-y[0] - 0.5*( x[1]-x[0]) * ( f(x[0],y[0]) + f(x[1],y[1]) ) = 0
...
y[N]-y[N-1] - 0.5*( x[N]-x[N-1]) * ( f(x[N-1],y[N-1]) + f(x[N],y[N]) ) = 0
right_bc(x[N],y[N])=0

As you can see, the Jacobians of f wrt. y are blocks in the Jacobian of that system. As with any large non-linear system, the solution process depends critically on the initial point.

BVP4c uses a 4th order collocation method instead of the 2nd order trapezoidal steps (which is also in the class of collocation methods).


问:
How to prevent ie from decoding a utf-8 url in flash?
I'm finding that in flash (10.x at least) and ie (7, 8, 9) that if I try to load an image url that contains escaped utf-8 characters (p%C3%83%C2%A5) that the characters get decoded before it makes the url request, even if I double or triple encode them.  Is there any way to prevent this so the url (with escapes) the way I want it is actually what is requested?

The problem its causing is we give a http status of 301 on utf-8 decoded url requests to the encoded url which flash then tries to request (but ie decodes it again) and I get stuck in an infinite loop because of the 301 + ie auto-decoding.

EDIT, adding code sample:

```<code>var url:URLRequest = new URLRequest('http://mydomain.com/p%C3%A5.jpg');
var loader:Loader = new Loader();
loader.load(url);
</code>```

Now I want the request to go over the line as http://mydomain.com/p%C3%A5.jpg (and it does in other browsers), but in IE it goes over the line as http://mydomain.com/pÃ¥.jpg

EDIT: I also tried the (good) suggestion of replacing % with %25 (double encoding the %) but that didn't work, it just caused this request to go over the wire:

http://mydomain.com/p%25C3%25A5.jpg

答:
IE is probably trying to resolve the file name by decoding it first.

301 is a redirect

Why not just make a redirct page
This could be another option for you.

```<code>var url:URLRequest = new URLRequest('http://mydomain.com/redirpage.php?page=p%C3%A5.jpg');
</code>```

Body:
I'm finding that in flash (10.x at least) and ie (7, 8, 9) that if I try to load an image url that contains escaped utf-8 characters (p%C3%83%C2%A5) that the characters get decoded before it makes the url request, even if I double or triple encode them.  Is there any way to prevent this so the url (with escapes) the way I want it is actually what is requested?

The problem its causing is we give a http status of 301 on utf-8 decoded url requests to the encoded url which flash then tries to request (but ie decodes it again) and I get stuck in an infinite loop because of the 301 + ie auto-decoding.

EDIT, adding code sample:

var url:URLRequest = new URLRequest('http://mydomain.com/p%C3%A5.jpg');
var loader:Loader = new Loader();
loader.load(url);

Now I want the request to go over the line as http://mydomain.com/p%C3%A5.jpg (and it does in other browsers), but in IE it goes over the line as http://mydomain.com/pÃ¥.jpg

EDIT: I also tried the (good) suggestion of replacing % with %25 (double encoding the %) but that didn't work, it just caused this request to go over the wire:

http://mydomain.com/p%25C3%25A5.jpg

Body:
IE is probably trying to resolve the file name by decoding it first.

301 is a redirect

Why not just make a redirct page
This could be another option for you.

var url:URLRequest = new URLRequest('http://mydomain.com/redirpage.php?page=p%C3%A5.jpg');


问:
What's the cleanest and most efficient way to pass two stereo images to a loss function in Keras?
First off, why am I using Keras? I'm trying to stay as high level as possible, which doesn't mean I'm scared of low-level Tensorflow; I just want to see how far I can go while keeping my code as simple and readable as possible.

I need my Keras model (custom-built using the Keras functional API) to read the left image from a stereo pair and minimize a loss function that needs to access both the right and left images. I want to store the data in a tf.data.Dataset.

What I tried:

Reading the dataset as (left image, right image), i.e. as tensors with shape ((W, H, 3), (W, H, 3)), then use function closure: define a keras_loss(left_images) that returns a loss(y_true, y_pred), with y_true being a tf.Tensor that holds the right image. The problem with this approach is that left_images is a tf.data.Dataset and Tensorflow complains (rightly so) that I'm trying to operate on a dataset instead of a tensor.

Reading the dataset as (left image, (left image, right image)), which should make y_true a tf.Tensor with shape ((W, H, 3), (W, H, 3)) that holds both the right and left images. The problem with this approach is that it...does not work and raises the following error:

```<code>ValueError: Error when checking model target: the list of Numpy arrays
that you are passing to your model is not the size the model expected.
Expected to see 1 array(s), for inputs ['tf_op_layer_resize/ResizeBilinear']
but instead got the following list of 2 arrays: [<tf.Tensor 'args_1:0'
shape=(None, 512, 256, 3) dtype=float32>, <tf.Tensor 'args_2:0'
shape=(None, 512, 256, 3) dtype=float32>]...
</code>```

So, is there anything I did not consider? I read the documentation and found nothing about what gets considered as y_pred and what as y_true, nor about how to convert a dataset into a tensor smartly and without loading it all in memory.

My model is designed as such:

```<code> def my_model(input_shape):
     width = input_shape[0]
     height = input_shape[1]
     inputs = tf.keras.Input(shape=input_shape)
     # < a few more layers >
     outputs = tf.image.resize(tf.nn.sigmoid(tf.slice(disp6, [0, 0, 0, 0], [-1, -1, -1, 2])), tf.Variable([width, height]))
     model = tf.keras.Model(inputs=inputs, outputs=outputs)
     return model
</code>```

And my dataset is built as such (in case 2, while in case 1 only the function read_stereo_pair_from_line() changes):

```<code>def read_img_from_file(file_name):
    img = tf.io.read_file(file_name)
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_png(img, channels=3)
    # Use `convert_image_dtype` to convert to floats in the [0,1] range.
    img = tf.image.convert_image_dtype(img, tf.float32)
    # resize the image to the desired size.
    return tf.image.resize(img, [args.input_width, args.input_height])

def read_stereo_pair_from_line(line):
    split_line = tf.strings.split(line, ' ')
    return read_img_from_file(split_line[0]), (read_img_from_file(split_line[0]), read_img_from_file(split_line[1]))

# Dataset loading
list_ds = tf.data.TextLineDataset('test/files.txt')
images_ds = list_ds.map(lambda x: read_stereo_pair_from_line(x))
images_ds = images_ds.batch(1)
</code>```

答: Solved. I just needed to read the dataset as (left image, [left image, right image]) instead of (left image, (left image, right image)) i.e. make the second item a list and not a tuple. I can then access the images as input_r = y_true[:, 1, :, :] and input_l = y_true[:, 0, :, :]

Body:
First off, why am I using Keras? I'm trying to stay as high level as possible, which doesn't mean I'm scared of low-level Tensorflow; I just want to see how far I can go while keeping my code as simple and readable as possible.

I need my Keras model (custom-built using the Keras functional API) to read the left image from a stereo pair and minimize a loss function that needs to access both the right and left images. I want to store the data in a tf.data.Dataset.

What I tried:

Reading the dataset as (left image, right image), i.e. as tensors with shape ((W, H, 3), (W, H, 3)), then use function closure: define a keras_loss(left_images) that returns a loss(y_true, y_pred), with y_true being a tf.Tensor that holds the right image. The problem with this approach is that left_images is a tf.data.Dataset and Tensorflow complains (rightly so) that I'm trying to operate on a dataset instead of a tensor.

Reading the dataset as (left image, (left image, right image)), which should make y_true a tf.Tensor with shape ((W, H, 3), (W, H, 3)) that holds both the right and left images. The problem with this approach is that it...does not work and raises the following error:

ValueError: Error when checking model target: the list of Numpy arrays
that you are passing to your model is not the size the model expected.
Expected to see 1 array(s), for inputs ['tf_op_layer_resize/ResizeBilinear']
but instead got the following list of 2 arrays: [<tf.Tensor 'args_1:0'
shape=(None, 512, 256, 3) dtype=float32>, <tf.Tensor 'args_2:0'
shape=(None, 512, 256, 3) dtype=float32>]...

So, is there anything I did not consider? I read the documentation and found nothing about what gets considered as y_pred and what as y_true, nor about how to convert a dataset into a tensor smartly and without loading it all in memory.

My model is designed as such:

 def my_model(input_shape):
     width = input_shape[0]
     height = input_shape[1]
     inputs = tf.keras.Input(shape=input_shape)
     #
     outputs = tf.image.resize(tf.nn.sigmoid(tf.slice(disp6, [0, 0, 0, 0], [-1, -1, -1, 2])), tf.Variable([width, height]))
     model = tf.keras.Model(inputs=inputs, outputs=outputs)
     return model

And my dataset is built as such (in case 2, while in case 1 only the function read_stereo_pair_from_line() changes):

def read_img_from_file(file_name):
    img = tf.io.read_file(file_name)
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_png(img, channels=3)
    # Use `convert_image_dtype` to convert to floats in the [0,1] range.
    img = tf.image.convert_image_dtype(img, tf.float32)
    # resize the image to the desired size.
    return tf.image.resize(img, [args.input_width, args.input_height])

def read_stereo_pair_from_line(line):
    split_line = tf.strings.split(line, ' ')
    return read_img_from_file(split_line[0]), (read_img_from_file(split_line[0]), read_img_from_file(split_line[1]))

# Dataset loading
list_ds = tf.data.TextLineDataset('test/files.txt')
images_ds = list_ds.map(lambda x: read_stereo_pair_from_line(x))
images_ds = images_ds.batch(1)


问:
Stripping out hyphens from a Date String
Is it possible to strip out/substitute/replace out hyphens from a date string so that only the digits are returned in the match group?

Test Strings

```<code>25-11-1982

11-10-1200
</code>```

I would like to return

```<code>25111982

11101200
</code>```

What I have so far:

```<code>(?<date>[\d]{2}-[\d]{2}-[\d]{4})
</code>```

Returns Date =

```<code>25-11-1982

11-10-1200
</code>```

Link to attempt: https://regex101.com/r/3vvYHu/2/

答:
Please take a look at the following example:
https://regex101.com/r/AcX8FL/1

It contains regular expression as well as substitution section.

Regex:

```<code>([\d]{2})-([\d]{2})-([\d]{4})
</code>```

Substitution:

```<code>$1$2$3
</code>```

Input:

```<code>25-11-1982
</code>```

Output:

```<code>25111982
</code>```

Body:
Is it possible to strip out/substitute/replace out hyphens from a date string so that only the digits are returned in the match group?

Test Strings

25-11-1982

11-10-1200

I would like to return

25111982

11101200

What I have so far:

(?<date>[\d]{2}-[\d]{2}-[\d]{4})

Returns Date =

25-11-1982

11-10-1200

Link to attempt: https://regex101.com/r/3vvYHu/2/

Body:
Please take a look at the following example:
https://regex101.com/r/AcX8FL/1

It contains regular expression as well as substitution section.

Regex:

([\d]{2})-([\d]{2})-([\d]{4})

Substitution:

$1$2$3

Input:

25-11-1982

Output:

25111982


问:
How to count the total number of rows in a ACF repeater output
Question: How do you simply count the rows in the output of an ACF repeater field?

Goal: to make the output look different with a css class when there's only one row, vs. more than one row.

My code:

```<code>if( have_rows('testimonials')) {
    $counter = 0;
    $numtestimonials = '';

    //loop thru the rows
    while ( have_rows('testimonials') ){
        the_row();
        $counter++;
            if ($counter < 2) {
                $numtestimonials = 'onlyone';
            }
        echo '<div class="testimonial ' . $numtestimonials . '">';
           // bunch of output here
        echo '</div>';
    }
}
</code>```

Obviously, The way I do it here will not work as the count is < 2 the first time thru the row, so it returns true even if more rows are counted after.

Thank you!

答:
Advanced Custom Fields has a built in function to count the rows added in version 5.3.4.

Official Documenation: ACF | get_row_index()

You can use get_row_index(); inside the loop.

```<code><?php if( have_rows('slides') ): ?>
    <?php while( have_rows('slides') ): the_row(); ?>
        <div class="accordion" id="accordion-<?php echo get_row_index(); ?>">
            <h3><?php the_sub_field('title'); ?></h3>
            <?php the_sub_field('text'); ?>
        </div>
    <?php endwhile; ?>
<?php endif; ?>
</code>```

The index returned from this function begins at 1. This means a Repeater field with 3 rows of data will produce indexes of 1, 2 and 3.

Body:
Question: How do you simply count the rows in the output of an ACF repeater field?

Goal: to make the output look different with a css class when there's only one row, vs. more than one row.

My code:

if( have_rows('testimonials')) {
    $counter = 0;
    $numtestimonials = '';

    //loop thru the rows
    while ( have_rows('testimonials') ){
        the_row();
        $counter++;
            if ($counter < 2) {
                $numtestimonials = 'onlyone';
            }
        echo '
';
           // bunch of output here
        echo '
';
    }
}

Obviously, The way I do it here will not work as the count is < 2 the first time thru the row, so it returns true even if more rows are counted after.

Thank you!

Body:
Advanced Custom Fields has a built in function to count the rows added in version 5.3.4.

Official Documenation: ACF | get_row_index()

You can use get_row_index(); inside the loop.

<?php if( have_rows('slides') ): ?>
    <?php while( have_rows('slides') ): the_row(); ?>
        <div class="accordion" id="accordion-<?php echo get_row_index(); ?>">
            <h3><?php the_sub_field('title'); ?></h3>
            <?php the_sub_field('text'); ?>
        </div>
    <?php endwhile; ?>
<?php endif; ?>

The index returned from this function begins at 1. This means a Repeater field with 3 rows of data will produce indexes of 1, 2 and 3.


问:
How to create a CSS loader with gradient border and transparency?
I'm trying to do a loader with HTML and CSS I have the loader done but there's an issue when I have information behind the center of the loader the information doesn't show and the reason is because I have background: white; that I need to avoid showing the gradient because if I remove the white color and put transparent the gradient appears.

So I need to fix the problem when I have something behind the loader

.loader {
  display: flex;
  justify-content: center;
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 10;
}

.loader .circle {
  background-image:linear-gradient(90deg, #a03297, #e90b5a);
  width: 80px;
  height: 80px;
  border-style: solid;
  border-color: transparent;
  border-radius: 50%;
  border-width: 1px;
  animation: rot 2s linear infinite;
  padding: 10px;
  box-sizing: content-box;
}

.circle > div {
  background:white;
  height: 100%;
  width: 100%;
  border-style: solid;
  border-color:transparent;
  border-radius: 50%;
  border-width: 1px;
}

@keyframes rot {
   0% { transform: rotate(0deg) }
   100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader">
  <div class="circle">
    <div></div>
  </div>
</div>

<p style="text-align: center; margin-top: 140px;">aaaaaaasssssssssssssssssçççççççççççççççççççççççççççççççççççççççççssssssss</p></code>```

答:
Use mask to make the inner part transparent:

.loader {
  background:linear-gradient(yellow, #e90b5a);
  /* Show only 10px from the border */
  -webkit-mask:radial-gradient(farthest-side,#0000 calc(100% - 10px),#fff 0);
          mask:radial-gradient(farthest-side,#0000 calc(100% - 10px),#fff 0);
  border-radius: 50%;
  position: fixed;
  inset : calc(50% - 50px);
  animation: rot 2s linear infinite;
}

@keyframes rot {
   100% { transform: rotate(360deg); }
}

body {
  background:linear-gradient(to right,grey,white)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader"></div></code>```

Body:
I'm trying to do a loader with HTML and CSS I have the loader done but there's an issue when I have information behind the center of the loader the information doesn't show and the reason is because I have background: white; that I need to avoid showing the gradient because if I remove the white color and put transparent the gradient appears.

So I need to fix the problem when I have something behind the loader

.loader {
  display: flex;
  justify-content: center;
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 10;
}

.loader .circle {
  background-image:linear-gradient(90deg, #a03297, #e90b5a);
  width: 80px;
  height: 80px;
  border-style: solid;
  border-color: transparent;
  border-radius: 50%;
  border-width: 1px;
  animation: rot 2s linear infinite;
  padding: 10px;
  box-sizing: content-box;
}

.circle > div {
  background:white;
  height: 100%;
  width: 100%;
  border-style: solid;
  border-color:transparent;
  border-radius: 50%;
  border-width: 1px;
}

@keyframes rot {
   0% { transform: rotate(0deg) }
   100% { transform: rotate(360deg); }
}

aaaaaaasssssssssssssssssçççççççççççççççççççççççççççççççççççççççççssssssss

Body:
Use mask to make the inner part transparent:

.loader {
  background:linear-gradient(yellow, #e90b5a);
  /* Show only 10px from the border */
  -webkit-mask:radial-gradient(farthest-side,#0000 calc(100% - 10px),#fff 0);
          mask:radial-gradient(farthest-side,#0000 calc(100% - 10px),#fff 0);
  border-radius: 50%;
  position: fixed;
  inset : calc(50% - 50px);
  animation: rot 2s linear infinite;
}

@keyframes rot {
   100% { transform: rotate(360deg); }
}

body {
  background:linear-gradient(to right,grey,white)
}

<div class="loader"></div>


问:
How to use jQuery validator with MVC 3 to display custom images
I am working in an MVC application, attempting to use custom images (check mark when the input is valid, and an "x" to show if the information is invalid).

The documentation for the plugin can be seen here http://docs.jquery.com/Plugins/Validation/. They have some good examples, and even some demo applications setup as well.

I can follow the example given here http://docs.jquery.com/Plugins/Validation/validate#toptions (scroll down to "Add a class "valid" to valid elements, styled via CSS). This works properly if I use a plain html page, however, when attempting to follow this in MVC I am running into issues and I can't specifically find the reason.

My script looks like:

```<code><script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("input").validate({
            success: "valid",
            submitHandler: function () { alert("Submitted!") }
        })
    })
</script>
</code>```

In my Site.css

```<code>label.valid
{
    background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif')    no-repeat;
    height:16px;
    width:16px;
    display: block;
    position: absolute;
    top: 4px;
    left: 152px;
}
</code>```

In my view

```<code><div class="smallError" align="center">
       @Html.ValidationMessageFor(model => model.GiftCode)
</div>
<div align="center">
       @Html.EditorFor(m => m.GiftCode)
</div>
</code>```

Now, I can get the ValidationMessageFor to appear, and show the appropriate message.. however I cannot get it to display my check mark if the image is valid.

Is there any easier way to tie into the validation that is already being done?

Regards.

答:
For anyone interested in the resolution of this problem, please copy the files locally that are used.

For example, in the documentation of the plug-in, it wants you to access the scripts like:

```<code><script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"
 src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js">
</script>
</code>```

However, in MVC the way they are referencing the files won't work. It will give you a forbidden 403 error when attempting to access the script and the associated image file.

To combat this simply download the script locally and place it inside of the scripts folder in your solution explorer.

I hope this saves somebody some time in the future as this was the only issue with the example provided here: http://docs.jquery.com/Plugins/Validation/validate#toptions .

Body:
I am working in an MVC application, attempting to use custom images (check mark when the input is valid, and an "x" to show if the information is invalid).

The documentation for the plugin can be seen here http://docs.jquery.com/Plugins/Validation/. They have some good examples, and even some demo applications setup as well.

I can follow the example given here http://docs.jquery.com/Plugins/Validation/validate#toptions (scroll down to "Add a class "valid" to valid elements, styled via CSS). This works properly if I use a plain html page, however, when attempting to follow this in MVC I am running into issues and I can't specifically find the reason.

My script looks like:

In my Site.css

label.valid
{
    background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif')    no-repeat;
    height:16px;
    width:16px;
    display: block;
    position: absolute;
    top: 4px;
    left: 152px;
}

In my view

       @Html.ValidationMessageFor(model => model.GiftCode)

       @Html.EditorFor(m => m.GiftCode)

Now, I can get the ValidationMessageFor to appear, and show the appropriate message.. however I cannot get it to display my check mark if the image is valid.

Is there any easier way to tie into the validation that is already being done?

Regards.

Body:
For anyone interested in the resolution of this problem, please copy the files locally that are used.

For example, in the documentation of the plug-in, it wants you to access the scripts like:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"
 src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js">
</script>

However, in MVC the way they are referencing the files won't work. It will give you a forbidden 403 error when attempting to access the script and the associated image file.

To combat this simply download the script locally and place it inside of the scripts folder in your solution explorer.

I hope this saves somebody some time in the future as this was the only issue with the example provided here: http://docs.jquery.com/Plugins/Validation/validate#toptions .


问:
Passing a Python variable to R using rpy2
I have basic R script that performs a GLM on a MySQL dataset. This runs fine using Rscript in bash. However I would like to call it within a python script so I can add it to a loop, I can create the sql statement but I can't seem to pass it to R using rpy2;

```<code>for word in words:
    sql_scores = "select a.article_id, response, score  from scores as a join profile as b on a.article_id = b.article_id where response in (1,0) and keyword = '%s';" % (word[0])
    robjects.r("library(RMySQL)")
    robjects.r("mydb = dbConnect(MySQL(), user='me', password='xxxx', host='aws.host', dbname='mydb')")
    robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
    robjects.r("model <- glm(response ~ score , data=results, family=binomial)")
    robjects.r("summary(model)")
</code>```

If I print sql_scores I can run this fine directly in MySQL. However Python produces this error;

```<code>Loading required package: DBI
Traceback (most recent call last):
  File "keyword_searcher.py", line 30, in <module>
    robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 268, in __call__
    p = rinterface.parse(string)
 ValueError: Error while parsing the string.
</code>```

I can't figure out the proper syntax for:

```<code>robjects.r("results = fetch(dbSendQuery(mydb, %s))") % (sql_scores)
</code>```

答:
You can access variables in the R environment with robjects.globalenv['varname'].
So an alternative way is:

```<code>robjects.globalenv['sql_scores'] = sql_scores
robjects.r("results = fetch(dbSendQuery(mydb, sql_scores))")
</code>```

Body:
I have basic R script that performs a GLM on a MySQL dataset. This runs fine using Rscript in bash. However I would like to call it within a python script so I can add it to a loop, I can create the sql statement but I can't seem to pass it to R using rpy2;

for word in words:
    sql_scores = "select a.article_id, response, score  from scores as a join profile as b on a.article_id = b.article_id where response in (1,0) and keyword = '%s';" % (word[0])
    robjects.r("library(RMySQL)")
    robjects.r("mydb = dbConnect(MySQL(), user='me', password='xxxx', host='aws.host', dbname='mydb')")
    robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
    robjects.r("model <- glm(response ~ score , data=results, family=binomial)")
    robjects.r("summary(model)")

If I print sql_scores I can run this fine directly in MySQL. However Python produces this error;

Loading required package: DBI
Traceback (most recent call last):
  File "keyword_searcher.py", line 30, in <module>
    robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 268, in __call__
    p = rinterface.parse(string)
 ValueError: Error while parsing the string.

I can't figure out the proper syntax for:

robjects.r("results = fetch(dbSendQuery(mydb, %s))") % (sql_scores)

Body:
You can access variables in the R environment with robjects.globalenv['varname'].
So an alternative way is:

robjects.globalenv['sql_scores'] = sql_scores
robjects.r("results = fetch(dbSendQuery(mydb, sql_scores))")


问:
Curl 415 Unsupported Media Type
I am trying to test my endpoint with curl and getting a 415:

```<code>curl -X POST "http://localhost:5001/api/countries/import" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer "$API_TOKEN \
--data @/D:/_countries.json
</code>```

Response:

```<code>{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"0HLTFOME7T990:00000001"}
</code>```

And here's my .net core endpoint:

```<code>// POST api/countries/import
[HttpPost]
[Route("[action]")]
public async Task<IActionResult> Import(IFormFile file)
{
    ...
}
</code>```

Btw, I have no problem with this endpoint in postman although it's generated code doesn't work for me (the response is the same):

```<code>curl --location --request POST 'http://localhost:5001/api/countries/import' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {token here}' \
--form 'file=@/D:/_countries.json'
</code>```

P.S. I am using Windows 10 and git bash to run the script.

答:
Unsupported Media Type

Your action public async Task<IActionResult> Import(IFormFile file) expect IFormFile  parameter, but you sepecified request header with Content-Type: application/json, which cuase this issue.

Please try to specify the header to  --header 'Content-Type: multipart/form-data', like below.

Title: Curl 415 Unsupported Media Type

Body:
I am trying to test my endpoint with curl and getting a 415:

curl -X POST "http://localhost:5001/api/countries/import" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer "$API_TOKEN \
--data @/D:/_countries.json

Response:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"0HLTFOME7T990:00000001"}

And here's my .net core endpoint:

// POST api/countries/import
[HttpPost]
[Route("[action]")]
public async Task<IActionResult> Import(IFormFile file)
{
    ...
}

Btw, I have no problem with this endpoint in postman although it's generated code doesn't work for me (the response is the same):

curl --location --request POST 'http://localhost:5001/api/countries/import' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {token here}' \
--form 'file=@/D:/_countries.json'

P.S. I am using Windows 10 and git bash to run the script.


问:
How to send numpy array to sagemaker endpoint using lambda function
How to invoke sagemaker endpoint with input data type numpy.ndarray.
I have deployed a sagemaker model and trying to hit it using lambda function.
But I am unable to figure out how to do it. I am getting server error.

One row of the Input data.
The total data set has shape=(91,5,12).
The below is only one row of Input data.

```<code>array([[[0.30440741, 0.30209799, 0.33520652, 0.41558442, 0.69096432,
         0.69611016, 0.25153326, 0.98333333, 0.82352941, 0.77187154,
         0.7664042 , 0.74468085],
        [0.30894981, 0.33151662, 0.22907725, 0.46753247, 0.69437367,
         0.70410559, 0.29259044, 0.9       , 0.80882353, 0.79401993,
         0.89501312, 0.86997636],
        [0.33511896, 0.34338939, 0.24065546, 0.48051948, 0.70384005,
         0.71058715, 0.31031288, 0.86666667, 0.89705882, 0.82724252,
         0.92650919, 0.89125296],
        [0.34617355, 0.36150251, 0.23726854, 0.54545455, 0.71368726,
         0.71703244, 0.30228356, 0.85      , 0.86764706, 0.86157254,
         0.97112861, 0.94089835],
        [0.36269508, 0.35923332, 0.40285461, 0.62337662, 0.73325475,
         0.7274392 , 0.26241391, 0.85      , 0.82352941, 0.89922481,
         0.9343832 , 0.90780142]]])
</code>```

I am using the following code but unable to invoke the endpoint

```<code>import boto3
def lambda_handler(event, context):
    # The SageMaker runtime is what allows us to invoke the endpoint that we've created.
    runtime = boto3.Session().client('sagemaker-runtime')

    endpoint = 'sagemaker-tensorflow-2019-04-22-07-16-51-717'

    print('givendata ', event['body'])
    # data = numpy.array([numpy.array(xi) for xi in event['body']])
    data = event['body']
    print('numpy array ', data)

    # Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given
    response = runtime.invoke_endpoint(EndpointName = endpoint,# The name of the endpoint we created
                                       ContentType = 'application/json',                 # The data format that is expected
                                       Body = data) # The actual review

    # The response is an HTTP response whose body contains the result of our inference
    result = response['Body'].read().decode('utf-8')

    print('response', result)

    # Round the result so that our web app only gets '1' or '0' as a response.
    result = round(float(result))

    return {
        'statusCode' : 200,
        'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' },
        'body' : str(result)
    }
</code>```

I am unable to figure out what should be written in place of ContentType.
Because I am not aware of MIME type in case of numpy.ndarray.

答:
Illustration of what I had and how I solved

```<code>from sagemaker.tensorflow import TensorFlowPredictor

predictor = TensorFlowPredictor('sagemaker-tensorflow-serving-date')
data = np.array(raw_data)
response = predictor.predict(data=data)
predictions = response['predictions']
print(predictions)
</code>```

What I did to find the answer:

Looked up predictions.py and content_types.py implementation in sagemaker python library to see what content types it used and what arguments it had.

First I thought that application/x-npy content_type was used and thus tried using serialisation code from predictor.py and passing the application/x-npy as content_type to invoke_endpoint.

After receiving 415 (unsupported media type), the issue was still the content_type. The following print statements helped me to reveal what content_type predictor actually uses (application/json) and thus I took the appropriate serialisation code from predictor.py

```<code>from sagemaker.tensorflow import TensorFlowPredictor

predictor = TensorFlowPredictor('sagemaker-tensorflow-serving-date')
data = np.array(raw_data)
response = predictor.predict(data=data)
print(predictor.content_type)
print(predictor.accept)
predictions = response['predictions']
print(predictions)
</code>```

TL;DR

Solution for lambda:

```<code>import json
import boto3

ENDPOINT_NAME = 'sagemaker-tensorflow-serving-date'
config = botocore.config.Config(read_timeout=80)
runtime= boto3.client('runtime.sagemaker', config=config)
data = np.array(raw_data)
payload = json.dumps(data.tolist())
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
                                   ContentType='application/json',
                                   Body=payload)
result = json.loads(response['Body'].read().decode())
res = result['predictions']
</code>```

Note: numpy is not included in lambda thus you would either include the numpy yourself or instead of data.tolist() operate with python list and json.dump that list (of lists). From your code it seems to me you have python list instead of numpy array, so simple json dump should work.

Body:
How to invoke sagemaker endpoint with input data type numpy.ndarray.
I have deployed a sagemaker model and trying to hit it using lambda function.
But I am unable to figure out how to do it. I am getting server error.

One row of the Input data.
The total data set has shape=(91,5,12).
The below is only one row of Input data.

array([[[0.30440741, 0.30209799, 0.33520652, 0.41558442, 0.69096432,
         0.69611016, 0.25153326, 0.98333333, 0.82352941, 0.77187154,
         0.7664042 , 0.74468085],
        [0.30894981, 0.33151662, 0.22907725, 0.46753247, 0.69437367,
         0.70410559, 0.29259044, 0.9       , 0.80882353, 0.79401993,
         0.89501312, 0.86997636],
        [0.33511896, 0.34338939, 0.24065546, 0.48051948, 0.70384005,
         0.71058715, 0.31031288, 0.86666667, 0.89705882, 0.82724252,
         0.92650919, 0.89125296],
        [0.34617355, 0.36150251, 0.23726854, 0.54545455, 0.71368726,
         0.71703244, 0.30228356, 0.85      , 0.86764706, 0.86157254,
         0.97112861, 0.94089835],
        [0.36269508, 0.35923332, 0.40285461, 0.62337662, 0.73325475,
         0.7274392 , 0.26241391, 0.85      , 0.82352941, 0.89922481,
         0.9343832 , 0.90780142]]])

I am using the following code but unable to invoke the endpoint

import boto3
def lambda_handler(event, context):
    # The SageMaker runtime is what allows us to invoke the endpoint that we've created.
    runtime = boto3.Session().client('sagemaker-runtime')

    endpoint = 'sagemaker-tensorflow-2019-04-22-07-16-51-717'

    print('givendata ', event['body'])
    # data = numpy.array([numpy.array(xi) for xi in event['body']])
    data = event['body']
    print('numpy array ', data)

    # Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given
    response = runtime.invoke_endpoint(EndpointName = endpoint,# The name of the endpoint we created
                                       ContentType = 'application/json',                 # The data format that is expected
                                       Body = data) # The actual review

    # The response is an HTTP response whose body contains the result of our inference
    result = response['Body'].read().decode('utf-8')

    print('response', result)

    # Round the result so that our web app only gets '1' or '0' as a response.
    result = round(float(result))

    return {
        'statusCode' : 200,
        'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' },
        'body' : str(result)
    }

I am unable to figure out what should be written in place of ContentType.
Because I am not aware of MIME type in case of numpy.ndarray.

Body:
Illustration of what I had and how I solved

from sagemaker.tensorflow import TensorFlowPredictor

predictor = TensorFlowPredictor('sagemaker-tensorflow-serving-date')
data = np.array(raw_data)
response = predictor.predict(data=data)
predictions = response['predictions']
print(predictions)

What I did to find the answer:

Looked up predictions.py and content_types.py implementation in sagemaker python library to see what content types it used and what arguments it had.

First I thought that application/x-npy content_type was used and thus tried using serialisation code from predictor.py and passing the application/x-npy as content_type to invoke_endpoint.

After receiving 415 (unsupported media type), the issue was still the content_type. The following print statements helped me to reveal what content_type predictor actually uses (application/json) and thus I took the appropriate serialisation code from predictor.py

from sagemaker.tensorflow import TensorFlowPredictor

predictor = TensorFlowPredictor('sagemaker-tensorflow-serving-date')
data = np.array(raw_data)
response = predictor.predict(data=data)
print(predictor.content_type)
print(predictor.accept)
predictions = response['predictions']
print(predictions)

TL;DR

Solution for lambda:

import json
import boto3

ENDPOINT_NAME = 'sagemaker-tensorflow-serving-date'
config = botocore.config.Config(read_timeout=80)
runtime= boto3.client('runtime.sagemaker', config=config)
data = np.array(raw_data)
payload = json.dumps(data.tolist())
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
                                   ContentType='application/json',
                                   Body=payload)
result = json.loads(response['Body'].read().decode())
res = result['predictions']

Note: numpy is not included in lambda thus you would either include the numpy yourself or instead of data.tolist() operate with python list and json.dump that list (of lists). From your code it seems to me you have python list instead of numpy array, so simple json dump should work.


问:
How to deserialize an XML with attributes in C#
I have an XML file that looks something similar to this:

```<code><data label="product data">
    <price min="10" max="60">35</price>
</data>
</code>```

I'm using System.Xml.Serialization in .Net Core. I'm trying to Deserialize the XML. For regular XML like this:

```<code><data>
   <price>35</price>
</data>
</code>```

The following method:

```<code>public T DeserializeXml<T>(string input)
{
    var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using var stringReader = new StringReader(input);
    var xmlReader = new XmlTextReader(stringReader);
    return (T) xmlSerializer.Deserialize(xmlReader);
}
</code>```

Works fine and parses it into its specific class object. But when the XML contains attributes, it's not working fine and while trying to deserialize it into it's object it crashes.

This is my class:

```<code>[XmlType("data")]
public class ProductInfo
{
    [XmlElement(ElementName = "price")]
    public string Price{ get; set; }
}
</code>```

So how can I retreive a valid XML with attributes and how to store its attributes values? Not sure on how to do it using System.Xml.Serialization library.

答:
By looking at the XML the model should look like</p>

```<code>[XmlRoot(ElementName="price")]
public class Price {
    [XmlAttribute(AttributeName="min")]
    public string Min { get; set; }
    [XmlAttribute(AttributeName="max")]
    public string Max { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="price")]
    public Price Price { get; set; }
    [XmlAttribute(AttributeName="label")]
    public string Label { get; set; }
}
</code>```

Body:
I have an XML file that looks something similar to this:

<data label="product data">
    <price min="10" max="60">35</price>
</data>

I'm using System.Xml.Serialization in .Net Core. I'm trying to Deserialize the XML. For regular XML like this:

<data>
   <price>35</price>
</data>

The following method:

public T DeserializeXml<T>(string input)
{
    var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using var stringReader = new StringReader(input);
    var xmlReader = new XmlTextReader(stringReader);
    return (T) xmlSerializer.Deserialize(xmlReader);
}

Works fine and parses it into its specific class object. But when the XML contains attributes, it's not working fine and while trying to deserialize it into it's object it crashes.

This is my class:

[XmlType("data")]
public class ProductInfo
{
    [XmlElement(ElementName = "price")]
    public string Price{ get; set; }
}

So how can I retreive a valid XML with attributes and how to store its attributes values? Not sure on how to do it using System.Xml.Serialization library.

Body:
By looking at the XML the model should look like

[XmlRoot(ElementName="price")]
public class Price {
    [XmlAttribute(AttributeName="min")]
    public string Min { get; set; }
    [XmlAttribute(AttributeName="max")]
    public string Max { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="price")]
    public Price Price { get; set; }
    [XmlAttribute(AttributeName="label")]
    public string Label { get; set; }
}


问:
How to access ag-Grid API in React function component (useState hook)?
What is the best way of accessing ag-Grid API inside of React function component?

I have to use some of the methods from API (getSelectedNodes, setColumnDefs etc.) so I save a reference to the API (using useState hook) in onGridReady event handler:

```<code>onGridReady={params => {
    setGridApi(params.api);
}}
</code>```

and then I can call the API like this: gridApi.getSelectedNodes()

I haven't noticed any problems with this approach, but I'm wondering if there's more idiomatic way?

Stack:

ag-grid-community & ag-grid-react 22.1.1

react 16.12.0

答:
Well I am doing it in my project. You can use useRef hook to store gridApi.

```<code>const gridApi = useRef();

const onGridReady = params => {

   gridApi.current = params.api;  // <== this is how you save it

   const datasource = getServerDataSource(
     gridApi.current,
     {
       size: AppConstants.PAGE_SIZE,
       url: baseUrl,
       defaultFilter: props.defaultFilter
     }
   );

  gridApi.current.setServerSideDatasource(datasource); // <== this is how you use it
};
</code>```

Body:
What is the best way of accessing ag-Grid API inside of React function component?

I have to use some of the methods from API (getSelectedNodes, setColumnDefs etc.) so I save a reference to the API (using useState hook) in onGridReady event handler:

onGridReady={params => {
    setGridApi(params.api);
}}

and then I can call the API like this: gridApi.getSelectedNodes()

I haven't noticed any problems with this approach, but I'm wondering if there's more idiomatic way?

Stack:

ag-grid-community & ag-grid-react 22.1.1

react 16.12.0

Body:
Well I am doing it in my project. You can use useRef hook to store gridApi.

const gridApi = useRef();

const onGridReady = params => {

   gridApi.current = params.api;  // <== this is how you save it

   const datasource = getServerDataSource(
     gridApi.current,
     {
       size: AppConstants.PAGE_SIZE,
       url: baseUrl,
       defaultFilter: props.defaultFilter
     }
   );

  gridApi.current.setServerSideDatasource(datasource); // <== this is how you use it
};


问:
UIViewController question for iPhone/iPad
I have an App with one MainWindow.xib file.  Then I have ViewControllerA.xib and ViewControllerB.xib.  My MainWindow.xib have one ViewController that points two ViewControllerA.xib.

On ViewControllerA I have a button and I would like the button, when pressed, to move ViewControllerB onto the screen.  How do I do that?

I tried this code, but I think I am missing something:

```<code>- (IBAction)btMyButton:(id)sender
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
    [self.navigationController pushViewController:viewController animated:YES];
}
</code>```

My ViewControllerB does appear, but it is squashed at the top of the screen, over the previous view.  Any help is greatly appreciated.

Thank you

答:
you will need to remove old viewcontroller from main windows. </p>

```<code>- (IBAction)btMyButton:(id)sender
{

//Assuming you declare two Iboutlet controllerA, controllerB mapping with that view as class variable
{
if (self.controllerB == nil)
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    self.controllerB = viewController;
[viewController release];
}
[controllerA.view removeFromSuperview];
[self.view insertSubview:controllerB.view atIndex:0];
}

}
</code>```

Body:
I have an App with one MainWindow.xib file.  Then I have ViewControllerA.xib and ViewControllerB.xib.  My MainWindow.xib have one ViewController that points two ViewControllerA.xib.

On ViewControllerA I have a button and I would like the button, when pressed, to move ViewControllerB onto the screen.  How do I do that?

I tried this code, but I think I am missing something:

- (IBAction)btMyButton:(id)sender
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
    [self.navigationController pushViewController:viewController animated:YES];
}

My ViewControllerB does appear, but it is squashed at the top of the screen, over the previous view.  Any help is greatly appreciated.

Thank you

Body:
you will need to remove old viewcontroller from main windows.

- (IBAction)btMyButton:(id)sender
{

//Assuming you declare two Iboutlet controllerA, controllerB mapping with that view as class variable
{
if (self.controllerB == nil)
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    self.controllerB = viewController;
[viewController release];
}
[controllerA.view removeFromSuperview];
[self.view insertSubview:controllerB.view atIndex:0];
}

}