问:
Categorical variables usage in pandas for ANOVA and regression?
To prepare a little toy example:

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

high, size = 100, 20
df = pd.DataFrame({'perception': np.random.randint(0, high, size),
                   'age': np.random.randint(0, high, size),
                   'outlook': pd.Categorical(np.tile(['positive', 'neutral', 'negative'], size//3+1)[:size]),
                   'smokes': pd.Categorical(np.tile(['lots', 'little', 'not'], size//3+1)[:size]),
                   'outcome': np.random.randint(0, high, size)
                  })
df['age_range'] = pd.Categorical(pd.cut(df.age, range(0, high+5, size//2), right=False,
                             labels=["{0} - {1}".format(i, i + 9) for i in range(0, high, size//2)]))
np.random.shuffle(df['smokes'])
</code>```

Which will give you something like:

```<code>In [2]: df.head(10)
Out[2]:
   perception  age   outlook  smokes  outcome age_range
0          13   65  positive  little       22   60 - 69
1          95   21   neutral    lots       95   20 - 29
2          61   53  negative     not        4   50 - 59
3          27   98  positive     not       42   90 - 99
4          55   99   neutral  little       93   90 - 99
5          28    5  negative     not        4     0 - 9
6          84   83  positive    lots       18   80 - 89
7          66   22   neutral    lots       35   20 - 29
8          13   22  negative    lots       71   20 - 29
9          58   95  positive     not       77   90 - 99
</code>```

Goal: figure out likelihood of outcome, given {perception, age, outlook, smokes}.

Secondary goal: figure out how important each column is in determining outcome.

Third goal: prove attributes about distribution (here we have randomly generated, so a random distribution should imply the null hypothesis is true?)

Clearly these are all questions findable with statistical hypothesis testing. What's the right way of answering these questions in pandas?

答:
Finding out likelihood of outcome given columns and Feature importance (1 and 2)

Categorical data

As the dataset contains categorical values, we can use the LabelEncoder() to convert the categorical data into numeric data.

from sklearn.preprocessing import LabelEncoder

enc = LabelEncoder()
df['outlook'] = enc.fit_transform(df['outlook'])
df['smokes'] = enc.fit_transform(df['smokes'])
```

<p><strong>Result</strong></p>

<pre class="lang-py prettyprint-override"><code>df.head()

   perception  age  outlook  smokes  outcome age_range
0          67   43        2       1       78     0 - 9
1          77   66        1       1       13     0 - 9
2          33   10        0       1        1     0 - 9
3          74   46        2       1       22     0 - 9
4          14   26        1       2       16     0 - 9
</code>```

Without creating any model, we can make use of the chi-squared test, p-value and correlation matrix to determine the relation.

Correlation matrix

import matplotlib.pyplot as plt
import seaborn as sns

corr = df.iloc[:, :-1].corr()
sns.heatmap(corr,
            xticklabels=corr.columns,
            yticklabels=corr.columns)
plt.show()
```

<p><img src="https://i.stack.imgur.com/GMjVW.png" alt="Correlation matrix"></p>

<p><strong>Chi-squared test and p-value</strong></p>

<pre class="lang-py prettyprint-override"><code>from sklearn.feature_selection import chi2

res = chi2(df.iloc[:, :4], df['outcome'])
features = pd.DataFrame({
    'features': df.columns[:4],
    'chi2': res[0],
    'p-value': res[1]
})
</code>```

Result

features.head()

     features         chi2        p-value
0  perception  1436.012987  1.022335e-243
1         age  1416.063117  1.221377e-239
2     outlook    61.139303   9.805304e-01
3      smokes    57.147404   9.929925e-01
```

<p>Randomly generated data, so null hypothesis is true. We can verify this by trying to fit a normal curve to the <code>outcome</code>.</p>

<p><strong>Distribution</strong></p>

<pre class="lang-py prettyprint-override"><code>import scipy as sp

sns.distplot(df['outcome'], fit=sp.stats.norm, kde=False)
plt.show()
</code>```

From the plot we can conclude that the data does not fit a normal distribution (as it is randomly generated.)

Note: As the data is all randomly generated, you results can vary, based on the size of the data set.

References

Hypothesis testing

Feature selection

Body:
To prepare a little toy example:

import pandas as pd
import numpy as np

high, size = 100, 20
df = pd.DataFrame({'perception': np.random.randint(0, high, size),
                   'age': np.random.randint(0, high, size),
                   'outlook': pd.Categorical(np.tile(['positive', 'neutral', 'negative'], size//3+1)[:size]),
                   'smokes': pd.Categorical(np.tile(['lots', 'little', 'not'], size//3+1)[:size]),
                   'outcome': np.random.randint(0, high, size)
                  })
df['age_range'] = pd.Categorical(pd.cut(df.age, range(0, high+5, size//2), right=False,
                             labels=["{0} - {1}".format(i, i + 9) for i in range(0, high, size//2)]))
np.random.shuffle(df['smokes'])

Which will give you something like:

In [2]: df.head(10)
Out[2]:
   perception  age   outlook  smokes  outcome age_range
0          13   65  positive  little       22   60 - 69
1          95   21   neutral    lots       95   20 - 29
2          61   53  negative     not        4   50 - 59
3          27   98  positive     not       42   90 - 99
4          55   99   neutral  little       93   90 - 99
5          28    5  negative     not        4     0 - 9
6          84   83  positive    lots       18   80 - 89
7          66   22   neutral    lots       35   20 - 29
8          13   22  negative    lots       71   20 - 29
9          58   95  positive     not       77   90 - 99

Goal: figure out likelihood of outcome, given {perception, age, outlook, smokes}.

Secondary goal: figure out how important each column is in determining outcome.

Third goal: prove attributes about distribution (here we have randomly generated, so a random distribution should imply the null hypothesis is true?)

Clearly these are all questions findable with statistical hypothesis testing. What's the right way of answering these questions in pandas?

Body:
Finding out likelihood of outcome given columns and Feature importance (1 and 2)

Categorical data

As the dataset contains categorical values, we can use the LabelEncoder() to convert the categorical data into numeric data.

from sklearn.preprocessing import LabelEncoder

enc = LabelEncoder()
df['outlook'] = enc.fit_transform(df['outlook'])
df['smokes'] = enc.fit_transform(df['smokes'])

Result

df.head()

   perception  age  outlook  smokes  outcome age_range
0          67   43        2       1       78     0 - 9
1          77   66        1       1       13     0 - 9
2          33   10        0       1        1     0 - 9
3          74   46        2       1       22     0 - 9
4          14   26        1       2       16     0 - 9

Without creating any model, we can make use of the chi-squared test, p-value and correlation matrix to determine the relation.

Correlation matrix

import matplotlib.pyplot as plt
import seaborn as sns

corr = df.iloc[:, :-1].corr()
sns.heatmap(corr,
            xticklabels=corr.columns,
            yticklabels=corr.columns)
plt.show()

Chi-squared test and p-value

from sklearn.feature_selection import chi2

res = chi2(df.iloc[:, :4], df['outcome'])
features = pd.DataFrame({
    'features': df.columns[:4],
    'chi2': res[0],
    'p-value': res[1]
})

Result

features.head()

     features         chi2        p-value
0  perception  1436.012987  1.022335e-243
1         age  1416.063117  1.221377e-239
2     outlook    61.139303   9.805304e-01
3      smokes    57.147404   9.929925e-01

Randomly generated data, so null hypothesis is true. We can verify this by trying to fit a normal curve to the outcome.

Distribution

import scipy as sp

sns.distplot(df['outcome'], fit=sp.stats.norm, kde=False)
plt.show()

From the plot we can conclude that the data does not fit a normal distribution (as it is randomly generated.)

Note: As the data is all randomly generated, you results can vary, based on the size of the data set.

References

Hypothesis testing

Feature selection


来源: stackexchange

问:
Accessing Configuration Properties for the Class Decorators in ASP.NET Core
Based on this Question Here , I am working on the solution to bind the controllers to certain URLs. These URLs are configured in appsettings.json.

As the solution is based on the Decorators, I am searching for a way to inject the IConfiguration object for the decorators.

Example :

```<code>[PortActionConstraint(configuration.GetValue<string>("Product1:Port")]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase
</code>```

In short, how can I inject IConfiguration of any Interface to the Class Decorator ?

答:
The easiest solution for this is to use the service locator pattern inside of your constraint implementation to retrieve the IConfiguration object.

So within the ´IsValidForRequest` method, retrieve the service through the HTTP context:

```<code>public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
    var configuration = routeContext.HttpContext.RequestServices.GetService<IConfiguration>();

    // do something with the configuration
}
</code>```

Alternatively, you could also implement the IActionConstraintFactory which would allow you to properly resolve the dependencies using constructor injection. This will require you to implement the IActionConstraint yourself though. So for this simple requirement, using the ActionMethodSelectorAttribute with the service locator is probably easier.

ContentLicense: CC BY-SA 4.0

Body:
Based on this Question Here , I am working on the solution to bind the controllers to certain URLs. These URLs are configured in appsettings.json.

As the solution is based on the Decorators, I am searching for a way to inject the IConfiguration object for the decorators.

Example :

[PortActionConstraint(configuration.GetValue<string>("Product1:Port")]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase

In short, how can I inject IConfiguration of any Interface to the Class Decorator ?

Body:
The easiest solution for this is to use the service locator pattern inside of your constraint implementation to retrieve the IConfiguration object.

So within the ´IsValidForRequest` method, retrieve the service through the HTTP context:

public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
    var configuration = routeContext.HttpContext.RequestServices.GetService<IConfiguration>();

    // do something with the configuration
}

Alternatively, you could also implement the IActionConstraintFactory which would allow you to properly resolve the dependencies using constructor injection. This will require you to implement the IActionConstraint yourself though. So for this simple requirement, using the ActionMethodSelectorAttribute with the service locator is probably easier.


问:
What contains the beachline in Fortune's algorithm?
I'm trying to implement Fortune's algorithm in Julia to find the Voronoi polygons of an array of random points, but I'm really struggling with the beachline.

I know that the beachline is the union of several parabolas. Each parabola has a point from the array as it's focus, so the intersection of the parabolas that are next to each other gives out the "edge" between the two Voronoi regions.
Each Point in the array will be an event for the beachline to be in, but there will be also something called "circle points" which correspond to a pole (the lowest in this case) of a circle that passes through three "real points", and the real points are the points in the array of random points.

I know how to intersect parabolas, I also know that when the beachline goes through a real point, its parabola will be half a line that intersects the parabolas of previous points, and that interseccion is easy to find.

How do you store the beachline? do you just store the points of intersections as you go through the events calculating every intersection of neighbors parabolas?

I'm reading Computational Geometry algorithms and applications by Mark de Berg, but my native language is not english, so it's a little hard for me to understand a few things.

So it would be great if you could help me on this, thanks in advance.

答:
When deciding how to represent the beach line, the important consideration is that each "event" that you process in the course of the algorithm must make only local modifications to it.  If the sweep line moves a little bit, but doesn't cross any events, then your representation of the beach line should not need to change.

Therefore, the beach line data structure should not include any actual points on the beach line!

It's also important that you can find the parts to modify in O(log N) time.

The simplest representation is just a binary search tree containing the input points that contribute parabolas to the beach line, in order.  The modifications made during each event then consist of adding or removing single points.


问:
Autofac: Registering types with dependencies
I'm trying to register my WPF views with their corresponding viewmodels and avoid having to use code behind.

So far my code would look like this:

```<code> builder.Register(c =>
    {
        PageA page = new PageA();
        page.DataContext = c.Resolve<PageAViewModel>;
        return page;
    });

    builder.Register(c =>
    {
        PageB page = new PageB();
        page.DataContext = c.Resolve<PageBViewModel>;
        return page;
    });
</code>```

Is there are a more dynamic way to avoid having to write these lines for all views/pages? (if possible without using Service locator pattern).

答:
You can create a generic method that will register your types :

```<code>public static class RegistrationExtension
{

    public static IRegistrationBuilder<TPage, ConcreteReflectionActivatorData, SingleRegistrationStyle>
        RegisterPage<TPage, TViewModel>(this ContainerBuilder builder)
        where TPage : IPage
    {
        return builder.RegisterType<TPage>()
                      .OnActivated(e =>
                      {
                          e.Instance.DataContext = e.Context.Resolve<TViewModel>();
                      });

    }
}
</code>```

and then register your pages like this :

```<code>builder.RegisterPage<PageA, PageAViewModel>();
</code>```

Body:
I'm trying to register my WPF views with their corresponding viewmodels and avoid having to use code behind.

So far my code would look like this:

 builder.Register(c =>
    {
        PageA page = new PageA();
        page.DataContext = c.Resolve<PageAViewModel>;
        return page;
    });

    builder.Register(c =>
    {
        PageB page = new PageB();
        page.DataContext = c.Resolve<PageBViewModel>;
        return page;
    });

Is there are a more dynamic way to avoid having to write these lines for all views/pages? (if possible without using Service locator pattern).

Body:
You can create a generic method that will register your types :

public static class RegistrationExtension
{

    public static IRegistrationBuilder<TPage, ConcreteReflectionActivatorData, SingleRegistrationStyle>
        RegisterPage<TPage, TViewModel>(this ContainerBuilder builder)
        where TPage : IPage
    {
        return builder.RegisterType<TPage>()
                      .OnActivated(e =>
                      {
                          e.Instance.DataContext = e.Context.Resolve<TViewModel>();
                      });

    }
}

and then register your pages like this :

builder.RegisterPage<PageA, PageAViewModel>();


问:
How can i know current foreground activity(not from service)?
I am having alert generation application. I want to start or switch to other(Third) activity from current activity(foreground) using another activity's context(middle). From current activity(foreground) i m switching to other(middle) activity using intents and from this switched activity again i m switching to another(third) activity using intents. Due to such scenario, i am getting little but flash of middle activity in between current foreground activity and final most(third) activity.
How can i resolve this one?

For this purpose i want to know current foreground activity or is there any other solution?

I am not having any ideas about this one. Highly appreciate solutions.

Thanks in advance

答:
Current activity context can be obtained in the following simple way.

```<code>            Context currentContext=this;
</code>```

hope it solves your question.

ContentLicense: CC BY-SA 3.0

Body:
Current activity context can be obtained in the following simple way.

            Context currentContext=this;

hope it solves your question.


问:
How to query documents with null values MongoRepository Spring Data MongoDB
I couldn't initialise the value to be false in Spring Data MongoDB, so in my query, I want to search documents with field set to false or null.

The following snippet doesn't seem to work:

```<code>@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveFalseOrIsActiveNull(@Param("id"))
</code>```

答:
I'm not sure you can achieve such query using Spring data method name. Since your query will be evaluated as _id == "id" AND isActive == false OR isActive == null and not _id == "id" AND ( isActive == false OR isActive == null ).

If by chance isActive can only be true, false or null, you could try

```<code>@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveNot(@Param("id"), true)
</code>```

Otherwise, you will need to use other query method provided by Spring data mongodb such as MongoTemplate helper class or @Query annotation.

@Query annotation

```<code>@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
@Query("{$and: [{'_id': :#{#id}}, $or: [{ 'isActive':false}, {'isActive': null}]]}")
Order findByIdAndIsActiveNot(@Param("id"))
</code>```

Body:
I couldn't initialise the value to be false in Spring Data MongoDB, so in my query, I want to search documents with field set to false or null.

The following snippet doesn't seem to work:

@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveFalseOrIsActiveNull(@Param("id"))

Body:
I'm not sure you can achieve such query using Spring data method name. Since your query will be evaluated as _id == "id" AND isActive == false OR isActive == null and not _id == "id" AND ( isActive == false OR isActive == null ).

If by chance isActive can only be true, false or null, you could try

@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveNot(@Param("id"), true)

Otherwise, you will need to use other query method provided by Spring data mongodb such as MongoTemplate helper class or @Query annotation.

@Query annotation

@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
@Query("{$and: [{'_id': :#{#id}}, $or: [{ 'isActive':false}, {'isActive': null}]]}")
Order findByIdAndIsActiveNot(@Param("id"))


问:
How to locate element in selenium for href
I am trying to locate the element for this:

```<code><a ng-if="showLink && customer.partnerType == 2 && customer.isDirectCustomer" class="cp_text_link ng-binding ng-scope" ng-href="/?orgId=77bc101729ad844e39c4c1e17231c7e4&orgName=Attunix" href="/?orgId=77bc101729ad844e39c4c1e17231c7e4&orgName=ABC">
  ABC
</a>
</code>```

I tried the XPath and CssSelector but its unable to locate element.
Can someone pls help me locate the element
TIA

答:
The desired element is an Angular element so to locate and invoke click() on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Java based Locator Strategies:

partialLinkText:

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.partialLinkText("ABC"))).click();
</code>```

cssSelector:

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.cp_text_link.ng-binding.ng-scope[ng-href*='orgId'][href$='ABC']"))).click();
</code>```

xpath:

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='cp_text_link ng-binding ng-scope' and contains(@ng-href, 'orgId')][contains(@href, 'ABC')]"))).click();
</code>```

Body:
I am trying to locate the element for this:

  ABC

I tried the XPath and CssSelector but its unable to locate element.
Can someone pls help me locate the element
TIA

Body:
The desired element is an Angular element so to locate and invoke click() on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Java based Locator Strategies:

partialLinkText:

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.partialLinkText("ABC"))).click();

cssSelector:

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.cp_text_link.ng-binding.ng-scope[ng-href*='orgId'][href$='ABC']"))).click();

xpath:

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='cp_text_link ng-binding ng-scope' and contains(@ng-href, 'orgId')][contains(@href, 'ABC')]"))).click();


问:
How to deal with code coverage?
The other day we had a hard discussion between different developers and project leads, about code coverage tools and the use of the corresponding reports.

Do you use code coverage in your projects and if so, why not?

Is code coverage a fixed part of your builds or continous integration
or do you just use it from time to time?

How do you deal with the numbers derived from the reports?

答: The way to look at Code Coverage is to see how much is NOT covered and find out why it is not covered. Code coverage simply tells us that the lines of code is being hit when the unit tests are running. It does not tell us that the code works correctly or not. 100% code coverage is a good number but in medium/large projects it is very hard to achieve. </p>

ContentLicense: CC BY-SA 2.5

Title: How to deal with code coverage?

OwnerDisplayName: azamsharp


问:
Converting between windows and unix path with sed losses double slash
This command almost gives me what I want :-

```<code>echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
/123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

But as one can see, its lost the '//' at the beginning!

ie, desired outout :-

```<code>//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

What am I missing?

Edit: After not testing the basics of echo (many thanks to all who pointed that out). I should of also been more clear on the end-game of this question.

I want to use this in a script, and define the windows path at the top.

How can I echo the path to a tmp file for sed?

This obviously wont work :-

```<code>WIN_PATH="\\123.123.123.123\path1\1 - path2\path3 path4\path5"
UNIX_PATH=`echo $WIN_PATH | sed 's_\\_/_g' | sed 's_ _\\ _g'`
</code>```

答:
Your problem is that in \\ is already the escape secuence for \ so you have already lost one of the \ on the echo.
You can try just :

```<code>echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5"
</code>```

to see it.

You have to escape those \ to make it work i.e.:

```<code>echo "\\\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

Body:
This command almost gives me what I want :-

echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
/123.123.123.123/path1/1\ -\ path2/path3\ path4/path5

But as one can see, its lost the '//' at the beginning!

ie, desired outout :-

//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5

What am I missing?

Edit: After not testing the basics of echo (many thanks to all who pointed that out). I should of also been more clear on the end-game of this question.

I want to use this in a script, and define the windows path at the top.

How can I echo the path to a tmp file for sed?

This obviously wont work :-

WIN_PATH="\\123.123.123.123\path1\1 - path2\path3 path4\path5"
UNIX_PATH=`echo $WIN_PATH | sed 's_\\_/_g' | sed 's_ _\\ _g'`

Body:
Your problem is that in \\ is already the escape secuence for \ so you have already lost one of the \ on the echo.
You can try just :

echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5"

to see it.

You have to escape those \ to make it work i.e.:

echo "\\\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5


问:
Kubernetes storage on GCP: mapping values not allowed in this context error
I am trying to create a 10Gi disk on Google's Kubernetes Service and using their example file:

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
  name: task-pv-volume
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"
</code>```

I get the error:

```<code>$ kubectl apply -f pv-volume.yml
Error: error parsing pv-volume.yml error converting YAML to JSON: line 4: mapping values not allowed in this context
</code>```

Anyone know what I am doing wrong?

答:
I have pasted your yaml to GKE and everything looks ok. However, there are a few things which may caused this error.

1) A few days ago there was some gcloud updates, check if all components are up to date - gcloud components update

2) Typo in yaml (some TAB or enter). To make sure the file do not contains any whitespace download it directly from k8s.io

```<code>kubectl apply -f https://k8s.io/examples/pods/storage/pv-volume.yaml
persistentvolume/task-pv-volume created
</code>```

3) Vi formating issue.
The only way i was able to get the same issue was when i copied yaml code directly to vi without :set paste or i to turn on insert mode and then ctrl+v

But then yaml code looks like:

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
          name: task-pv-volume
            labels:
                        type: local
                        spec:
                                  storageClassName: manual
                                    capacity:
                                                storage: 10Gi
                                                  accessModes:
                                                              - ReadWriteOnce
                                                                  hostPath:
                                                                              path: "/mnt/data"
</code>```

===

Please let know if you still have issue while apply directly from k8s.io

Body:
I am trying to create a 10Gi disk on Google's Kubernetes Service and using their example file:

kind: PersistentVolume
apiVersion: v1
metadata:
  name: task-pv-volume
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"

I get the error:

$ kubectl apply -f pv-volume.yml
Error: error parsing pv-volume.yml error converting YAML to JSON: line 4: mapping values not allowed in this context

Anyone know what I am doing wrong?

Body:
I have pasted your yaml to GKE and everything looks ok. However, there are a few things which may caused this error.

1) A few days ago there was some gcloud updates, check if all components are up to date - gcloud components update

2) Typo in yaml (some TAB or enter). To make sure the file do not contains any whitespace download it directly from k8s.io

kubectl apply -f https://k8s.io/examples/pods/storage/pv-volume.yaml
persistentvolume/task-pv-volume created

3) Vi formating issue.
The only way i was able to get the same issue was when i copied yaml code directly to vi without :set paste or i to turn on insert mode and then ctrl+v

But then yaml code looks like:

kind: PersistentVolume
apiVersion: v1
metadata:
          name: task-pv-volume
            labels:
                        type: local
                        spec:
                                  storageClassName: manual
                                    capacity:
                                                storage: 10Gi
                                                  accessModes:
                                                              - ReadWriteOnce
                                                                  hostPath:
                                                                              path: "/mnt/data"

===

Please let know if you still have issue while apply directly from k8s.io


问:
How to install psycopg2 for django on mac
I have postgresql installed (with postgresql app). When I try "pip install psycopg2", i get "unable to execute gcc-4.2: No such file or directory. How to fix?</p>

答:
You can try this way. First, you should install PostgreSQL through brew.

```<code>    brew install postgresql
</code>```

Then you should add pg_config to PATH. You can find pg_config with.

```<code>    which pg_config
</code>```

Finally, install psycopg2 with pip.

```<code>    pip install psycopg2
</code>```

Body:
You can try this way. First, you should install PostgreSQL through brew.

    brew install postgresql

Then you should add pg_config to PATH. You can find pg_config with.

    which pg_config

Finally, install psycopg2 with pip.

    pip install psycopg2


问:
How to remove duplicate comma separated value in a single column in MySQL

```<code>SELECT id, country FROM my_records
</code>```

I've got the above result from MySQL query and i want to remove duplicate ID from the result.
Not with the help of PHP code but do with MySQL query. Is there any function or query to do the same.

Thanks

答:
The other solutions given are case insensitive, If you want result to be case sensitive and NOT remove accented matches like 'o' and 'ö', and looking for exact and strict match, here is the code

If utf8mb4_bin does not work, try utf8_bin or other binary types.

```<code>DELIMITER //

DROP FUNCTION IF EXISTS `find_duplicate_using_comma` //
CREATE FUNCTION `find_duplicate_using_comma` (in_str LONGTEXT) RETURNS LONGTEXT
DETERMINISTIC
NO SQL
BEGIN

DECLARE out_str LONGTEXT DEFAULT NULL; -- pending output
DECLARE next_str TEXT DEFAULT NULL;    -- next element under consideration

dedup:
LOOP

  IF CHAR_LENGTH(TRIM(in_str)) = 0 OR in_str IS NULL THEN
    LEAVE dedup; -- no more data to consider
  END IF;

  SET next_str = SUBSTRING_INDEX(in_str,',',1);                   -- find the next element
  SET in_str = SUBSTRING(in_str FROM (CHAR_LENGTH(next_str) + 1 + 1)); -- remove that element

  SET in_str = TRIM(in_str), next_str = TRIM(next_str); -- trim the new and the rest

  IF FIND_IN_SET(next_str collate utf8mb4_bin,out_str collate utf8mb4_bin) OR CHAR_LENGTH(next_str) = 0 THEN -- if empty or already found
    ITERATE dedup;
  END IF;

  SET out_str = CONCAT_WS(',',out_str,next_str); -- append the new to pending output

END LOOP;

RETURN out_str;

END //

DELIMITER ;
</code>```

Body:
SELECT id, country FROM my_records

I've got the above result from MySQL query and i want to remove duplicate ID from the result.
Not with the help of PHP code but do with MySQL query. Is there any function or query to do the same.

Thanks

Body:
The other solutions given are case insensitive, If you want result to be case sensitive and NOT remove accented matches like 'o' and 'ö', and looking for exact and strict match, here is the code

If utf8mb4_bin does not work, try utf8_bin or other binary types.

DELIMITER //

DROP FUNCTION IF EXISTS `find_duplicate_using_comma` //
CREATE FUNCTION `find_duplicate_using_comma` (in_str LONGTEXT) RETURNS LONGTEXT
DETERMINISTIC
NO SQL
BEGIN

DECLARE out_str LONGTEXT DEFAULT NULL; -- pending output
DECLARE next_str TEXT DEFAULT NULL;    -- next element under consideration

dedup:
LOOP

  IF CHAR_LENGTH(TRIM(in_str)) = 0 OR in_str IS NULL THEN
    LEAVE dedup; -- no more data to consider
  END IF;

  SET next_str = SUBSTRING_INDEX(in_str,',',1);                   -- find the next element
  SET in_str = SUBSTRING(in_str FROM (CHAR_LENGTH(next_str) + 1 + 1)); -- remove that element

  SET in_str = TRIM(in_str), next_str = TRIM(next_str); -- trim the new and the rest

  IF FIND_IN_SET(next_str collate utf8mb4_bin,out_str collate utf8mb4_bin) OR CHAR_LENGTH(next_str) = 0 THEN -- if empty or already found
    ITERATE dedup;
  END IF;

  SET out_str = CONCAT_WS(',',out_str,next_str); -- append the new to pending output

END LOOP;

RETURN out_str;

END //

DELIMITER ;


问:
How a defined method in delphi COM type library should be implemented, so it can return another COM object?
I am developing a COM Dll from existing Delphi legacy code to be used in C#.NET. I have added proper Interfaces to the Type Library and the COM server is successfully registered and objects can be seen and created from the C# environment.
However, some of the existing classes have customized Constructors which are necessary. So, I added a Helper class (also as a COM object) which contains methods which are supposed to construct and return other COM objects, but the return type is incompatible with the created object and the program crashes.

I am using COM object wizard and the code is pretty much generated by Delphi itself. For example, by defining a ISomeObject Interface, its corresponding CoClass named SomeObject and a Delphi class TSomeObject are generated. TSomeObject implements ISomeObject includes implementation of properties and methods. My intention is to create an instance of TSomeObject, using the Helper object and use it in C# environment.

The C# code that creates the Helper object and its method is as follows:

```<code>    Helper helper = new Helper;
    SomeObject = helper.CreateSomeObject(Param1, Param2);
</code>```

When I add a method with the return type set to SomeObject to the IHelper interface in Type Library, the following code (minus the body) is generated.

function THelper.CreateSomeObject(Param1, Param2): SomeObject
begin
    Result := TSomeProject.Create(Param1, Param2); //This line is not generated by COM Object Wizard
end;
```

The code above crashes with an error due to incompatibility.

While debugging, I realized that the type of Result is Pointer as ISomeObject. I have tried to Type Cast the output of TSomeProject.Create to SomeProject using as operand, which did not work.

The question is how can I return an instance of TSomeObject through a method which its return type is SomeObject.

答:
Change your method signature to return the interface rather than instance of SomeObject class. You can do that in type library editor like this:

The generated code would then be:

```<code>function THelper.CreateSomeObject: ISomeObject;
begin

end;
</code>```

Edit 1

As per comment: Although you've provided a lot of text in your question, it still lacks some essential information. You've mentioned some pointer operations, but that isn't something that you are supposed to deal with in a typical scenario when developing a COM server.

So I tried to re-create your scenario myself in Delphi 7 (oldest delphi version that I have installed). I created a COM server (ActiveX Library project in Delphi) similar to the one above. My implementation of method CreateSomeObject was:

```<code>function THelper.CreateSomeObject: ISomeObject;
begin
  Result := TSomeObject.Create;
end;
</code>```

Implementation of method TSomeObject.HelloWorld is unimportant. Then I registered the server via IDE function Run > Register ActiveX Server. After that I created sample console application in Delphi, imported type library (Project > Import Type Library) and added few lines of code to main program:

```<code>uses
  ActiveX, COMTest_TLB;

var
  _Helper: IHelper;
  _SomeObject: ISomeObject;
begin
  CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
  _Helper := CoHelper.Create;
  _SomeObject := _Helper.CreateSomeObject;
  _SomeObject.HelloWorld;
end.
</code>```

The console application ran to completion without a crash or unexpected result. So far so good. Then I created sample C#.NET console application (.NET 4.5.2) with reference to my COMTest library:

using System;
using COMTest;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var helper = new Helper();
        var someObject = helper.CreateSomeObject();
        someObject.HelloWorld();
    }
}
```

<p>And indeed the application was crashing with <code>AccessViolationException</code>. I quickly set up debugging of COM server by setting host application to .NET console application and enabling remote debug symbols in project's linker options (I'm sure you've figured that out already). Creation of <code>TSomeObject</code> instance went smoothly, but the assignment to <code>Result</code> failed.</p>

<p>There's some compiler magic when assigning value to a variable of managed type (interface in this case). It starts with clearing the destination which basically is a call to <code>_Release</code>, if the destination is not <code>nil</code>. And to my surprise in case of .NET console app client it wasn't! So I amended the implementation to:</p>

```function THelper.CreateSomeObject: ISomeObject;
begin
  Pointer(Result) := nil;
  Result := TSomeObject.Create;
end;
```

<p>Clearing the result before its first usage as interface did the trick. I haven't dug into detail on why that happens, but I will certainly do. I'll also check it with newer Delphi version and publish my findings in another edit of this answer.</p>

<p>Here you can find some great resources related to COM development in Delphi.
http://www.techvanguards.com/com/</p>

<p><em>Disclaimer: I'm not related to that site in any way, I just find it incredibly useful.</em></p>

<h2>Edit 2</h2>

<p>COM interface methods should return <code>HRESULT</code> by convention. That's the default mechanism in COM to report errors. Returning additional value(s) from a method should be implemented via parameters with <code>[Out]</code> modifier. Alternatively a parameter can be marked with [Out, RetVal] modifier (usually the last one) to indicate the return value of the method. Note that [Out] parameters are passed by reference, which you must indicate with additional asterisk (*) symbol appended to type name in type library editor. So <code>ISomeObject*</code> becomes <code>[Out] ISomeObject**</code>.</p>

<p>Delphi supports <code>safecall</code> calling convention and thus it can eliminate <code>HRESULT</code> return value from your method signature by wrapping any uncaught exception in your method and passing it back in EAX register allowing the [Out, RetVal] parameter to become the return value. But this is only supported for dual interfaces (see Flags tab of an interface) that are derived from <code>IDispatch</code>. To avoid implementing <code>IDispatch</code> methods you can convert your lightweight COM object to automation object (<code>TAutoObject</code>), if you haven't done that already. This can be achieved by selecting 'Automation Object' option instead of 'COM Object' when adding new item to your ActiveX library.</p>

<p>So this is how the method definition looks like when converted to <code>safecall</code>:
<img src="https://i.stack.imgur.com/f1GdV.png" alt="Type library editor"></p>

<p>And here's generated code with trivial implementation:</p>

```type
  THelper = class(TAutoObject, IHelper)
  protected
    function CreateSomeObject: ISomeObject; safecall;
  end;

function THelper.CreateSomeObject: ISomeObject;
begin
  Result := TSomeObject.Create;
end;
```

Body:
I am developing a COM Dll from existing Delphi legacy code to be used in C#.NET. I have added proper Interfaces to the Type Library and the COM server is successfully registered and objects can be seen and created from the C# environment.
However, some of the existing classes have customized Constructors which are necessary. So, I added a Helper class (also as a COM object) which contains methods which are supposed to construct and return other COM objects, but the return type is incompatible with the created object and the program crashes.

I am using COM object wizard and the code is pretty much generated by Delphi itself. For example, by defining a ISomeObject Interface, its corresponding CoClass named SomeObject and a Delphi class TSomeObject are generated. TSomeObject implements ISomeObject includes implementation of properties and methods. My intention is to create an instance of TSomeObject, using the Helper object and use it in C# environment.

The C# code that creates the Helper object and its method is as follows:

    Helper helper = new Helper;
    SomeObject = helper.CreateSomeObject(Param1, Param2);

When I add a method with the return type set to SomeObject to the IHelper interface in Type Library, the following code (minus the body) is generated.

function THelper.CreateSomeObject(Param1, Param2): SomeObject
begin
    Result := TSomeProject.Create(Param1, Param2); //This line is not generated by COM Object Wizard
end;

The code above crashes with an error due to incompatibility.

While debugging, I realized that the type of Result is Pointer as ISomeObject. I have tried to Type Cast the output of TSomeProject.Create to SomeProject using as operand, which did not work.

The question is how can I return an instance of TSomeObject through a method which its return type is SomeObject.

Body:
Change your method signature to return the interface rather than instance of SomeObject class. You can do that in type library editor like this:

The generated code would then be:

function THelper.CreateSomeObject: ISomeObject;
begin

end;

Edit 1

As per comment: Although you've provided a lot of text in your question, it still lacks some essential information. You've mentioned some pointer operations, but that isn't something that you are supposed to deal with in a typical scenario when developing a COM server.

So I tried to re-create your scenario myself in Delphi 7 (oldest delphi version that I have installed). I created a COM server (ActiveX Library project in Delphi) similar to the one above. My implementation of method CreateSomeObject was:

function THelper.CreateSomeObject: ISomeObject;
begin
  Result := TSomeObject.Create;
end;

Implementation of method TSomeObject.HelloWorld is unimportant. Then I registered the server via IDE function Run > Register ActiveX Server. After that I created sample console application in Delphi, imported type library (Project > Import Type Library) and added few lines of code to main program:

uses
  ActiveX, COMTest_TLB;

var
  _Helper: IHelper;
  _SomeObject: ISomeObject;
begin
  CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
  _Helper := CoHelper.Create;
  _SomeObject := _Helper.CreateSomeObject;
  _SomeObject.HelloWorld;
end.

The console application ran to completion without a crash or unexpected result. So far so good. Then I created sample C#.NET console application (.NET 4.5.2) with reference to my COMTest library:

using System;
using COMTest;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var helper = new Helper();
        var someObject = helper.CreateSomeObject();
        someObject.HelloWorld();
    }
}

And indeed the application was crashing with AccessViolationException. I quickly set up debugging of COM server by setting host application to .NET console application and enabling remote debug symbols in project's linker options (I'm sure you've figured that out already). Creation of TSomeObject instance went smoothly, but the assignment to Result failed.

There's some compiler magic when assigning value to a variable of managed type (interface in this case). It starts with clearing the destination which basically is a call to _Release, if the destination is not nil. And to my surprise in case of .NET console app client it wasn't! So I amended the implementation to:

function THelper.CreateSomeObject: ISomeObject;
begin
  Pointer(Result) := nil;
  Result := TSomeObject.Create;
end;

Clearing the result before its first usage as interface did the trick. I haven't dug into detail on why that happens, but I will certainly do. I'll also check it with newer Delphi version and publish my findings in another edit of this answer.

Here you can find some great resources related to COM development in Delphi.
http://www.techvanguards.com/com/

Disclaimer: I'm not related to that site in any way, I just find it incredibly useful.

Edit 2

COM interface methods should return HRESULT by convention. That's the default mechanism in COM to report errors. Returning additional value(s) from a method should be implemented via parameters with [Out] modifier. Alternatively a parameter can be marked with [Out, RetVal] modifier (usually the last one) to indicate the return value of the method. Note that [Out] parameters are passed by reference, which you must indicate with additional asterisk (*) symbol appended to type name in type library editor. So ISomeObject* becomes [Out] ISomeObject**.

Delphi supports safecall calling convention and thus it can eliminate HRESULT return value from your method signature by wrapping any uncaught exception in your method and passing it back in EAX register allowing the [Out, RetVal] parameter to become the return value. But this is only supported for dual interfaces (see Flags tab of an interface) that are derived from IDispatch. To avoid implementing IDispatch methods you can convert your lightweight COM object to automation object (TAutoObject), if you haven't done that already. This can be achieved by selecting 'Automation Object' option instead of 'COM Object' when adding new item to your ActiveX library.

So this is how the method definition looks like when converted to safecall:

And here's generated code with trivial implementation:

type
  THelper = class(TAutoObject, IHelper)
  protected
    function CreateSomeObject: ISomeObject; safecall;
  end;

function THelper.CreateSomeObject: ISomeObject;
begin
  Result := TSomeObject.Create;
end;


问:
Getting "Null" values for Aggregating the Data
I writing a query and getting the value

I have tried this on SQL Server 2012

```<code>;With CTE_ColorIndicator
AS
(
    select Name,Value,Report_Date,
    Dense_Rank() Over(Order by Report_Date DESC)Dno,
    (AVG(value)+(3*STDEV(value))) UpperLimit,
    (AVG(value)+(3*STDEV(value)))*0.85 Limit
    from #Temp1
    group by Name,value,Report_date
)

Select *
from CTE_ColorIndicator
where Dno <=90 and Dno > 7
</code>```

"I expected the aggregated values in the place of Upper-limit and limit columns"
"But the output is showing 'NULL' values in the upper-limit and limit columns"

答:
You are grouping by value.  Hence, the standard deviation is not defined.  I think you intend for the subquery to be:

```<code>select Name, Report_Date,
       Dense_Rank() Over (Order by Report_Date DESC) as Dno,
       (AVG(value) + 3 * STDEV(value)) as UpperLimit,
       (AVG(value) + 3 * STDEV(value)) * 0.85 as Limit
from #Temp1
group by Name, Report_date
</code>```

Body:
I writing a query and getting the value

I have tried this on SQL Server 2012

;With CTE_ColorIndicator
AS
(
    select Name,Value,Report_Date,
    Dense_Rank() Over(Order by Report_Date DESC)Dno,
    (AVG(value)+(3*STDEV(value))) UpperLimit,
    (AVG(value)+(3*STDEV(value)))*0.85 Limit
    from #Temp1
    group by Name,value,Report_date
)

Select *
from CTE_ColorIndicator
where Dno <=90 and Dno > 7

"I expected the aggregated values in the place of Upper-limit and limit columns"
"But the output is showing 'NULL' values in the upper-limit and limit columns"

Body:
You are grouping by value.  Hence, the standard deviation is not defined.  I think you intend for the subquery to be:

select Name, Report_Date,
       Dense_Rank() Over (Order by Report_Date DESC) as Dno,
       (AVG(value) + 3 * STDEV(value)) as UpperLimit,
       (AVG(value) + 3 * STDEV(value)) * 0.85 as Limit
from #Temp1
group by Name, Report_date


问:
Building docker images on slaves with cache
I have a continuous building system where docker images are being built after every commit. It is scalable and every build is on the separate slave. It works fine for small docker images, but for bigger ones, it takes sometimes hours to build a docker image for bigger projects, e.g. web apps. It is caused by lack of docker cache on slaves because they are dynamically created when building start

I wonder if there is some solution to share docker cache between those slave nodes? Have you ever encountered that problem?

EDIT

As recommended in answers I tried building with option --cache-from, but did not work, because every node calculates identical layers differently:

Here is a link to to comparison

Any ideas why docker calculates identical layers differently?

答:
Base principle: Build Once, Deploy Anywhere.

I understand you are building the image on different salves multiple times.

How about introducing "Image Repositories DTR or Docker-Hub" in middle.

Build the image once using one worker node and Push to Image Repositories.

Pull the image on remaining worker node.

This helps environment consistency as same image is getting used in all salves.

if you are willing to push image in docker-hub and pull back. Need to consider network latency, Before making decision.

We handled this problem with DTR, which is hosted in same network where I have other worker and pushing and pulling didn't take much time.

DTR: If security and image promotions can be other concerns,Then can be well handled with this approach by creating image promotion criteria.

PS: This answer will be improved based on question clarifications


问:
How to concatenate multiple data frames with long index without error?
I have a directory ".../dados" in which have multiple subdirectories whose names are a serial number plus some useless information - e.g. "17448_2017_Jul_2017_Oct", where the first number on it is the serial number. Inside each subdirectory, I have four ".txt" files whose lines/rows have the information of date and time, and an attribute of a certain type, say humidity, all named the same way in each subdirectory - e.g. "2019-01-29 03:11:26 54.7".

I want to concatenate all of them in order to generate a dataset with date index.

```<code>path = "/.../dados/"

df = pd.DataFrame()

for fld in os.listdir(path):
    subfld = path + fld
    if os.path.isdir(subfld):
        aux = pd.DataFrame()
        sn = fld.split('_')[0]
        for file in os.listdir(subfld):
            filepath = os.path.join(subfld, file)
            if os.path.isfile(filepath):
                new_col = pd.read_fwf(filepath, colspecs=[(0, 19), (20, -1)], skiprows=8, names=[file.split('_')[2][:-4]], parse_dates=[0], nrows=9999999)
                aux = pd.concat([aux, new_col], axis=1,  sort=False)
        aux['Machine'] = sn
        df = df.append(aux)
</code>```

This is a print of df.head(10):

```<code>HumTechRoom  TempTechRoom  TempExamRoom  HumExamRoom Machine
2018-03-04 00:45:11         82.6           NaN           NaN          NaN   22162
2018-03-04 00:45:47         80.0           NaN           NaN          NaN   22162
2018-03-04 00:45:53         78.0           NaN           NaN          NaN   22162
2018-03-04 00:46:04         75.9           NaN           NaN          NaN   22162
2018-03-04 00:46:20         73.7           NaN           NaN         51.3   22162
2018-03-04 00:46:58         71.7           NaN           NaN          NaN   22162
2018-03-04 00:47:40          NaN           NaN           NaN         53.4   22162
2018-03-04 00:47:41          NaN          14.5           NaN          NaN   22162
2018-03-04 00:47:54         74.3           NaN           NaN          NaN   22162
2018-03-04 00:47:59         76.6           NaN           NaN          NaN   22162
</code>```

THis is the error message that I get:

```<code>...
line 31, in <module>
    aux = pd.concat([aux, new_col], axis=1,  sort=False)

  File ".../concat.py", line 226, in concat
    return op.get_result()

  File ".../concat.py", line 423, in get_result
    copy=self.copy)

  File ".../internals.py", line 5425, in concatenate_block_managers
    return BlockManager(blocks, axes)

  File ".../internals.py", line 3282, in __init__
    self._verify_integrity()

  File ".../internals.py", line 3493, in _verify_integrity
    construction_error(tot_items, block.shape[1:], self.axes)

  File ".../internals.py", line 4843, in construction_error
    passed, implied))

ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)
</code>```

答:
It seems that you are using pd.concat over the wrong axis. Remove axis=1 out of your pd.concat.. line, since axis=0 is the default as can be found in the docs

Just for your convencience. To get a cleaner dataframe, use ignore_index=True as well:

```<code>aux = pd.concat([aux, new_col], ignore_index=True,  sort=False)
</code>```

Which gives a reset index back.

Body:
I have a directory ".../dados" in which have multiple subdirectories whose names are a serial number plus some useless information - e.g. "17448_2017_Jul_2017_Oct", where the first number on it is the serial number. Inside each subdirectory, I have four ".txt" files whose lines/rows have the information of date and time, and an attribute of a certain type, say humidity, all named the same way in each subdirectory - e.g. "2019-01-29 03:11:26 54.7".

I want to concatenate all of them in order to generate a dataset with date index.

path = "/.../dados/"

df = pd.DataFrame()

for fld in os.listdir(path):
    subfld = path + fld
    if os.path.isdir(subfld):
        aux = pd.DataFrame()
        sn = fld.split('_')[0]
        for file in os.listdir(subfld):
            filepath = os.path.join(subfld, file)
            if os.path.isfile(filepath):
                new_col = pd.read_fwf(filepath, colspecs=[(0, 19), (20, -1)], skiprows=8, names=[file.split('_')[2][:-4]], parse_dates=[0], nrows=9999999)
                aux = pd.concat([aux, new_col], axis=1,  sort=False)
        aux['Machine'] = sn
        df = df.append(aux)

This is a print of df.head(10):

HumTechRoom  TempTechRoom  TempExamRoom  HumExamRoom Machine
2018-03-04 00:45:11         82.6           NaN           NaN          NaN   22162
2018-03-04 00:45:47         80.0           NaN           NaN          NaN   22162
2018-03-04 00:45:53         78.0           NaN           NaN          NaN   22162
2018-03-04 00:46:04         75.9           NaN           NaN          NaN   22162
2018-03-04 00:46:20         73.7           NaN           NaN         51.3   22162
2018-03-04 00:46:58         71.7           NaN           NaN          NaN   22162
2018-03-04 00:47:40          NaN           NaN           NaN         53.4   22162
2018-03-04 00:47:41          NaN          14.5           NaN          NaN   22162
2018-03-04 00:47:54         74.3           NaN           NaN          NaN   22162
2018-03-04 00:47:59         76.6           NaN           NaN          NaN   22162

THis is the error message that I get:

...
line 31, in <module>
    aux = pd.concat([aux, new_col], axis=1,  sort=False)

  File ".../concat.py", line 226, in concat
    return op.get_result()

  File ".../concat.py", line 423, in get_result
    copy=self.copy)

  File ".../internals.py", line 5425, in concatenate_block_managers
    return BlockManager(blocks, axes)

  File ".../internals.py", line 3282, in __init__
    self._verify_integrity()

  File ".../internals.py", line 3493, in _verify_integrity
    construction_error(tot_items, block.shape[1:], self.axes)

  File ".../internals.py", line 4843, in construction_error
    passed, implied))

ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)

Body:
It seems that you are using pd.concat over the wrong axis. Remove axis=1 out of your pd.concat.. line, since axis=0 is the default as can be found in the docs

Just for your convencience. To get a cleaner dataframe, use ignore_index=True as well:

aux = pd.concat([aux, new_col], ignore_index=True,  sort=False)

Which gives a reset index back.


问:
LINQ side effects
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

```<code>List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);
</code>```

To:

```<code>List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);
</code>```

答:
For any IEnumerable, you can do:

```<code>items.Any(item =>
{
    Console.WriteLine(item);
    return false;
}
</code>```

But this would be utterly wrong! It's like using a shoe to hammer the nail.
Semantically, it does not make sense.

Title: LINQ side effects

Body:
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);

To:

List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);

Body:
For any IEnumerable, you can do:

items.Any(item =>
{
    Console.WriteLine(item);
    return false;
}

But this would be utterly wrong! It's like using a shoe to hammer the nail.
Semantically, it does not make sense.


问:
Measure the size of a box or object on a fixed size platform
I have a web cam mounted over a table.  I know the exact size/measurements of the table and it won't change.

I want to be able to place a box or similar object onto the table, and then determine the size/dimensions of the item I just placed on the table.

Any tips or ideas on how I could do this ?

I tried using a 3d computer vision camera, but the environmental conditions required are to hard to achieve in the real world, and at best the measure measurement it was returned where random, and never consistent. If anybody knows of a good CV solution that is solid and robust that might also do the trick. (perhaps I just bought a crap solution)

答:
i think you can do it with OpenCV they have an sdk which i worked with a long time ago, check this: https://www.pyimagesearch.com/2016/03/28/measuring-size-of-objects-in-an-image-with-opencv/

Get "Emgu CV" the .Net wrapper here: http://www.emgu.com/wiki/index.php/Main_Page


问:
App keeps crashing when push notification is sent from firebase
I am unable to send notifications to my app from firebase, as it crashes everytime i do so

It previously showed error for latest versions of the firebase_messaging plugin, so i kept it empty so that the ide will get the latest packages.

These are my dependencies in pubspec.yaml file

```<code>dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  #firebase_auth: ^0.10.0+1
  #firebase_core: ^0.4.0
  firebase_database: ^3.0.0
  firebase_messaging:
dev_dependencies:
</code>```

My code for the push notifications is as follows:

```<code>firebaseMessaging.getToken().then((token){
      print("Token: $token");
    });

    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print('on message $message');
        final notification=message['notification'];
        setState(() {
          messages.add(Message(
              title: notification['title'],body: notification['body']
          ));
        });
      },
      onResume: (Map<String, dynamic> message) async {
        print('on resume $message');
      },
      onLaunch: (Map<String, dynamic> message) async {
        print('on launch $message');
      },
    );
</code>```

This the logcat summary when i run my program:

```<code> Syncing files to device SM G960F...
    D/ViewRootImpl@df42dca[MainActivity](21660): MSG_WINDOW_FOCUS_CHANGED 1 1
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    V/InputMethodManager(21660): Starting input: tba=com.kashyap.user_admin ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
    D/InputMethodManager(21660): startInputInner - Id : 0
    I/InputMethodManager(21660): startInputInner - mService.startInputOrWindowGainedFocus
    D/InputTransport(21660): Input channel constructed: fd=105
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    V/InputMethodManager(21660): Starting input: tba=com.kashyap.user_admin ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
    D/InputMethodManager(21660): startInputInner - Id : 0
    D/ViewRootImpl@df42dca[MainActivity](21660): ViewPostIme pointer 0
    D/ViewRootImpl@df42dca[MainActivity](21660): ViewPostIme pointer 1
    D/ViewRootImpl@df42dca[MainActivity](21660): MSG_WINDOW_FOCUS_CHANGED 0 1
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    D/SurfaceView(21660): windowStopped(true) false 7c74c04 of ViewRootImpl@df42dca[MainActivity]
    D/SurfaceView(21660): show() Surface(name=SurfaceView - com.kashyap.user_admin/com.kashyap.user_admin.MainActivity@7c74c04@0[21660])/@0x81cc5ed io.flutter.view.FlutterView{7c74c04 VFE...... ........ 0,0-1440,2960}
    D/SurfaceView(21660): surfaceDestroyed callback.size 1 #1 io.flutter.view.FlutterView{7c74c04 VFE...... ........ 0,0-1440,2960}
    W/libEGL  (21660): EGLNativeWindowType 0x72580fe010 disconnect failed
    D/SurfaceView(21660): destroy() Surface(name=SurfaceView - com.kashyap.user_admin/com.kashyap.user_admin.MainActivity@7c74c04@0[21660])/@0x81cc5ed io.flutter.view.FlutterView{7c74c04 VFE...... ........ 0,0-1440,2960}
    D/SurfaceView(21660): onWindowVisibilityChanged(4) false 7c74c04 of ViewRootImpl@df42dca[MainActivity]
    W/libEGL  (21660): EGLNativeWindowType 0x726fef2010 disconnect failed
    D/OpenGLRenderer(21660): eglDestroySurface = 0x7266249a00, 0x726fef2000
    D/ViewRootImpl@df42dca[MainActivity](21660): Relayout returned: old=[0,0][1440,2960] new=[0,0][1440,2960] result=0x5 surface={valid=false 0} changed=true
    D/InputTransport(21660): Input channel destroyed: fd=105
    D/SurfaceView(21660): onWindowVisibilityChanged(8) false 7c74c04 of ViewRootImpl@df42dca[MainActivity]
    D/ViewRootImpl@df42dca[MainActivity](21660): Relayout returned: old=[0,0][1440,2960] new=[0,0][1440,2960] result=0x1 surface={valid=false 0} changed=false
    I/hyap.user_admi(21660): Rejecting re-init on previously-failed class java.lang.Class<com.google.firebase.messaging.FirebaseMessagingService>: java.lang.IllegalAccessError: Class com.google.firebase.iid.zzb extended by class com.google.firebase.messaging.FirebaseMessagingService is inaccessible (declaration of 'com.google.firebase.messaging.FirebaseMessagingService' appears in /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!classes2.dex)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at android.app.Service android.app.AppComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (AppComponentFactory.java:103)
    I/hyap.user_admi(21660):   at android.app.Service androidx.core.app.CoreComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (CoreComponentFactory.java:68)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3710)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.access$1400(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:235)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1784)
    I/hyap.user_admi(21660):   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
    I/hyap.user_admi(21660):   at void android.os.Looper.loop() (Looper.java:214)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6981)
    I/hyap.user_admi(21660):   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
    I/hyap.user_admi(21660):   at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:493)
    I/hyap.user_admi(21660):   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1445)
    I/hyap.user_admi(21660):
    I/hyap.user_admi(21660): Rejecting re-init on previously-failed class java.lang.Class<io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService>: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at android.app.Service android.app.AppComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (AppComponentFactory.java:103)
    I/hyap.user_admi(21660):   at android.app.Service androidx.core.app.CoreComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (CoreComponentFactory.java:68)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3710)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.access$1400(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:235)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1784)
    I/hyap.user_admi(21660):   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
    I/hyap.user_admi(21660):   at void android.os.Looper.loop() (Looper.java:214)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6981)
    I/hyap.user_admi(21660):   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
    I/hyap.user_admi(21660):   at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:493)
    I/hyap.user_admi(21660):   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1445)
    I/hyap.user_admi(21660): Caused by: java.lang.ClassNotFoundException: com.google.firebase.messaging.FirebaseMessagingService
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at android.app.Service android.app.AppComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (AppComponentFactory.java:103)
    I/hyap.user_admi(21660):   at android.app.Service androidx.core.app.CoreComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (CoreComponentFactory.java:68)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3710)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.access$1400(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:235)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1784)
    I/hyap.user_admi(21660):   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
    I/hyap.user_admi(21660):   at void android.os.Looper.loop() (Looper.java:214)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6981)
    I/hyap.user_admi(21660):   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
    I/hyap.user_admi(21660):   at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:493)
    I/hyap.user_admi(21660):   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1445)
    I/hyap.user_admi(21660):
    D/AndroidRuntime(21660): Shutting down VM
    E/AndroidRuntime(21660): FATAL EXCEPTION: main
    E/AndroidRuntime(21660): Process: com.kashyap.user_admin, PID: 21660
    E/AndroidRuntime(21660): java.lang.RuntimeException: Unable to instantiate service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk"],nativeLibraryDirectories=[/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/lib/arm64, /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!/lib/arm64-v8a, /system/lib64]]
    E/AndroidRuntime(21660):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3715)
    E/AndroidRuntime(21660):    at android.app.ActivityThread.access$1400(ActivityThread.java:235)
    E/AndroidRuntime(21660):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1784)
    E/AndroidRuntime(21660):    at android.os.Handler.dispatchMessage(Handler.java:106)
    E/AndroidRuntime(21660):    at android.os.Looper.loop(Looper.java:214)
    E/AndroidRuntime(21660):    at android.app.ActivityThread.main(ActivityThread.java:6981)
    E/AndroidRuntime(21660):    at java.lang.reflect.Method.invoke(Native Method)
    E/AndroidRuntime(21660):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    E/AndroidRuntime(21660):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
    E/AndroidRuntime(21660): Caused by: java.lang.ClassNotFoundException: Didn't find class "io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk"],nativeLibraryDirectories=[/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/lib/arm64, /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!/lib/arm64-v8a, /system/lib64]]
    E/AndroidRuntime(21660):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    E/AndroidRuntime(21660):    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    E/AndroidRuntime(21660):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    E/AndroidRuntime(21660):    at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:103)
    E/AndroidRuntime(21660):    at androidx.core.app.CoreComponentFactory.instantiateService(CoreComponentFactory.java:68)
    E/AndroidRuntime(21660):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3710)
    E/AndroidRuntime(21660):    ... 8 more
    E/AndroidRuntime(21660):    Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
    E/AndroidRuntime(21660):        at java.lang.VMClassLoader.findLoadedClass(Native Method)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
    E/AndroidRuntime(21660):        ... 12 more
    E/AndroidRuntime(21660):    Caused by: java.lang.ClassNotFoundException: com.google.firebase.messaging.FirebaseMessagingService
    E/AndroidRuntime(21660):        at java.lang.VMClassLoader.findLoadedClass(Native Method)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    E/AndroidRuntime(21660):        ... 15 more
    E/AndroidRuntime(21660):    Caused by: java.lang.IllegalAccessError: Class com.google.firebase.iid.zzb extended by class com.google.firebase.messaging.FirebaseMessagingService is inaccessible (declaration of 'com.google.firebase.messaging.FirebaseMessagingService' appears in /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!classes2.dex)
    E/AndroidRuntime(21660):        ... 15 more
    I/Process (21660): Sending signal. PID: 21660 SIG: 9
    Lost connection to device.
</code>```

答:
This GitHub issue/comment suggests you need to pay very close attention to the plugin versions you are using. This means you'll also have to keep the platform specific dependencies updated as well (this for Android).

From the Firebase docs:

```<code>app/build.gradle:
implementation 'com.google.firebase:firebase-messaging:18.0.0'
</code>```

Body:
I am unable to send notifications to my app from firebase, as it crashes everytime i do so

It previously showed error for latest versions of the firebase_messaging plugin, so i kept it empty so that the ide will get the latest packages.

These are my dependencies in pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  #firebase_auth: ^0.10.0+1
  #firebase_core: ^0.4.0
  firebase_database: ^3.0.0
  firebase_messaging:
dev_dependencies:

My code for the push notifications is as follows:

firebaseMessaging.getToken().then((token){
      print("Token: $token");
    });

    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print('on message $message');
        final notification=message['notification'];
        setState(() {
          messages.add(Message(
              title: notification['title'],body: notification['body']
          ));
        });
      },
      onResume: (Map<String, dynamic> message) async {
        print('on resume $message');
      },
      onLaunch: (Map<String, dynamic> message) async {
        print('on launch $message');
      },
    );

This the logcat summary when i run my program:

 Syncing files to device SM G960F...
    D/ViewRootImpl@df42dca[MainActivity](21660): MSG_WINDOW_FOCUS_CHANGED 1 1
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    V/InputMethodManager(21660): Starting input: tba=com.kashyap.user_admin ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
    D/InputMethodManager(21660): startInputInner - Id : 0
    I/InputMethodManager(21660): startInputInner - mService.startInputOrWindowGainedFocus
    D/InputTransport(21660): Input channel constructed: fd=105
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    V/InputMethodManager(21660): Starting input: tba=com.kashyap.user_admin ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
    D/InputMethodManager(21660): startInputInner - Id : 0
    D/ViewRootImpl@df42dca[MainActivity](21660): ViewPostIme pointer 0
    D/ViewRootImpl@df42dca[MainActivity](21660): ViewPostIme pointer 1
    D/ViewRootImpl@df42dca[MainActivity](21660): MSG_WINDOW_FOCUS_CHANGED 0 1
    D/InputMethodManager(21660): prepareNavigationBarInfo() DecorView@b273b3b[MainActivity]
    D/InputMethodManager(21660): getNavigationBarColor() -855310
    D/SurfaceView(21660): windowStopped(true) false 7c74c04 of ViewRootImpl@df42dca[MainActivity]
    D/SurfaceView(21660): show() Surface(name=SurfaceView - com.kashyap.user_admin/com.kashyap.user_admin.MainActivity@7c74c04@0[21660])/@0x81cc5ed io.flutter.view.FlutterView{7c74c04 VFE...... ........ 0,0-1440,2960}
    D/SurfaceView(21660): surfaceDestroyed callback.size 1 #1 io.flutter.view.FlutterView{7c74c04 VFE...... ........ 0,0-1440,2960}
    W/libEGL  (21660): EGLNativeWindowType 0x72580fe010 disconnect failed
    D/SurfaceView(21660): destroy() Surface(name=SurfaceView - com.kashyap.user_admin/com.kashyap.user_admin.MainActivity@7c74c04@0[21660])/@0x81cc5ed io.flutter.view.FlutterView{7c74c04 VFE...... ........ 0,0-1440,2960}
    D/SurfaceView(21660): onWindowVisibilityChanged(4) false 7c74c04 of ViewRootImpl@df42dca[MainActivity]
    W/libEGL  (21660): EGLNativeWindowType 0x726fef2010 disconnect failed
    D/OpenGLRenderer(21660): eglDestroySurface = 0x7266249a00, 0x726fef2000
    D/ViewRootImpl@df42dca[MainActivity](21660): Relayout returned: old=[0,0][1440,2960] new=[0,0][1440,2960] result=0x5 surface={valid=false 0} changed=true
    D/InputTransport(21660): Input channel destroyed: fd=105
    D/SurfaceView(21660): onWindowVisibilityChanged(8) false 7c74c04 of ViewRootImpl@df42dca[MainActivity]
    D/ViewRootImpl@df42dca[MainActivity](21660): Relayout returned: old=[0,0][1440,2960] new=[0,0][1440,2960] result=0x1 surface={valid=false 0} changed=false
    I/hyap.user_admi(21660): Rejecting re-init on previously-failed class java.lang.Class<com.google.firebase.messaging.FirebaseMessagingService>: java.lang.IllegalAccessError: Class com.google.firebase.iid.zzb extended by class com.google.firebase.messaging.FirebaseMessagingService is inaccessible (declaration of 'com.google.firebase.messaging.FirebaseMessagingService' appears in /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!classes2.dex)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at android.app.Service android.app.AppComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (AppComponentFactory.java:103)
    I/hyap.user_admi(21660):   at android.app.Service androidx.core.app.CoreComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (CoreComponentFactory.java:68)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3710)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.access$1400(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:235)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1784)
    I/hyap.user_admi(21660):   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
    I/hyap.user_admi(21660):   at void android.os.Looper.loop() (Looper.java:214)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6981)
    I/hyap.user_admi(21660):   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
    I/hyap.user_admi(21660):   at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:493)
    I/hyap.user_admi(21660):   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1445)
    I/hyap.user_admi(21660):
    I/hyap.user_admi(21660): Rejecting re-init on previously-failed class java.lang.Class<io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService>: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at android.app.Service android.app.AppComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (AppComponentFactory.java:103)
    I/hyap.user_admi(21660):   at android.app.Service androidx.core.app.CoreComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (CoreComponentFactory.java:68)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3710)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.access$1400(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:235)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1784)
    I/hyap.user_admi(21660):   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
    I/hyap.user_admi(21660):   at void android.os.Looper.loop() (Looper.java:214)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6981)
    I/hyap.user_admi(21660):   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
    I/hyap.user_admi(21660):   at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:493)
    I/hyap.user_admi(21660):   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1445)
    I/hyap.user_admi(21660): Caused by: java.lang.ClassNotFoundException: com.google.firebase.messaging.FirebaseMessagingService
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String) (VMClassLoader.java:-2)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) (ClassLoader.java:738)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:363)
    I/hyap.user_admi(21660):   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
    I/hyap.user_admi(21660):   at android.app.Service android.app.AppComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (AppComponentFactory.java:103)
    I/hyap.user_admi(21660):   at android.app.Service androidx.core.app.CoreComponentFactory.instantiateService(java.lang.ClassLoader, java.lang.String, android.content.Intent) (CoreComponentFactory.java:68)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3710)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.access$1400(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:235)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1784)
    I/hyap.user_admi(21660):   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
    I/hyap.user_admi(21660):   at void android.os.Looper.loop() (Looper.java:214)
    I/hyap.user_admi(21660):   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6981)
    I/hyap.user_admi(21660):   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
    I/hyap.user_admi(21660):   at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:493)
    I/hyap.user_admi(21660):   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1445)
    I/hyap.user_admi(21660):
    D/AndroidRuntime(21660): Shutting down VM
    E/AndroidRuntime(21660): FATAL EXCEPTION: main
    E/AndroidRuntime(21660): Process: com.kashyap.user_admin, PID: 21660
    E/AndroidRuntime(21660): java.lang.RuntimeException: Unable to instantiate service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk"],nativeLibraryDirectories=[/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/lib/arm64, /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!/lib/arm64-v8a, /system/lib64]]
    E/AndroidRuntime(21660):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3715)
    E/AndroidRuntime(21660):    at android.app.ActivityThread.access$1400(ActivityThread.java:235)
    E/AndroidRuntime(21660):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1784)
    E/AndroidRuntime(21660):    at android.os.Handler.dispatchMessage(Handler.java:106)
    E/AndroidRuntime(21660):    at android.os.Looper.loop(Looper.java:214)
    E/AndroidRuntime(21660):    at android.app.ActivityThread.main(ActivityThread.java:6981)
    E/AndroidRuntime(21660):    at java.lang.reflect.Method.invoke(Native Method)
    E/AndroidRuntime(21660):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    E/AndroidRuntime(21660):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
    E/AndroidRuntime(21660): Caused by: java.lang.ClassNotFoundException: Didn't find class "io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk"],nativeLibraryDirectories=[/data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/lib/arm64, /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!/lib/arm64-v8a, /system/lib64]]
    E/AndroidRuntime(21660):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    E/AndroidRuntime(21660):    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    E/AndroidRuntime(21660):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    E/AndroidRuntime(21660):    at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:103)
    E/AndroidRuntime(21660):    at androidx.core.app.CoreComponentFactory.instantiateService(CoreComponentFactory.java:68)
    E/AndroidRuntime(21660):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3710)
    E/AndroidRuntime(21660):    ... 8 more
    E/AndroidRuntime(21660):    Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
    E/AndroidRuntime(21660):        at java.lang.VMClassLoader.findLoadedClass(Native Method)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
    E/AndroidRuntime(21660):        ... 12 more
    E/AndroidRuntime(21660):    Caused by: java.lang.ClassNotFoundException: com.google.firebase.messaging.FirebaseMessagingService
    E/AndroidRuntime(21660):        at java.lang.VMClassLoader.findLoadedClass(Native Method)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
    E/AndroidRuntime(21660):        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    E/AndroidRuntime(21660):        ... 15 more
    E/AndroidRuntime(21660):    Caused by: java.lang.IllegalAccessError: Class com.google.firebase.iid.zzb extended by class com.google.firebase.messaging.FirebaseMessagingService is inaccessible (declaration of 'com.google.firebase.messaging.FirebaseMessagingService' appears in /data/app/com.kashyap.user_admin-P6LJr-bNg8zLx2ZhadHMPA==/base.apk!classes2.dex)
    E/AndroidRuntime(21660):        ... 15 more
    I/Process (21660): Sending signal. PID: 21660 SIG: 9
    Lost connection to device.

Body:
This GitHub issue/comment suggests you need to pay very close attention to the plugin versions you are using. This means you'll also have to keep the platform specific dependencies updated as well (this for Android).

From the Firebase docs:

app/build.gradle:
implementation 'com.google.firebase:firebase-messaging:18.0.0'


问:
Can i change the text "view project" on button with javascript or jquery?
I would like to change the text "view project" of button at this page:
https://new.emanuelemarazzi.com/pacchetti-creativi/

If you see the code there is a span under a class.

I tried to use jQuery with this code:

```<code>$('.button-style5 span').text('Text changed');
</code>```

答: Seems like your Solution is working

Body:
I would like to change the text "view project" of button at this page:
https://new.emanuelemarazzi.com/pacchetti-creativi/

If you see the code there is a span under a class.

I tried to use jQuery with this code:

$('.button-style5 span').text('Text changed');

Body: Seems like your Solution is working


问:
Java 8 predicates using methods bodies are called only once?
I have examined the following snippet:

```<code>public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> computed = new ConcurrentHashMap<>();/*IS THIS LINE CALLED ONCE ON STREAM->FILTER NOT MATTER HOW LONG THE STREAM IS*/
    return t -> {return computed.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;};
}

private void test(){
    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
    System.out.println("d = " + d);
}
</code>```

This code is not mine. I know that using a ConcurrentMap is not the right choice in this example and I should use ConcurrentMap instead of Map in this case, but this is not my concern now.

I thought that the distinctByKey method is called or interpreted in each iteration of the Stream. I mean the Map being instantiated in each turn, but it's not!

Is the body of the Predicate method called only once?

In the Stream iteration, is this an assertion?

Because when I try the following code:

```<code>final Function<String,Integer>a = (name)->name.length();
System.out.println(distinctByKey(a).test("JOHN"));
System.out.println(distinctByKey(a).test("STEPHEN"));
System.out.println(distinctByKey(a).test("ORTIZ"));
System.out.println(distinctByKey(a).test("RONDON"));
</code>```

I can see that the body of the method is indeed called in each line. What makes the body of the filter to only be called once?

答: distinctByKey returns a single instance of the Predicate that caches the ConcurrentHashMap. You could achieve almost the same thing if you replace the creation of the Predicate via the lambda with an anonymous inner class for example.

Body:
I have examined the following snippet:

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> computed = new ConcurrentHashMap<>();/*IS THIS LINE CALLED ONCE ON STREAM->FILTER NOT MATTER HOW LONG THE STREAM IS*/
    return t -> {return computed.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;};
}

private void test(){
    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
    System.out.println("d = " + d);
}

This code is not mine. I know that using a ConcurrentMap is not the right choice in this example and I should use ConcurrentMap instead of Map in this case, but this is not my concern now.

I thought that the distinctByKey method is called or interpreted in each iteration of the Stream. I mean the Map being instantiated in each turn, but it's not!

Is the body of the Predicate method called only once?

In the Stream iteration, is this an assertion?

Because when I try the following code:

final Function<String,Integer>a = (name)->name.length();
System.out.println(distinctByKey(a).test("JOHN"));
System.out.println(distinctByKey(a).test("STEPHEN"));
System.out.println(distinctByKey(a).test("ORTIZ"));
System.out.println(distinctByKey(a).test("RONDON"));

I can see that the body of the method is indeed called in each line. What makes the body of the filter to only be called once?