问:
How to set a Number field with a different Number type using Java Reflection
Our original code is something like:

```<code>Object bean = ...
Field field = ...
Object value = ... // Retrieved from Database
field.set(bean, value);
</code>```

But the type of bean field may be different from type of value, e.g. our bean is an Integer but value retrieved from db may be Byte or Short.

How can I write some simple code to convert boxed types without reflection exception?

Here is my solution but not as simple as my expectation:

```<code>if (field.getType().equals(Integer.class)) {
   field.set(bean, Integer.valueOf(((Number) value).intValue()));
} else if (field.getType().equals(Short.class)) {
   field.set(bean, Short.valueOf(((Number) value).shortValue()));
} else if (...) {
   ...
}
</code>```

答:
There’s no way to handle these conversion generically unless you add even more Reflection.

The best you can do, is to make these required expressions more maintainable. One thing to consider, is that with your expressions like, e.g. Short.valueOf(((Number) value).shortValue()), the valueOf invocation is unnecessary. That’s what auto-boxing does anyway.

Then, you can do with recent Java versions:

```<code>static final Map<Class<?>,Setter> SETTERS =Map.copyOf(Map.<Class<?>,NumericSetter>ofEntries(
    Map.entry(byte.class, (field,bean,n) -> field.setByte(bean, n.byteValue())),
    Map.entry(short.class, (field,bean,n) -> field.setShort(bean, n.shortValue())),
    Map.entry(int.class, (field,bean,n) -> field.setInt(bean, n.intValue())),
    Map.entry(long.class, (field,bean,n) -> field.setLong(bean, n.longValue())),
    Map.entry(float.class, (field,bean,n) -> field.setFloat(bean, n.floatValue())),
    Map.entry(double.class, (field,bean,n) -> field.setDouble(bean, n.doubleValue())),
    Map.entry(Byte.class, (field,bean,n) -> field.set(bean, n.byteValue())),
    Map.entry(Short.class, (field,bean,n) -> field.set(bean, n.shortValue())),
    Map.entry(Integer.class, (field,bean,n) -> field.set(bean, n.intValue())),
    Map.entry(Long.class, (field,bean,n) -> field.set(bean, n.longValue())),
    Map.entry(Float.class, (field,bean,n) -> field.set(bean, n.floatValue())),
    Map.entry(Double.class, (field,bean,n) -> field.set(bean, n.doubleValue()))
));
interface Setter {
    void set(Field field, Object bean, Object value) throws IllegalAccessException;
    Setter FALLBACK = Field::set;
}
interface NumericSetter extends Setter {
    @Override default void set(Field field, Object bean, Object value)
    throws IllegalAccessException {
        setNumeric(field, bean, (Number)value);
    }
    void setNumeric(Field f, Object bean, Number n) throws IllegalAccessException;
}
</code>```

To handle all numeric field types, whether primitive or boxed. This can be use like

```<code>SETTERS.getOrDefault(field.getType(), Setter.FALLBACK).set(field, bean, value);
</code>```

to use one of the numeric conversions if applicable or just use the set method without transformations otherwise. The latter would also throw the appropriate exception for mismatching types.

For older Java versions you could consider something like

```<code>static boolean setNumeric(Field field, Object bean, Object value)
throws IllegalAccessException {
    if(!(value instanceof Number)) return false;
    Number n = (Number)value;
    Class<?> type = field.getType();
    if(type.isPrimitive()) {
        if(type == boolean.class || type == char.class) return false;
        switch(type.getName().charAt(0)) {
            case 'b': field.setByte(bean, n.byteValue()); break;
            case 's': field.setShort(bean, n.shortValue()); break;
            case 'i': field.setInt(bean, n.intValue()); break;
            case 'l': field.setLong(bean, n.longValue()); break;
            case 'f': field.setFloat(bean, n.floatValue()); break;
            case 'd': field.setDouble(bean, n.doubleValue()); break;
            default: throw new AssertionError(type);
        }
    }
    else {
        if(!Number.class.isAssignableFrom(type)
        || type.getPackage() != Object.class.getPackage())
            return false;
        switch(type.getSimpleName().charAt(0)) {
            case 'B': field.set(bean, n.byteValue()); break;
            case 'S': field.set(bean, n.shortValue()); break;
            case 'I': field.set(bean, n.intValue()); break;
            case 'L': field.set(bean, n.longValue()); break;
            case 'F': field.set(bean, n.floatValue()); break;
            case 'D': field.set(bean, n.doubleValue()); break;
            default: throw new AssertionError(type);
        }
    }
    return true;
}
</code>```

This only handles the numeric types and return the success status. The caller can use it like

```<code>if(!setNumeric(field, bean, value)) {
    field.set(bean, value); // non numeric or throw appropriate exception
}
</code>```

Body:
Our original code is something like:

Object bean = ...
Field field = ...
Object value = ... // Retrieved from Database
field.set(bean, value);

But the type of bean field may be different from type of value, e.g. our bean is an Integer but value retrieved from db may be Byte or Short.

How can I write some simple code to convert boxed types without reflection exception?

Here is my solution but not as simple as my expectation:

if (field.getType().equals(Integer.class)) {
   field.set(bean, Integer.valueOf(((Number) value).intValue()));
} else if (field.getType().equals(Short.class)) {
   field.set(bean, Short.valueOf(((Number) value).shortValue()));
} else if (...) {
   ...
}

Body:
There’s no way to handle these conversion generically unless you add even more Reflection.

The best you can do, is to make these required expressions more maintainable. One thing to consider, is that with your expressions like, e.g. Short.valueOf(((Number) value).shortValue()), the valueOf invocation is unnecessary. That’s what auto-boxing does anyway.

Then, you can do with recent Java versions:

static final Map<Class<?>,Setter> SETTERS =Map.copyOf(Map.<Class<?>,NumericSetter>ofEntries(
    Map.entry(byte.class, (field,bean,n) -> field.setByte(bean, n.byteValue())),
    Map.entry(short.class, (field,bean,n) -> field.setShort(bean, n.shortValue())),
    Map.entry(int.class, (field,bean,n) -> field.setInt(bean, n.intValue())),
    Map.entry(long.class, (field,bean,n) -> field.setLong(bean, n.longValue())),
    Map.entry(float.class, (field,bean,n) -> field.setFloat(bean, n.floatValue())),
    Map.entry(double.class, (field,bean,n) -> field.setDouble(bean, n.doubleValue())),
    Map.entry(Byte.class, (field,bean,n) -> field.set(bean, n.byteValue())),
    Map.entry(Short.class, (field,bean,n) -> field.set(bean, n.shortValue())),
    Map.entry(Integer.class, (field,bean,n) -> field.set(bean, n.intValue())),
    Map.entry(Long.class, (field,bean,n) -> field.set(bean, n.longValue())),
    Map.entry(Float.class, (field,bean,n) -> field.set(bean, n.floatValue())),
    Map.entry(Double.class, (field,bean,n) -> field.set(bean, n.doubleValue()))
));
interface Setter {
    void set(Field field, Object bean, Object value) throws IllegalAccessException;
    Setter FALLBACK = Field::set;
}
interface NumericSetter extends Setter {
    @Override default void set(Field field, Object bean, Object value)
    throws IllegalAccessException {
        setNumeric(field, bean, (Number)value);
    }
    void setNumeric(Field f, Object bean, Number n) throws IllegalAccessException;
}

To handle all numeric field types, whether primitive or boxed. This can be use like

SETTERS.getOrDefault(field.getType(), Setter.FALLBACK).set(field, bean, value);

to use one of the numeric conversions if applicable or just use the set method without transformations otherwise. The latter would also throw the appropriate exception for mismatching types.

For older Java versions you could consider something like

static boolean setNumeric(Field field, Object bean, Object value)
throws IllegalAccessException {
    if(!(value instanceof Number)) return false;
    Number n = (Number)value;
    Class<?> type = field.getType();
    if(type.isPrimitive()) {
        if(type == boolean.class || type == char.class) return false;
        switch(type.getName().charAt(0)) {
            case 'b': field.setByte(bean, n.byteValue()); break;
            case 's': field.setShort(bean, n.shortValue()); break;
            case 'i': field.setInt(bean, n.intValue()); break;
            case 'l': field.setLong(bean, n.longValue()); break;
            case 'f': field.setFloat(bean, n.floatValue()); break;
            case 'd': field.setDouble(bean, n.doubleValue()); break;
            default: throw new AssertionError(type);
        }
    }
    else {
        if(!Number.class.isAssignableFrom(type)
        || type.getPackage() != Object.class.getPackage())
            return false;
        switch(type.getSimpleName().charAt(0)) {
            case 'B': field.set(bean, n.byteValue()); break;
            case 'S': field.set(bean, n.shortValue()); break;
            case 'I': field.set(bean, n.intValue()); break;
            case 'L': field.set(bean, n.longValue()); break;
            case 'F': field.set(bean, n.floatValue()); break;
            case 'D': field.set(bean, n.doubleValue()); break;
            default: throw new AssertionError(type);
        }
    }
    return true;
}

This only handles the numeric types and return the success status. The caller can use it like

if(!setNumeric(field, bean, value)) {
    field.set(bean, value); // non numeric or throw appropriate exception
}


来源: stackexchange

问:
Deny all connections to ports that aren't 443 or 80 over HTTP/HTTPS on NGINX
I'm running a server on Nginx and Ubuntu, the site has a domain. I have an issue where if someone navigates to the IP and an appended port (https://<ip-addr>:<port>) it will load up a service that should not be accessed directly like that, the ports can be figured out with nmap.

I'm trying to return a 444 to these types of connections. I've tried adding these under the 'server' block:

```<code>if ($host != "domain.tld") {
          return 444;
                   }
</code>```

and

```<code>    location / {

        return 444;
   }
</code>```

now these work pretty well for denying connections to the IP and restricting it to the domain, but if you do the ip and the port it loads up just fine. if some of these services did not have some form of authentication then they are exposed to anyone and everyone.

I tried using iptables to block the port but that would also block the `https://domain.tld/service, But that needs to work.

Service should be only accessible through this URL and not the IP and port.

答:
Try this</p>

```<code>server { # Will redirect all http to https
    listen      80 default_server;
    server_name _; # will catch everything

    return 301 https://domain.tld$request_uri;
}

server{ # Will redirect everything that is not "domain.tld" to http://domain.tld
    listen      443 ssl http2;
    server_name _; # will catch everything

    ssl_...

    return 301 http://domain.tld$request_uri;
}

server { # Do normal behavior
    listen      443 default_server;
    server_name *.domain.tld; # will catch everything

    ssl_...

    location / {
        ...
    }

    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm running a server on Nginx and Ubuntu, the site has a domain. I have an issue where if someone navigates to the IP and an appended port (https://<ip-addr>:<port>) it will load up a service that should not be accessed directly like that, the ports can be figured out with nmap.

I'm trying to return a 444 to these types of connections. I've tried adding these under the 'server' block:

if ($host != "domain.tld") {
          return 444;
                   }

and

    location / {

        return 444;
   }

now these work pretty well for denying connections to the IP and restricting it to the domain, but if you do the ip and the port it loads up just fine. if some of these services did not have some form of authentication then they are exposed to anyone and everyone.

I tried using iptables to block the port but that would also block the `https://domain.tld/service, But that needs to work.

Service should be only accessible through this URL and not the IP and port.

Body:
Try this

server { # Will redirect all http to https
    listen      80 default_server;
    server_name _; # will catch everything

    return 301 https://domain.tld$request_uri;
}

server{ # Will redirect everything that is not "domain.tld" to http://domain.tld
    listen      443 ssl http2;
    server_name _; # will catch everything

    ssl_...

    return 301 http://domain.tld$request_uri;
}

server { # Do normal behavior
    listen      443 default_server;
    server_name *.domain.tld; # will catch everything

    ssl_...

    location / {
        ...
    }

    ...
}


问:
What will be performance impact if I will drop all statistics from my database in sql server?
I have a website which is running since last 7 years, for back end database we were using Sql Server 2008 and recently we have migrated on Sql Server 2014.

Now a days, we are facing issues like slowness suddenly with some of pages only.
I want to know that whether this due to Statistic on tables, which are used in slow pages. As per SQL Server: Auto Statistics Cleanup blog post, it is recommended to drop all the existing statistics as our database gradually do so many CRUD operations and changes in table definitions as well.

Please note that I have set Auto update statistics to ON.

So What should I do whether I have to drop all the statistics or not? if yes, what would be performance impact on my current web application? Is there any another way to identify slowness issue, which do come gradually with no deadlock or blocking conditions?

答:
This query gets all unused indexes and statistics. In order to optimize your DB you need to profile and tune the DB: </p>

```<code>SELECT
    objects.name AS Table_name,
    indexes.name AS Index_name,
    dm_db_index_usage_stats.user_seeks,
    dm_db_index_usage_stats.user_scans,
    dm_db_index_usage_stats.user_updates
FROM
    sys.dm_db_index_usage_stats
    INNER JOIN sys.objects ON dm_db_index_usage_stats.OBJECT_ID = objects.OBJECT_ID
    INNER JOIN sys.indexes ON indexes.index_id = dm_db_index_usage_stats.index_id AND dm_db_index_usage_stats.OBJECT_ID = indexes.OBJECT_ID
WHERE
    indexes.is_primary_key = 0 --This line excludes primary key constarint
    AND
    indexes. is_unique = 0 --This line excludes unique key constarint
    AND
    dm_db_index_usage_stats.user_updates <> 0 -- This line excludes indexes SQL Server hasn’t done any work with
    AND
    dm_db_index_usage_stats. user_lookups = 0
    AND
    dm_db_index_usage_stats.user_seeks = 0
    AND
    dm_db_index_usage_stats.user_scans = 0
ORDER BY
    dm_db_index_usage_stats.user_updates DESC
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This query gets all unused indexes and statistics. In order to optimize your DB you need to profile and tune the DB:

SELECT
    objects.name AS Table_name,
    indexes.name AS Index_name,
    dm_db_index_usage_stats.user_seeks,
    dm_db_index_usage_stats.user_scans,
    dm_db_index_usage_stats.user_updates
FROM
    sys.dm_db_index_usage_stats
    INNER JOIN sys.objects ON dm_db_index_usage_stats.OBJECT_ID = objects.OBJECT_ID
    INNER JOIN sys.indexes ON indexes.index_id = dm_db_index_usage_stats.index_id AND dm_db_index_usage_stats.OBJECT_ID = indexes.OBJECT_ID
WHERE
    indexes.is_primary_key = 0 --This line excludes primary key constarint
    AND
    indexes. is_unique = 0 --This line excludes unique key constarint
    AND
    dm_db_index_usage_stats.user_updates <> 0 -- This line excludes indexes SQL Server hasn’t done any work with
    AND
    dm_db_index_usage_stats. user_lookups = 0
    AND
    dm_db_index_usage_stats.user_seeks = 0
    AND
    dm_db_index_usage_stats.user_scans = 0
ORDER BY
    dm_db_index_usage_stats.user_updates DESC


问:
jquery hover problem on IE
I have just using the jquery hover :

```<code>$.each(navItems, function(i){
    $(navItems[i]).hover(function(){
        $(this).find('ul:first').css({visibility: "visible",display: "none"}).show();
    },function(){
        $(this).find('ul:first').css({visibility: "hidden"});
    });
});
</code>```

I works fine on all browser except IE. I have looking for the others code that work fine in all major browsers(include IE), normally they also using same the way i did.
Anybody can help me to explain what i wrong?
full code on here : http://jsfiddle.net/XrMNr/

答:
Why is your hover in a loop? Have you tried...</p>

```<code>$('.NaviItem').hover(function(){
    $(this).find('ul:first').css({visibility: "visible", display: "none"}).show();
},function(){
    $(this).find('ul:first').css({visibility: "hidden"});
});
</code>```

Title: jquery hover problem on IE

Body:
I have just using the jquery hover :

$.each(navItems, function(i){
    $(navItems[i]).hover(function(){
        $(this).find('ul:first').css({visibility: "visible",display: "none"}).show();
    },function(){
        $(this).find('ul:first').css({visibility: "hidden"});
    });
});

I works fine on all browser except IE. I have looking for the others code that work fine in all major browsers(include IE), normally they also using same the way i did.
Anybody can help me to explain what i wrong?
full code on here : http://jsfiddle.net/XrMNr/

Body:
Why is your hover in a loop? Have you tried...

$('.NaviItem').hover(function(){
    $(this).find('ul:first').css({visibility: "visible", display: "none"}).show();
},function(){
    $(this).find('ul:first').css({visibility: "hidden"});
});


问:
CPLEX generic callbacks, node LP for cut separation
I am setting up a branch-and-cut algorithm using the generic callback framework through the C API of CPLEX 12.10.

At each node, the separation problem is based on the current node LP and detects locally valid cuts, that if violated are added for every child node of the current node.

To my understanding, the information of a current node LP is not readily available in the generic callbacks. However, I would like to use cuts generated for a parent node, to generate better cuts in the child nodes.

Is it necessary to do book-keeping about which cuts are generated at all the nodes or can this information somehow be passed on using CPLEX functionality? If the only possibility is to keep track of all generated cuts, how can this book-keeping be made thread-safe, if CPLEX calls the callback from different threads and in different nodes?

答:
There is no way to make CPLEX keep track of this information for you. You have to roll your own.

One way to do this is to implement a dictionary that maps a node's unique id (see CPXCALLBACKINFO_NODEUID) to the information you want to store along with that node. With respect to thread-safety you only have to protect the accesses to that dictionary. To do that, use a lock (pthread_mutex on non-Windows, CRITICAL_SECTION on Windows, for example) and lock and lookup or update operation on that dictionary.


问:
Django server won't run even if django is installed in the environment
I cannot configure Django and Miniconda on my Mac.

I receive this error every time when I run python manage.py runserver:

Traceback (most recent call last):   File "manage.py", line 10, in
  main
      from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):   File "manage.py", line 21, in

      main()   File "manage.py", line 12, in main
      raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment
  variable? Did you forge t to activate a virtual environment?

These are the steps I have followed so far:

cd /Users/myuser/projects/My_Django_Stuff

conda create --name MyDjangoEnv python=3.7

source activate MyDjangoEnv

conda install django=2.2

django-admin startproject first_project

cd first_project

python manage.py runserver

If I run conda list, django package appears to be installed in my environment:

```<code>ca-certificates           2020.1.1                      0
certifi                   2019.11.28               py37_0
django                    2.2.5                    py37_1
libcxx                    4.0.1                hcfea43d_1
libcxxabi                 4.0.1                hcfea43d_1
libedit                   3.1.20181209         hb402a30_0
libffi                    3.2.1                h475c297_4
ncurses                   6.1                  h0a44026_1
openssl                   1.1.1d               h1de35cc_4
pip                       20.0.2                   py37_1
python                    3.7.6                h359304d_2
pytz                      2019.3                     py_0
readline                  7.0                  h1de35cc_5
setuptools                45.2.0                   py37_0
sqlite                    3.31.1               ha441bb4_0
sqlparse                  0.3.0                      py_0
tk                        8.6.8                ha441bb4_0
wheel                     0.34.2                   py37_0
xz                        5.2.4                h1de35cc_4
zlib                      1.2.11               h1de35cc_3
</code>```

I have tried to delete the environment and create a new one, but I receive the same error every time.

Most of the solutions found online are based on "make sure the environment is activated" and "install Django again using pip", but none of them applies to me as the environment is 100% activated and I use conda for it.

Any idea how I can fix this? Thank you!

Edit: I don't know what was wrong, but after uninstalling Miniconda, reinstalling it again, creating a new environment and reinstalling Django, I no longer get the above error message.

Edit 2: This is getting stupid. I run Django, create my first views, templates, the website was working properly, but after the first mac restart, I get this error again.

Edit 3: I forgot to mention all the commands were executed in Atom's terminal. It looks like Django is actually working if I start the server using Mac's terminal.

If I run which python I get the following response:

Atom's terminal: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3

Mac's terminal: /Users/myuser/opt/miniconda3/envs/MyDjangoEnv/bin/python3

What can be wrong?

答:
Ok I thinks it's a silling mistake ! Can you run python3 manage.py and not python manage.py

On my mac it's enough ;)

Body:
I cannot configure Django and Miniconda on my Mac.

I receive this error every time when I run python manage.py runserver:

Traceback (most recent call last):   File "manage.py", line 10, in
  main
      from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):   File "manage.py", line 21, in

      main()   File "manage.py", line 12, in main
      raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment
  variable? Did you forge t to activate a virtual environment?

These are the steps I have followed so far:

cd /Users/myuser/projects/My_Django_Stuff

conda create --name MyDjangoEnv python=3.7

source activate MyDjangoEnv

conda install django=2.2

django-admin startproject first_project

cd first_project

python manage.py runserver

If I run conda list, django package appears to be installed in my environment:

ca-certificates           2020.1.1                      0
certifi                   2019.11.28               py37_0
django                    2.2.5                    py37_1
libcxx                    4.0.1                hcfea43d_1
libcxxabi                 4.0.1                hcfea43d_1
libedit                   3.1.20181209         hb402a30_0
libffi                    3.2.1                h475c297_4
ncurses                   6.1                  h0a44026_1
openssl                   1.1.1d               h1de35cc_4
pip                       20.0.2                   py37_1
python                    3.7.6                h359304d_2
pytz                      2019.3                     py_0
readline                  7.0                  h1de35cc_5
setuptools                45.2.0                   py37_0
sqlite                    3.31.1               ha441bb4_0
sqlparse                  0.3.0                      py_0
tk                        8.6.8                ha441bb4_0
wheel                     0.34.2                   py37_0
xz                        5.2.4                h1de35cc_4
zlib                      1.2.11               h1de35cc_3

I have tried to delete the environment and create a new one, but I receive the same error every time.

Most of the solutions found online are based on "make sure the environment is activated" and "install Django again using pip", but none of them applies to me as the environment is 100% activated and I use conda for it.

Any idea how I can fix this? Thank you!

Edit: I don't know what was wrong, but after uninstalling Miniconda, reinstalling it again, creating a new environment and reinstalling Django, I no longer get the above error message.

Edit 2: This is getting stupid. I run Django, create my first views, templates, the website was working properly, but after the first mac restart, I get this error again.

Edit 3: I forgot to mention all the commands were executed in Atom's terminal. It looks like Django is actually working if I start the server using Mac's terminal.

If I run which python I get the following response:

Atom's terminal: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3

Mac's terminal: /Users/myuser/opt/miniconda3/envs/MyDjangoEnv/bin/python3

What can be wrong?


问:
JPA 2 @SequenceGenerator @GeneratedValue producing unique constraint violation
Problem Overview

At seemingly random times we get an exception "postgresql duplicate key violates unique constraint." I do think I know what our problem"s" are but I don't want to make changes to the code without having a reproducible test case. But since we haven't been able to reproduce it in any environment other than randomly in production, I'm asking assistance from SO.

In this project we have multiple postgres databases, and a primary key sequence configured for each table in each database. These sequences are created like this:

```<code>create sequence PERSONS_SEQ;
create sequence VISITS_SEQ;
etc...
</code>```

We use these sequences to generate the primary keys for the entities like this:

```<code>@Entity
@Table(name = "visits")
public class Visit {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "seq", sequenceName = "visits_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  private int id;
  ...
}

@Entity
@Table(name = "person")
public class Person {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "seq", sequenceName = "persons_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  private int id;
  ...
}
</code>```

Analysis

I think I recognize 2 problems with this configuration:

1) Both @SequenceGenerators specify the same name attribute even though they are supposed to map to different database sequences.

2) The @SequenceGenerator allocationSize attribute defaults to 50 (we're using hibernate as the JPA provider) so I think the create sequence syntax should specify how much the sequence should increment by, specifically by 50 to match the allocationSize.

Based on this guess, I think the code should be modified to something like this:

```<code>create sequence PERSONS_SEQ increment by 50;
create sequence VISITS_SEQ increment by 50;
etc...

@Entity
@Table(name = "visits")
public class Visit {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "visits_seq", sequenceName = "visits_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "visits_seq")
  private int id;
  ...
}

@Entity
@Table(name = "person")
public class Person {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "persons_seq", sequenceName = "persons_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "persons_seq")
  private int id;
  ...
}
</code>```

I would just test this rather than asking the question on SO, but again, we have not been able to reproduce this production issue in any other environments. And even in production the unique constraint violation only occurs at seemingly random times.

Questions:

1) Am I correct in my analysis of what the changes should be to fix this unique constraint violation?

2) What are the best practices for using sequence generators when using hibernate as a JPA provider?

答:
I gone through the same problem. and I tried this to fix the problem. may be this is not the best solution but i hope it will solve your problem for now.</p>

```<code>@SequenceGenerator(schema = "DS_TEST",name = "SEQ_PR_TEXT",sequenceName = "SEQ_PR_TEXT",
        allocationSize = 1)
public class TextEntity {
    @Id
    @GeneratedValue(generator = SequenceConstant.SEQ_PR_TEXT,
            strategy = GenerationType.SEQUENCE)
    @Column(name = "PR_TEXT_ID")
    private Long id;
}
</code>```

Body:
Problem Overview

At seemingly random times we get an exception "postgresql duplicate key violates unique constraint." I do think I know what our problem"s" are but I don't want to make changes to the code without having a reproducible test case. But since we haven't been able to reproduce it in any environment other than randomly in production, I'm asking assistance from SO.

In this project we have multiple postgres databases, and a primary key sequence configured for each table in each database. These sequences are created like this:

create sequence PERSONS_SEQ;
create sequence VISITS_SEQ;
etc...

We use these sequences to generate the primary keys for the entities like this:

@Entity
@Table(name = "visits")
public class Visit {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "seq", sequenceName = "visits_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  private int id;
  ...
}

@Entity
@Table(name = "person")
public class Person {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "seq", sequenceName = "persons_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  private int id;
  ...
}

Analysis

I think I recognize 2 problems with this configuration:

1) Both @SequenceGenerators specify the same name attribute even though they are supposed to map to different database sequences.

2) The @SequenceGenerator allocationSize attribute defaults to 50 (we're using hibernate as the JPA provider) so I think the create sequence syntax should specify how much the sequence should increment by, specifically by 50 to match the allocationSize.

Based on this guess, I think the code should be modified to something like this:

create sequence PERSONS_SEQ increment by 50;
create sequence VISITS_SEQ increment by 50;
etc...

@Entity
@Table(name = "visits")
public class Visit {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "visits_seq", sequenceName = "visits_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "visits_seq")
  private int id;
  ...
}

@Entity
@Table(name = "person")
public class Person {
  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "persons_seq", sequenceName = "persons_seq")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "persons_seq")
  private int id;
  ...
}

I would just test this rather than asking the question on SO, but again, we have not been able to reproduce this production issue in any other environments. And even in production the unique constraint violation only occurs at seemingly random times.

Questions:

1) Am I correct in my analysis of what the changes should be to fix this unique constraint violation?

2) What are the best practices for using sequence generators when using hibernate as a JPA provider?

Body:
I gone through the same problem. and I tried this to fix the problem. may be this is not the best solution but i hope it will solve your problem for now.

@SequenceGenerator(schema = "DS_TEST",name = "SEQ_PR_TEXT",sequenceName = "SEQ_PR_TEXT",
        allocationSize = 1)
public class TextEntity {
    @Id
    @GeneratedValue(generator = SequenceConstant.SEQ_PR_TEXT,
            strategy = GenerationType.SEQUENCE)
    @Column(name = "PR_TEXT_ID")
    private Long id;
}


问:
How do you generate and analyze a thread dump from a running JBoss instance?
How do you generate and analyze a thread dump from a running JBoss instance?</p>

答: The stacktrace app found here is also useful, especially on Windows machines when the   java app is not started from the command line.</p>

OwnerDisplayName: Teflon Ted

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Andrei


问:
list the file and its base directory
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

```<code>pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls
</code>```

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

```<code>/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls
</code>```

答:
Something like this?</p>

```<code>for i in {*.pdf,*.doc,*.xls}; do
    find /home/sample/ -name "$i";
done | perl -lnwe '/([^\/]+\/[^\/]+)$/&&print $1'
</code>```

Title: list the file and its base directory

Body:
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls

Body:
Something like this?

for i in {*.pdf,*.doc,*.xls}; do
    find /home/sample/ -name "$i";
done | perl -lnwe '/([^\/]+\/[^\/]+)$/&&print $1'


问:
how to create high trust SharePoint Add-ins?
I am working on SharePoint add-in to create high trusted app. I am trying to create SharePoint add-in using certificates. I took Create high-trust SharePoint Add-ins as the reference. I have successfully generated .pfx and .cer file. Now, the next step is to configure SharePoint. I have opened my SharePoint Online Management Shell in Administrator mode. I executed these 2 lines successfully.

```<code>$publicCertPath = "C:\Certs\HighTrustSampleCert.cer"
$certificate = New-Object
System.Security.Cryptography.X509Certificates.X509Certificate2($publicCertPath)
</code>```

As soon as i entered New-SPTrustedRootAuthority -Name "HighTrustSampleCert" -Certificate $certificate, I got the following exception.

```<code>New-SPTrustedRootAuthority : The term 'New-SPTrustedRootAuthority' is not recognized as the name of a
cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the
path is correct and try again.
At line:1 char:1
+ New-SPTrustedRootAuthority -Name "HighTrustSampleCert" -Certificate $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (New-SPTrustedRootAuthority:String) [],
      CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

I don't know, why am I getting this error. Is there any other way to generate high trusted SharePoint add-in?

答: High-trust add-in cannot be installed to Microsoft SharePoint Online, you need use low-trust for SharePoint online.</p>

Body:
I am working on SharePoint add-in to create high trusted app. I am trying to create SharePoint add-in using certificates. I took Create high-trust SharePoint Add-ins as the reference. I have successfully generated .pfx and .cer file. Now, the next step is to configure SharePoint. I have opened my SharePoint Online Management Shell in Administrator mode. I executed these 2 lines successfully.

$publicCertPath = "C:\Certs\HighTrustSampleCert.cer"
$certificate = New-Object
System.Security.Cryptography.X509Certificates.X509Certificate2($publicCertPath)

As soon as i entered New-SPTrustedRootAuthority -Name "HighTrustSampleCert" -Certificate $certificate, I got the following exception.

New-SPTrustedRootAuthority : The term 'New-SPTrustedRootAuthority' is not recognized as the name of a
cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the
path is correct and try again.
At line:1 char:1
+ New-SPTrustedRootAuthority -Name "HighTrustSampleCert" -Certificate $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (New-SPTrustedRootAuthority:String) [],
      CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I don't know, why am I getting this error. Is there any other way to generate high trusted SharePoint add-in?


问:
Scapy load into readable string python 3.7
print(scapy_packet[scapy.Raw].load) gives hex string. How to convert into readable string?

答:
You can use below code.</p>

```<code>print(bytearray.fromhex(scapy_packet[scapy.Raw].load).decode())
</code>```

Body:
You can use below code.

print(bytearray.fromhex(scapy_packet[scapy.Raw].load).decode())


问:
how to pause and restart an automatic ejb
I'm studying the EJB and testing automatic function by create a simple EJB like below.

I hope it can run automatically once it's deployed.

```<code>import javax.ejb.Schedule;
import javax.ejb.Stateless;
@Stateless
public class TestAuto {

@Schedule(minute="*",hour="15")
    public void testprint()
    {
        System.out.println("AutoWrite");
    }
}
</code>```

I run it at eclipse and it successfully deployed but I can't see any output at console. Can someone help? I used wildfly 11, java 1.8 and ejb 3.2. Thanks.
Update: Now it worked. But how to pause it and restart?

答:
There is not such thing as a "pause" and "restart", but you can cancel an annotation based timer declared with a @Schedule, and recreate it. You will have to store the schedulerexpression somewhere.

You can do something like this:

```<code>@Resource
private TimerService timerService;

public ScheduleExpression cancelTimer() {
    Timer currentTimer = timerService.getTimers().iterator().next();
    ScheduleExpression scheduleExpression = currentTimer.getSchedule();
    currentTimer.cancel();
    return scheduleExpression;
}

public void restartTimer(ScheduleExpression scheduleExpression) {
    timerService.createCalendarTimer(scheduleExpression);
}
</code>```

Body:
I'm studying the EJB and testing automatic function by create a simple EJB like below.

I hope it can run automatically once it's deployed.

import javax.ejb.Schedule;
import javax.ejb.Stateless;
@Stateless
public class TestAuto {

@Schedule(minute="*",hour="15")
    public void testprint()
    {
        System.out.println("AutoWrite");
    }
}

I run it at eclipse and it successfully deployed but I can't see any output at console. Can someone help? I used wildfly 11, java 1.8 and ejb 3.2. Thanks.
Update: Now it worked. But how to pause it and restart?

Body:
There is not such thing as a "pause" and "restart", but you can cancel an annotation based timer declared with a @Schedule, and recreate it. You will have to store the schedulerexpression somewhere.

You can do something like this:

@Resource
private TimerService timerService;

public ScheduleExpression cancelTimer() {
    Timer currentTimer = timerService.getTimers().iterator().next();
    ScheduleExpression scheduleExpression = currentTimer.getSchedule();
    currentTimer.cancel();
    return scheduleExpression;
}

public void restartTimer(ScheduleExpression scheduleExpression) {
    timerService.createCalendarTimer(scheduleExpression);
}


问:
How to generate HMAC-SHA1 Signature in android?
This is my base String:

```<code>        String args ="oauth_consumer_key="+enc(consumerkey) +
                   "&oauth_nonce="+enc(generateNonce()) +
                   "&oauth_signature_method=HMAC-SHA1" +
                   "&oauth_timestamp="+ timestamp +
                   "&oauth_token="+enc(Home.consToken) +
                   "&oauth_verifier="+verifier+"&oauth_version=1.0";
                    String base ="POST&"+enc("https://api.linkedin.com/uas/oauth   /accessToken") +"&"+ enc(args);

       String signature =computeHmac(base,consumer_secret+"&"+secretToken);
</code>```

This is my Header:

```<code>        String header = "OAuth " +
       "oauth_consumer_key=\""+ enc(consumerkey)+ "\"," +
       "oauth_nonce=\""+ enc(generateNonce()) + "\"," +
       "oauth_signature_method=\"HMAC-SHA1\"," +
       "oauth_timestamp=\""+ timestamp + "\"," +
       "oauth_token=\""+Home.consToken + "\"," +
       "oauth_signature=\""+enc(signature)+"\","+
       "oauth_verifier=\""+verifier +"\","+
       "oauth_version=\""+1.0+"\"" ;
</code>```

I am using following method to generate Signature:

```<code>public String computeHmac(String baseString, String key)
    throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,  UnsupportedEncodingException
{
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] digest = mac.doFinal(baseString.getBytes());
    byte[] result=Base64.encodeBase64(digest);
    return new String(result);
}
</code>```

while executing this code i am getting the following error...

```<code>oauth_problem=signature_invalid&
oauth_problem_advice=com.linkedin.security.auth.pub.LoginDeniedInvalidAuthTokenException
</code>```

can anybody help me out this?

Thanks...

答:
Messy, but I'm using this:

```<code>static String hash_hmac(String type, String value, String key)
    {
    try {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance(type);
        javax.crypto.spec.SecretKeySpec secret = new javax.crypto.spec.SecretKeySpec(key.getBytes(), type);
        mac.init(secret);
        byte[] digest = mac.doFinal(value.getBytes());
        StringBuilder sb = new StringBuilder(digest.length*2);
        String s;
        for (byte b : digest){
        s = Integer.toHexString(intval(b));
        if(s.length() == 1) sb.append('0');
        sb.append(s);
        }
        return sb.toString();
    } catch (Exception e) {
        android.util.Log.v("TAG","Exception ["+e.getMessage()+"]", e);
    }
        return "";
    }
</code>```

You then invoke it like this:

```<code>hash_hmac("HmacSHA1", value, key);
</code>```

Body:
This is my base String:

        String args ="oauth_consumer_key="+enc(consumerkey) +
                   "&oauth_nonce="+enc(generateNonce()) +
                   "&oauth_signature_method=HMAC-SHA1" +
                   "&oauth_timestamp="+ timestamp +
                   "&oauth_token="+enc(Home.consToken) +
                   "&oauth_verifier="+verifier+"&oauth_version=1.0";
                    String base ="POST&"+enc("https://api.linkedin.com/uas/oauth   /accessToken") +"&"+ enc(args);

       String signature =computeHmac(base,consumer_secret+"&"+secretToken);

This is my Header:

        String header = "OAuth " +
       "oauth_consumer_key=\""+ enc(consumerkey)+ "\"," +
       "oauth_nonce=\""+ enc(generateNonce()) + "\"," +
       "oauth_signature_method=\"HMAC-SHA1\"," +
       "oauth_timestamp=\""+ timestamp + "\"," +
       "oauth_token=\""+Home.consToken + "\"," +
       "oauth_signature=\""+enc(signature)+"\","+
       "oauth_verifier=\""+verifier +"\","+
       "oauth_version=\""+1.0+"\"" ;

I am using following method to generate Signature:

public String computeHmac(String baseString, String key)
    throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,  UnsupportedEncodingException
{
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] digest = mac.doFinal(baseString.getBytes());
    byte[] result=Base64.encodeBase64(digest);
    return new String(result);
}

while executing this code i am getting the following error...

oauth_problem=signature_invalid&
oauth_problem_advice=com.linkedin.security.auth.pub.LoginDeniedInvalidAuthTokenException

can anybody help me out this?

Thanks...

Body:
Messy, but I'm using this:

static String hash_hmac(String type, String value, String key)
    {
    try {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance(type);
        javax.crypto.spec.SecretKeySpec secret = new javax.crypto.spec.SecretKeySpec(key.getBytes(), type);
        mac.init(secret);
        byte[] digest = mac.doFinal(value.getBytes());
        StringBuilder sb = new StringBuilder(digest.length*2);
        String s;
        for (byte b : digest){
        s = Integer.toHexString(intval(b));
        if(s.length() == 1) sb.append('0');
        sb.append(s);
        }
        return sb.toString();
    } catch (Exception e) {
        android.util.Log.v("TAG","Exception ["+e.getMessage()+"]", e);
    }
        return "";
    }

You then invoke it like this:

hash_hmac("HmacSHA1", value, key);


问:
TForm.PixelsPerInch has no effect in Delphi Rio 10.3.3
As already described in How PixelsPerInch works in Delphi 10.3 Rio? and Form.PixelsPerInch no longer used in Delphi Tokyo TForm.PixelsPerInch has no effect in Delphi Rio (I use Rio 10.3.3). I can change its value (either in the IDE or by editing the dfm file) to 96, 120, 144,... but the size of the form, font sizes etc. remain unchanged (both at designtime and runtime). Form.Scaled is true.

How can I enable correct scaling of forms in Delphi Rio if pixels per inch is different than 96, i.e. if Windows scaling is different from 100%?

I am migrating a project with more than 50 forms from Delphi XE5 to Rio. The project was developed at 120 pixels per inch in XE5 and had correct font sizes and form sizes, Form.Scaled is True, Form.PixelsPerInch is 120, Form.Font is 'Segoe UI' at 11 pt (this is identical to 9 pt at 96 pixels per inch). When opening the project in Rio at 120 pixels per inch all forms are too large and the font used is 'Segoe UI' at about 14 pt, i.e. Rio uses PixelsPerInch of 96 instead of 120 (which is given in the dfm file).

答:
I am not sure if these answer steps are actually working, as it is near to impossible to test before given my current system settings. But let us give it a try:

set up XE5 in an environment with 96 dpi

open the project

open and save all forms

open the project on your Rio system

compile, run and check if it is working now

optional:

play with the DPI settings in the Manifest section of the Project Options

if that turns out to be worse, leave this setting at none


问:
How to remove white space on the side of my website
I have a website (https://olsenspkg.com) that has white space on the right hand side of every page. Currently I have tried this to solve it:

body {
  overflow-x: hidden !important;
  width: 100%;
}```

It only fixes it on chrome though. Safari still acts like I haven't put that code in.

Regular Site View

White Space on the Right

答:
This element is overflown:

```<code><div id="searchBar">
</code>```

The width is the same as parents div. Change width to 300px or change that rendering completely.

Overflown div

Body:
I have a website (https://olsenspkg.com) that has white space on the right hand side of every page. Currently I have tried this to solve it:

body {
  overflow-x: hidden !important;
  width: 100%;
}

It only fixes it on chrome though. Safari still acts like I haven't put that code in.

Regular Site View

White Space on the Right

Body:
This element is overflown:

<div id="searchBar">

The width is the same as parents div. Change width to 300px or change that rendering completely.

Overflown div


问:
Adding a static option to ui-select choices
In the code bellow options are added dynamically from a database.

```<code><ui-select ng-model="model.people">
    <ui-select-match>{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="value.id as value in options | filter: $select.search">
        <div ng-bind-html="value.name | highlight: $select.search"></div>
    </ui-select-choices>
</ui-select>
</code>```

My question is : How to add an option "all" manually into the dropdown. Is there any way to achive that ?

答:
This should work:

```<code><ui-select ng-model="model.people" theme="bootstrap">
<ui-select-match>{{ $select.selected }}</ui-select-match>
<ui-select-choices repeat="choice in ['option 1', 'option 2']">
    <span>{{ choice }}</span>
</ui-select-choices>
</code>```

Body:
In the code bellow options are added dynamically from a database.

<ui-select ng-model="model.people">
    <ui-select-match>{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="value.id as value in options | filter: $select.search">

    </ui-select-choices>
</ui-select>

My question is : How to add an option "all" manually into the dropdown. Is there any way to achive that ?

Body:
This should work:

<ui-select ng-model="model.people" theme="bootstrap">
<ui-select-match>{{ $select.selected }}</ui-select-match>
<ui-select-choices repeat="choice in ['option 1', 'option 2']">
    <span>{{ choice }}</span>
</ui-select-choices>


问:
How can I undo the git garbage collector command? I ran git gc
I ran
git gc
to see how git garbage collector works in general.

But as soon as I ran it,my 15 objects that were shown in .git/objects as blobs, commits, and tree, they are gone.
1. How to undo it and restore those git objects?
2. When I'll run ls, it shows me all the files but what is there status? Where are they at present? They are in the working directory, staging or modified area. And why can't I see them?

Please help me and suggest me If I'm missing some use-case.

答:
How to undo it and restore those git objects?

I see that this has been answered in the comments, credits to @Sven.

When I'll run ls, it shows me all the files but what is there status? Where are they at present? They are in the working directory, staging or modified area. And why can't I see them?

Well, assuming you are talking about the "linux" ls (i.e. the one which displays all the files), to see the current status of your git repo, run git status which tells you if any file(s) are there in the staging area. This will also tell you which file(s) are not being tracked hence your directory(the things present in your working folder) minus the untracked file(s) gives you your working directory.

Best


问:
Compile error when building with Angular Ivy
I have an angular 8 project and when I enable angular Ivy then it is getting failed during compile time. When I check for the solutions provided by others and updated to angular 8.1.0( from 8.0.3) but the issue still persists and keep giving me the below error:

```<code>D:\Users\Backup>ng build shared
Building Angular Package
Building entry point 'shared'
Compiling TypeScript sources through ngc

BUILD ERROR
node_modules/@angular/common/common.d.ts(115,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class
node_modules/@angular/forms/forms.d.ts(2669,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class
node_modules/@angular/forms/forms.d.ts(3703,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class
node_modules/@angular/common/http/http.d.ts(2799,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class
</code>```

My Angular Ivy is enabled in tsconfig.app.json.

```<code>"angularCompilerOptions": {
    "enableIvy": true
  }
</code>```

My package.json has the following dependencies:

```<code>"dependencies": {
    "@angular/animations": "~8.0.3",
    "@angular/common": "~8.0.3",
    "@angular/compiler": "~8.0.3",
    "@angular/core": "~8.0.3",
    "@angular/forms": "~8.0.3",
    "@angular/material": "^8.0.1",
    "@angular/platform-browser": "~8.0.3",
    "@angular/platform-browser-dynamic": "~8.0.3",
    "@angular/platform-server": "~8.0.3",
    "@angular/router": "~8.0.3",
    "@ng-bootstrap/ng-bootstrap": "^5.0.0-rc.0",
    "@nguniversal/express-engine": "^7.1.1",
    "@nguniversal/module-map-ngfactory-loader": "0.0.0",
    "@nicky-lenaers/ngx-scroll-to": "^2.0.0",
    "@swimlane/ngx-charts": "^11.1.0",
    "@types/googlemaps": "^3.36.5",
    "core-js": "^2.5.4",
    "express": "^4.15.2",
    "ngx-cookie-service": "^2.2.0",
    "ngx-typeahead": "^6.2.0",
    "rxjs": "~6.5.2",
    "systemjs": "3.0.2",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.6",
    "@angular-devkit/build-ng-packagr": "~0.800.6",
    "@angular/cli": "~8.0.6",
    "@angular/compiler-cli": "~8.0.3",
    "@angular/language-service": "~8.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.1",
    "jasmine": "^3.3.1",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "ng-packagr": "^5.1.0",
    "prettier": "^1.16.4",
    "tsickle": ">=0.34.0",
    "ts-loader": "^5.2.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.4.5",
    "webpack-cli": "^3.1.0"
  }
</code>```

Please help me on how to resolve the above issues.

答:
If you have path declaration in tsconfig.json file like below

```<code>"paths":{ "@sharedmodule":[ "your-shared-module"/index"]    }
</code>```

And if you are using @sharemodule in import statement in any of the component then remove @ shared from that import statement and replace that with fully qualified path of shared module.

Body:
I have an angular 8 project and when I enable angular Ivy then it is getting failed during compile time. When I check for the solutions provided by others and updated to angular 8.1.0( from 8.0.3) but the issue still persists and keep giving me the below error:

D:\Users\Backup>ng build shared
Building Angular Package
Building entry point 'shared'
Compiling TypeScript sources through ngc

BUILD ERROR
node_modules/@angular/common/common.d.ts(115,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class
node_modules/@angular/forms/forms.d.ts(2669,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class
node_modules/@angular/forms/forms.d.ts(3703,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class
node_modules/@angular/common/http/http.d.ts(2799,22): error TS-996002: Appears in the NgModule.imports of SharedModule, but could not be resolved to an NgModule class

My Angular Ivy is enabled in tsconfig.app.json.

"angularCompilerOptions": {
    "enableIvy": true
  }

My package.json has the following dependencies:

"dependencies": {
    "@angular/animations": "~8.0.3",
    "@angular/common": "~8.0.3",
    "@angular/compiler": "~8.0.3",
    "@angular/core": "~8.0.3",
    "@angular/forms": "~8.0.3",
    "@angular/material": "^8.0.1",
    "@angular/platform-browser": "~8.0.3",
    "@angular/platform-browser-dynamic": "~8.0.3",
    "@angular/platform-server": "~8.0.3",
    "@angular/router": "~8.0.3",
    "@ng-bootstrap/ng-bootstrap": "^5.0.0-rc.0",
    "@nguniversal/express-engine": "^7.1.1",
    "@nguniversal/module-map-ngfactory-loader": "0.0.0",
    "@nicky-lenaers/ngx-scroll-to": "^2.0.0",
    "@swimlane/ngx-charts": "^11.1.0",
    "@types/googlemaps": "^3.36.5",
    "core-js": "^2.5.4",
    "express": "^4.15.2",
    "ngx-cookie-service": "^2.2.0",
    "ngx-typeahead": "^6.2.0",
    "rxjs": "~6.5.2",
    "systemjs": "3.0.2",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.6",
    "@angular-devkit/build-ng-packagr": "~0.800.6",
    "@angular/cli": "~8.0.6",
    "@angular/compiler-cli": "~8.0.3",
    "@angular/language-service": "~8.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.1",
    "jasmine": "^3.3.1",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "ng-packagr": "^5.1.0",
    "prettier": "^1.16.4",
    "tsickle": ">=0.34.0",
    "ts-loader": "^5.2.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.4.5",
    "webpack-cli": "^3.1.0"
  }

Please help me on how to resolve the above issues.

Body:
If you have path declaration in tsconfig.json file like below

"paths":{ "@sharedmodule":[ "your-shared-module"/index"]    }

And if you are using @sharemodule in import statement in any of the component then remove @ shared from that import statement and replace that with fully qualified path of shared module.


问:
How can I play my lottie animation with an OnTapGesture event?
I followed MengTo's example of how to get a Lottie animation to play within SwiftUI. (https://www.youtube.com/watch?v=fVehE3Jf7K0) However, I was wondering if anyone could help me understand how to initially present the first frame of the animation, but only have the animation play once a user taps on it in a button format.

My current LottieButton file is as follows:

```<code>import SwiftUI
import Lottie

struct LottieButton: UIViewRepresentable {
/// Create a button.
let animationButton = AnimatedButton()
var filename = "LottieLogo2"

func makeUIView(context: UIViewRepresentableContext<LottieButton>) -> UIView {
    let view = UIView()

    let animation = Animation.named(filename)
    animationButton.animation = animation
    animationButton.contentMode = .scaleAspectFit

    animationButton.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(animationButton)

    animationButton.clipsToBounds = false
       /// Set animation play ranges for touch states
    animationButton.setPlayRange(fromMarker: "touchDownStart", toMarker: "touchDownEnd", event: .touchUpInside)
       animationButton.setPlayRange(fromMarker: "touchDownEnd", toMarker: "touchUpCancel", event: .touchUpOutside)
       animationButton.setPlayRange(fromMarker: "touchDownEnd", toMarker: "touchUpEnd", event: .touchUpInside)

    NSLayoutConstraint.activate([
        animationButton.heightAnchor.constraint(equalTo: view.heightAnchor),
        animationButton.widthAnchor.constraint(equalTo: view.widthAnchor),
    ])

    return view

}

func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieButton>) {

    }
}
</code>```

And then I just have a simple view that is displaying the animation:

```<code>struct InboxView: View {
var body: some View {
    VStack {
        Button(action: {}) {
        LottieButton(filename: "inbox-notification")
        .frame(width: 100)
            }
        }
    }
}
</code>```

答:
If you want to show lottie file only when button pressed, you can set @State toggle and show your Lottie when the variable in toggled.

Sample code:

 @State var toggleValue = false
    var body: some View {
        VStack {
            Button(action: {
                self.toggleValue.toggle()
            }) {
                VStack {
                if toggleValue {
                    LottieView(filename: "inbox-notification")
                        .frame(width: 100)
                    }
                    Text("Button")
                }
            }
        }
    }
```

Body:
I followed MengTo's example of how to get a Lottie animation to play within SwiftUI. (https://www.youtube.com/watch?v=fVehE3Jf7K0) However, I was wondering if anyone could help me understand how to initially present the first frame of the animation, but only have the animation play once a user taps on it in a button format.

My current LottieButton file is as follows:

import SwiftUI
import Lottie

struct LottieButton: UIViewRepresentable {
/// Create a button.
let animationButton = AnimatedButton()
var filename = "LottieLogo2"

func makeUIView(context: UIViewRepresentableContext<LottieButton>) -> UIView {
    let view = UIView()

    let animation = Animation.named(filename)
    animationButton.animation = animation
    animationButton.contentMode = .scaleAspectFit

    animationButton.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(animationButton)

    animationButton.clipsToBounds = false
       /// Set animation play ranges for touch states
    animationButton.setPlayRange(fromMarker: "touchDownStart", toMarker: "touchDownEnd", event: .touchUpInside)
       animationButton.setPlayRange(fromMarker: "touchDownEnd", toMarker: "touchUpCancel", event: .touchUpOutside)
       animationButton.setPlayRange(fromMarker: "touchDownEnd", toMarker: "touchUpEnd", event: .touchUpInside)

    NSLayoutConstraint.activate([
        animationButton.heightAnchor.constraint(equalTo: view.heightAnchor),
        animationButton.widthAnchor.constraint(equalTo: view.widthAnchor),
    ])

    return view

}

func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieButton>) {

    }
}

And then I just have a simple view that is displaying the animation:

struct InboxView: View {
var body: some View {
    VStack {
        Button(action: {}) {
        LottieButton(filename: "inbox-notification")
        .frame(width: 100)
            }
        }
    }
}


问:
prop depto_modules.length not exist in the row, How can I resolve this?
I have a table where I need show data from another associated table. Everything works well but I receive this warning when I pass some filter:

prop depto_modules.length not exist in the row, please confirm wether the prop is right, this may cause unpredictable filter result

This warning does not affect the operation but I would like to remove this.
My table is Modules and the associated table is depto_modules(DeptoModules).

My list.vue :

```<code><template>
  <div class="">
    <alert
      :show-alert="alertShowErrors"
      :closable="alertClosable"
      :type="alertType"
      :title="alertTitle"
      :description="alertDescription"
      :show-icon="alertShowIcon"
    />
    <box box_type="solid" :title="title" :collapse="collapse" class="box-title">
      <el-row>
        <el-col :span="2">
          <el-tooltip class="item" effect="dark" content="Novo" placement="top-start">
            <el-button plain type="primary" size="mini" @click="handleInsert()">
              <i class="fas fa-plus" /><span v-if="device!=='mobile'">  Novo</span>
            </el-button>
          </el-tooltip>
        </el-col>
        <el-col :xs="11" :sm="11" :md="11" :lg="11" :offset="1">
          <el-input v-model="filters[0].value" size="mini" placeholder="Search" prefix-icon="el-icon-search" />
        </el-col>
        <el-col :span="3" :offset="1">
          <el-tooltip class="item" effect="dark" content="Update Table" placement="top-start">
            <el-button plain size="mini" @click="handleRefresh()">
              <i class="fas fa-sync" /><span v-if="device!=='mobile'">  Atualizar</span>
            </el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <data-tables
            v-loading="listLoading"
            :data="data"
            :filters="filters"
            :total="totalRows"
            :pagination-props="pageSizes"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            @expand-change="handleExpand"
            @query-change="list"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
          >
            <el-table-column align="left" min-width="35" width="70">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="Edit" placement="top-start">
                  <el-button size="mini" type="primary" icon="el-icon-edit" plain circle @click="handleEdit(scope.$index, scope.row)" />
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="Remove" placement="top-start">
                  <el-button size="mini" type="danger" icon="el-icon-delete" plain circle @click="handleDelete(scope.$index, scope.row)" />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              v-for="(column, index) in columns"
              :key="column.prop"
              :item="column"
              :index="index"
              :prop="column.prop"
              :label="column.label"
              :type="column.type"
              :resizable="column.resizable"
              :min-width="column.width"
              :align="column.align"
              :header-align="column.headerAlign"
              :formatter="cellValueRenderer"
              sortable="custom"
            />
          </data-tables>
        </el-col>
      </el-row>
    </box>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Box from '@/components/Share/box'
import Alert from '@/components/Alert'
import { iframeResize } from '@/utils/resize_iframe'
import { getStatusCode } from '@/utils/status-response'
import { numberFormat } from '@/utils/cells-format'
import Modules from '@/api/plan/modules'

export default {
  name: 'Modules',
  components: {
    Box,
    Alert
  },
  props: {
    title: {
      type: String,
      default: 'Modules List'
    },
    collapse: {
      type: Boolean,
      default: false
    },
    filterField: {
      type: String,
      default: null
    },
    filterValue: {
      type: (String, Number),
      default: null
    }
  },
  data() {
    return {
      data: [],
      columns: this.loadColumns(),
      filters: this.loadFilter(),
      selectedRow: [],
      pageSize: 10,
      perPage: 10,
      pageSizeExpand: 10,
      pageSizes: {
        background: true,
        pageSizes: [10, 20, 30, 40, 50, 100, 150, 200, 250, 300]
      },
      pageSizesExpand: {
        background: true,
        pageSizes: [10, 20, 30, 40, 50, 100, 150, 200, 250, 300]
      },
      currentPage: 1,
      currentPageExpand: 1,
      totalRows: 0,
      totalRowsExpand: 0,
      listLoading: true,
      expandLoading: false,
      alertType: 'warning',
      alertShowErrors: false,
      alertClosable: false,
      alertShowIcon: false,
      alertTitle: null,
      alertDescription: ''
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  created() {},
  mounted() {
    this.getFilter()
    this.resetAlert()
    this.list()
  },
  updated() {
    this.$nextTick(() => {
      iframeResize()
    })
  },
  methods: {
    cellValueRenderer(row, column, cellValue) {
      var value = cellValue
      if (column.type === 'money') {
        value = numberFormat(cellValue, 'money')
      }
      if (column.type === 'decimal') {
        value = numberFormat(cellValue, 'decimal')
      }
      if (column.type === 'date') {
        value = numberFormat(cellValue, 'date')
      }
      if (column.type === 'percent') {
        value = numberFormat(cellValue, 'percent')
      }
      if (typeof row[column.property] === 'boolean') {
        value = 'Inativo'
        if (cellValue) {
          value = 'Ativo'
        }
      }
      return value
    },
    loadColumns() {
      var columns = [
        { prop: 'id', label: 'ID', resizable: true, align: 'left', headerAlign: 'left', width: '30' },
        { prop: 'name', label: 'Name', resizable: true, align: 'left', headerAlign: 'left', width: '30' },
        { prop: 'path', label: 'Path', resizable: true, align: 'left', headerAlign: 'left', width: '30' },
        { prop: 'depto_modules.length', label: 'Deptos', resizable: true, align: 'left', headerAlign: 'left', width: '30' },
        { prop: 'status', label: 'Status', resizable: true, align: 'left', headerAlign: 'left', width: '30' }
      ]
      if (this.filterField) {
        for (var i = 0; i < columns.length; i++) {
          if (columns[i].prop === this.filterField) {
            columns.splice(i, 1)
          }
        }
      }
      return columns
    },
    loadFilter() {
      var columns = this.loadColumns()
      var filterItems = []
      columns.forEach(function(value) {
        filterItems.push(value.prop)
      })
      var filter = [{ prop: filterItems, value: '' }]
      return filter
    },
    getFilter() {
      if (this.getStore('FilterPageSizeModules')) {
        this.pageSize = this.getStore('FilterPageSizeModules')
      } else {
        this.pageSize = 10
      }
    },
    setFilter() {
      this.setStore('FilterPageSizeModules', this.perPage)
    },
    setParentField() {
      var params = []
      if (this.filterField) {
        params = { 'parent_id': this.filterValue }
      }
      return params
    },
    handleRefresh() {
      this.list()
    },
    handleInsert() {
      this.$router.push({ name: 'Modules_Add', query: this.setParentField() })
    },
    handleEdit(index, row) {
      if (this.filterField) {
        this.setParentField()
      }
      this.setStore('setModulesId', row.id)
      this.$router.push({ name: 'Modules_Edit' })
    },
    handleDelete(index, row) {
      this.setStore('setModulesId', row.id)
      this.delete(row.id)
    },
    handleSizeChange(val) {
      this.perPage = val
      this.setFilter()
      this.$nextTick(() => {
        iframeResize()
      })
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleSelectionChange(val) {
      this.selectedRow = val
    },
    handleExpand(row, expandedRows) {
    },
    setStore(field, value) {
      this.$session.set(field, value)
    },
    getStore(field) {
      return this.$session.get(field)
    },
    showAlert(message, title = '') {
      this.alertShowErrors = true
      this.alertClosable = true
      this.alertTitle = title
      this.alertDescription = message
    },
    resetAlert() {
      this.alertShowErrors = false
      this.alertClosable = false
      this.alertTitle = ''
      this.alertDescription = ''
    },
    formatData(data) {
      return data
    },
    async list() {
      this.resetAlert()
      this.listLoading = true
      var tables = { table: 'UsersModules, DeptoModules' }
      var select = {}
      var order = {}
      var query = { ...tables, ...select, ...order }
      if (this.filterField && this.filterValue) {
        query = { ...query, filter: this.filterField + ':' + this.filterValue }
      }
      Modules.list(query)
        .then(response => {
          this.resetAlert()
          var dados = response.data
          this.data = this.formatData(dados.data)
          this.totalRows = dados.count
          this.listLoading = false
        })
        .catch(error => {
          var err = getStatusCode(error)
          this.showAlert(err)
          this.listLoading = false
        })
    }, ...
</code>```

The warning:

My out:

Someone has some idea about how can I remove this warning?

答:
Try to change the name of property:

From: depto_modules.length

To: depto_modules_length

It's seems that el-table-column think the depto_modules.length is a sub-object.

Body:
I have a table where I need show data from another associated table. Everything works well but I receive this warning when I pass some filter:

prop depto_modules.length not exist in the row, please confirm wether the prop is right, this may cause unpredictable filter result

This warning does not affect the operation but I would like to remove this.
My table is Modules and the associated table is depto_modules(DeptoModules).

My list.vue :

<template>

    <alert
      :show-alert="alertShowErrors"
      :closable="alertClosable"
      :type="alertType"
      :title="alertTitle"
      :description="alertDescription"
      :show-icon="alertShowIcon"
    />
    <box box_type="solid" :title="title" :collapse="collapse" class="box-title">
      <el-row>
        <el-col :span="2">
          <el-tooltip class="item" effect="dark" content="Novo" placement="top-start">
            <el-button plain type="primary" size="mini" @click="handleInsert()">
                Novo
            </el-button>
          </el-tooltip>
        </el-col>
        <el-col :xs="11" :sm="11" :md="11" :lg="11" :offset="1">
          <el-input v-model="filters[0].value" size="mini" placeholder="Search" prefix-icon="el-icon-search" />
        </el-col>
        <el-col :span="3" :offset="1">
          <el-tooltip class="item" effect="dark" content="Update Table" placement="top-start">
            <el-button plain size="mini" @click="handleRefresh()">
                Atualizar
            </el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <data-tables
            v-loading="listLoading"
            :data="data"
            :filters="filters"
            :total="totalRows"
            :pagination-props="pageSizes"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            @expand-change="handleExpand"
            @query-change="list"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
          >
            <el-table-column align="left" min-width="35" width="70">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="Edit" placement="top-start">
                  <el-button size="mini" type="primary" icon="el-icon-edit" plain circle @click="handleEdit(scope.$index, scope.row)" />
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="Remove" placement="top-start">
                  <el-button size="mini" type="danger" icon="el-icon-delete" plain circle @click="handleDelete(scope.$index, scope.row)" />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              v-for="(column, index) in columns"
              :key="column.prop"
              :item="column"
              :index="index"
              :prop="column.prop"
              :label="column.label"
              :type="column.type"
              :resizable="column.resizable"
              :min-width="column.width"
              :align="column.align"
              :header-align="column.headerAlign"
              :formatter="cellValueRenderer"
              sortable="custom"
            />
          </data-tables>
        </el-col>
      </el-row>
    </box>

</template>


问:
Property 'target' does not exist on type 'string'
I am making a search bar in Typescript but it is not taking any input. The term target on my onChange method keeps giving an error that

```<code>Property 'target' does not exist on type 'string'.
</code>```

```<code>export default class userSearchPage extends Component <{}, { searchItem: string}>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: ''
    };
  }

  render() {
    return (

  <div>
    <PermanentDrawerLeft></PermanentDrawerLeft>
    <div className='main-content'>
      <SearchBar
        onChange={e => {
          this.setState({searchItem: e.target.value})
        }}

        onRequestSearch={() => console.log('onRequestSearch')}
        style={{
          margin: '0 auto',
          maxWidth: 800
        }}
      />
    </div>
  </div>
  );
}
}
</code>```

How could I fix this?

答:
Your callback onChange seems like it's already a string. So you can use it directly e.g.

```<code>onChange={e => this.setState({searchItem: e}) }
</code>```

Body:
I am making a search bar in Typescript but it is not taking any input. The term target on my onChange method keeps giving an error that

Property 'target' does not exist on type 'string'.

export default class userSearchPage extends Component <{}, { searchItem: string}>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: ''
    };
  }

  render() {
    return (

    <PermanentDrawerLeft></PermanentDrawerLeft>

      <SearchBar
        onChange={e => {
          this.setState({searchItem: e.target.value})
        }}

        onRequestSearch={() => console.log('onRequestSearch')}
        style={{
          margin: '0 auto',
          maxWidth: 800
        }}
      />

  );
}
}

How could I fix this?

Body:
Your callback onChange seems like it's already a string. So you can use it directly e.g.

onChange={e => this.setState({searchItem: e}) }


问:
Android : tgid task_struct val
I have a daemon that I continuously start and do a 'kill -9' in a loop in order to stress test a particular use case. This daemon loads a shared library which in turn opens a fd. (opening / closing of fd is in another shared library code handled in kernel) . I observe that at the time of clean up operations in the kernel library, it checks for the PID value from task_structs, (tgid) before cleaning up .
Now my observation : I sometime see that  when the daemon gets killed , i do not see a relevant tgid value instead i see a strange process ID value which of 'binder process'. As a result my clean up operations in the kernel code does not take in effect for that process ID that juts got killed by 'kill -9'

Any one knows why current->tgid value is that of a binder process and not of the daemon that gets killed. Note that my daemon does link to 'libbinder'. Not sure if that can make a difference. If I remove the linking to 'libbinder' and its relevant code from my daemon, everything seems fine

Any suggestions/ ideas please?

答:
If your userspace process opens a file, then forks another process, the open file will be duplicated in the forked process (it appears probable that this libbinder is forking off another process).

The close method of the file_operations struct in the kernel will only be called when the last reference to the file is put.  If both processes die around the same time, then the process which ends up calling the close method will be whichever one happens to die second.

Your kernel code should not be keying on tgid.  It should be attaching the data required for the cleanup operations to the struct file, not to the task_struct.

Title: Android : tgid task_struct val


问:
Live incrementing a Counter from code behind in a textBox
I have a WPF App which loops in Codebehind through data and increments a counter for each found element.

Now I would like to display the live incrementing counter as status feedback to the user.

All I get now is the value after my task has finished because we need to run it as await task.

Button Click fires the method which loops my data.

Can I update the counter in my Xaml if my method runs and not after finishing?

Solution form mm8:

Code Behind:

```<code>public partial class UserControlCounter : UserControl, INotifyPropertyChanged
{
    private int _scanStatusCounter;
    public int ScanStatusCounter
    {
        get { return _scanStatusCounter; }
        set { _scanStatusCounter = value; NotifyPropertyChanged(); }
    }

    public UserControlCounter()
    {
        InitializeComponent();
        DataContext = this;
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {

        await Task.Run(getAll);
        scanStatus.Text = "Persons " + ScanStatusCounter.ToString();
    }

    private async void getAll()
    {
        //grab data and iterate it
        string[] string_array = new string[] { "a", "b", "c", "d", "e" }; // type = System.String[]

        foreach (var i in string_array)
        {

            ScanStatusCounter++;
            await Task.Delay(100);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

That's my Xaml for the Control:

```<code>    <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Grid.Column="0" x:Name="scanStatus" Text="{Binding Path=ScanStatusCounter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
    <Button Grid.Row="0" Grid.Column="1" Click="Button_Click"> Click Me</Button>
</Grid>
</code>```

thank you

Updated working Solution added.
Thanks in advance to mm8 for holding my hand!

答:
Implement INotifyPropertyChanged and make scanStatusCounter a property:

```<code>public partial class UserControlCounter : UserControl, INotifyPropertyChanged
{
    private int _scanStatusCounter;
    public int ScanStatusCounter
    {
        get { return _scanStatusCounter; }
        set { _scanStatusCounter = value; NotifyPropertyChanged(); }
    }

    public UserControlCounter()
    {
        InitializeComponent();
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        var btn = sender as Button;
        var contentPresenter = (btn.TemplatedParent as ContentPresenter);

        var ppStatusCounter = contentPresenter.ContentTemplate.FindName("scanStatus", contentPresenter) as TextBlock;

        await Task.Run(getAll);
        ppStatusCounter.Text = "Persons " + ScanStatusCounter.ToString();
    }

    private static async void getAll()
    {
        //grab data and iterate it

        foreach (var result in data)
        {
            ScanStatusCounter++;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

You may also want to add some delay in the loop to actually be able see the counter being incremented:

```<code>private static async void getAll()
{
    //grab data and iterate it

    foreach (var result in data)
    {
        ScanStatusCounter++;
        await Task.Delay(100);
    }
}
</code>```

Body:
I have a WPF App which loops in Codebehind through data and increments a counter for each found element.

Now I would like to display the live incrementing counter as status feedback to the user.

All I get now is the value after my task has finished because we need to run it as await task.

Button Click fires the method which loops my data.

Can I update the counter in my Xaml if my method runs and not after finishing?

Solution form mm8:

Code Behind:

public partial class UserControlCounter : UserControl, INotifyPropertyChanged
{
    private int _scanStatusCounter;
    public int ScanStatusCounter
    {
        get { return _scanStatusCounter; }
        set { _scanStatusCounter = value; NotifyPropertyChanged(); }
    }

    public UserControlCounter()
    {
        InitializeComponent();
        DataContext = this;
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {

        await Task.Run(getAll);
        scanStatus.Text = "Persons " + ScanStatusCounter.ToString();
    }

    private async void getAll()
    {
        //grab data and iterate it
        string[] string_array = new string[] { "a", "b", "c", "d", "e" }; // type = System.String[]

        foreach (var i in string_array)
        {

            ScanStatusCounter++;
            await Task.Delay(100);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

That's my Xaml for the Control:

    <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Grid.Column="0" x:Name="scanStatus" Text="{Binding Path=ScanStatusCounter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
    <Button Grid.Row="0" Grid.Column="1" Click="Button_Click"> Click Me</Button>
</Grid>

thank you

Updated working Solution added.
Thanks in advance to mm8 for holding my hand!

Body:
Implement INotifyPropertyChanged and make scanStatusCounter a property:

public partial class UserControlCounter : UserControl, INotifyPropertyChanged
{
    private int _scanStatusCounter;
    public int ScanStatusCounter
    {
        get { return _scanStatusCounter; }
        set { _scanStatusCounter = value; NotifyPropertyChanged(); }
    }

    public UserControlCounter()
    {
        InitializeComponent();
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        var btn = sender as Button;
        var contentPresenter = (btn.TemplatedParent as ContentPresenter);

        var ppStatusCounter = contentPresenter.ContentTemplate.FindName("scanStatus", contentPresenter) as TextBlock;

        await Task.Run(getAll);
        ppStatusCounter.Text = "Persons " + ScanStatusCounter.ToString();
    }

    private static async void getAll()
    {
        //grab data and iterate it

        foreach (var result in data)
        {
            ScanStatusCounter++;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

You may also want to add some delay in the loop to actually be able see the counter being incremented:

private static async void getAll()
{
    //grab data and iterate it

    foreach (var result in data)
    {
        ScanStatusCounter++;
        await Task.Delay(100);
    }
}


问:
How to check if NA within replace() function in R?
In my dataset, the duration of a activity is either given in hours (column duration_hours) or in minutes (column duration_minutes). If it is given in hours, the duration_minutes column is empty (NA) and vice versa.

I now want to convert the values given in minutes into hours by dividing them by 60 (minutes).

To do so I tried this command:

df <- df %>% mutate(duration_recoded = replace(duration_minutes, !is.na(duration_minutes), duration_minutes / 60))

However, the command produces incorrect results and this warning message is shown:

```<code>Warning message:
In x[list] <- values :
  number of items to replace is not a multiple of replacement length
</code>```

Can anybody tell me where my mistake is?

Here's some sample data:

```<code>df <- structure(list(duration_hours = c(1, NA, 2, NA, 1), duration_minutes = c(NA, 25, NA, 30, NA)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
The problem in your code is that duration minutes is a vector and when you divide by 60 you are performing a vector operation. Let's use an example df:

```<code># A tibble: 7 x 1
  duration_minutes
             <dbl>
1               10
2               20
3               30
4               NA
5               50
6               NA
7               60
</code>```

In this case, df$duraction_minutes / 60 results in:

```<code>0.1666667 0.3333333 0.5000000        NA 0.8333333        NA 1.0000000
</code>```

That means that you are trying to replace every NA value with a vector of multiple values... That is why your warning message says number of items to replace is not a multiple of replacement length.

You either have to use some function that aggregates multiple values to a single value (such as sum(), mean(), first(), etc) or you have to select a single value to act as a replacement. the coalesce() function is just finding the first non-missing element.

Body:
In my dataset, the duration of a activity is either given in hours (column duration_hours) or in minutes (column duration_minutes). If it is given in hours, the duration_minutes column is empty (NA) and vice versa.

I now want to convert the values given in minutes into hours by dividing them by 60 (minutes).

To do so I tried this command:

df <- df %>% mutate(duration_recoded = replace(duration_minutes, !is.na(duration_minutes), duration_minutes / 60))

However, the command produces incorrect results and this warning message is shown:

Warning message:
In x[list] <- values :
  number of items to replace is not a multiple of replacement length

Can anybody tell me where my mistake is?

Here's some sample data:

df <- structure(list(duration_hours = c(1, NA, 2, NA, 1), duration_minutes = c(NA, 25, NA, 30, NA)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

Body:
The problem in your code is that duration minutes is a vector and when you divide by 60 you are performing a vector operation. Let's use an example df:

# A tibble: 7 x 1
  duration_minutes
             <dbl>
1               10
2               20
3               30
4               NA
5               50
6               NA
7               60

In this case, df$duraction_minutes / 60 results in:

0.1666667 0.3333333 0.5000000        NA 0.8333333        NA 1.0000000

That means that you are trying to replace every NA value with a vector of multiple values... That is why your warning message says number of items to replace is not a multiple of replacement length.

You either have to use some function that aggregates multiple values to a single value (such as sum(), mean(), first(), etc) or you have to select a single value to act as a replacement. the coalesce() function is just finding the first non-missing element.


问:
Check if field in SQL contains specific alphanumeric format
I need to test a specific Column in a SQL table to look for any variances outside of a specific alphanumeric format.  In this field, the correct format should be one alpha character followed by six numbers, like G123456.  the first letter could be anything in the alphabet (upper or lower case), and the number could be any sequence of six digits.  But the pattern is always one alpha followed by six digits.

I have done some searching but have not been able to come up with a solution.  Any suggestions would be welcome!

I am running SQL server 2008 R2.

Thanks!

答:
This SQL query will give you all Alpha-Numeric Name in SampleTable:</p>

```<code>select XYZ_ColumnName from DBName.Schema.SampleTable
where Name like '%[^a-z][^A-Z][^0-9]%'
</code>```

Body:
This SQL query will give you all Alpha-Numeric Name in SampleTable:

select XYZ_ColumnName from DBName.Schema.SampleTable
where Name like '%[^a-z][^A-Z][^0-9]%'


问:
Error 404 when trying to download Apache ActiveMQ
When i type this in my bash:

```<code>wget http://www.apache.org/dist//activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz
</code>```

I get the following:

```<code>--2020-02-17 11:21:20--  http://www.apache.org/dist//activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz
Resolving www.apache.org (www.apache.org)... 40.79.78.1, 95.216.24.32, 2a01:4f9:2a:185f::2
Connecting to www.apache.org (www.apache.org)|40.79.78.1|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://downloads.apache.org/activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz [following]
--2020-02-17 11:21:21--  https://downloads.apache.org/activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz
Resolving downloads.apache.org (downloads.apache.org)... 88.99.95.219, 2a01:4f8:10a:201a::2
Connecting to downloads.apache.org (downloads.apache.org)|88.99.95.219|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2020-02-17 11:21:21 ERROR 404: Not Found.
</code>```

Why am I getting an error 404?

答:
Only recent Apache ActiveMQ releases are available on https://downloads.apache.org/activemq/. Older releases (e.g. 5.5.0) are available in the archive area at http://archive.apache.org/dist/activemq/. This is in accordance with Apache release policy.

The specific release you're looking for is in http://archive.apache.org/dist/activemq/apache-activemq/5.5.0/. This is linked from the Apache ActiveMQ website.

Body:
When i type this in my bash:

wget http://www.apache.org/dist//activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz

I get the following:

--2020-02-17 11:21:20--  http://www.apache.org/dist//activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz
Resolving www.apache.org (www.apache.org)... 40.79.78.1, 95.216.24.32, 2a01:4f9:2a:185f::2
Connecting to www.apache.org (www.apache.org)|40.79.78.1|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://downloads.apache.org/activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz [following]
--2020-02-17 11:21:21--  https://downloads.apache.org/activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz
Resolving downloads.apache.org (downloads.apache.org)... 88.99.95.219, 2a01:4f8:10a:201a::2
Connecting to downloads.apache.org (downloads.apache.org)|88.99.95.219|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2020-02-17 11:21:21 ERROR 404: Not Found.

Why am I getting an error 404?


问:
A difference output with difference ways for make a list that only exist from the dictionary
first i used a list methods remove() to delete the item that doesn't exist in the dictionary values.
The code is like this:

```<code>rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
for num in rollNumber:
    if num not in sampleDict.values():
        rollNumber.remove(num)

print('After removing unwanted element from list', rollNumber)
</code>```

output : [47,69,76,95,97]
this is wrong answer

the second one i made a empty list and used append() methods from the item that in dictionary.values
the code is like this:

```<code>rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
new = []
for num in rollNumber:
    if num in sampleDict.values():
        new.append(num)

print('After removing unwanted element from list', new)
</code>```

output : [47,69,76,97]
this the correct answer

Do you guys know why this happens?

答:
Instead of mutating the list, try using a comprehension to generate a new list</p>

```<code>In [2]: vals = list(sampleDict.values())

In [3]: out = [v for v in rollNumber if v in vals]

In [4]: out
Out[4]: [47, 69, 76, 97]
</code>```

Body:
first i used a list methods remove() to delete the item that doesn't exist in the dictionary values.
The code is like this:

rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
for num in rollNumber:
    if num not in sampleDict.values():
        rollNumber.remove(num)

print('After removing unwanted element from list', rollNumber)

output : [47,69,76,95,97]
this is wrong answer

the second one i made a empty list and used append() methods from the item that in dictionary.values
the code is like this:

rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
new = []
for num in rollNumber:
    if num in sampleDict.values():
        new.append(num)

print('After removing unwanted element from list', new)

output : [47,69,76,97]
this the correct answer

Do you guys know why this happens?

Body:
Instead of mutating the list, try using a comprehension to generate a new list

In [2]: vals = list(sampleDict.values())

In [3]: out = [v for v in rollNumber if v in vals]

In [4]: out
Out[4]: [47, 69, 76, 97]


问:
How to save a SQLite binding into an NSString
I have the following bind statement for binding an SQLite column. I want to save this value into an NSString named journeyName. For this I have written the following statement:

```<code>NSString * journeyName = sqlite3_bind_text( compiledStatement, 1,
                                           [Gjourney UTF8String], -1,
                                           SQLITE_TRANSIENT );
</code>```

This gives me a warning that

initialization makes pointer from integer without a cast

and my app crashes.

答:
My guess you should have written

NSString* journeyName = sqlite3_bind_text( compiledStatement, 1, [Gjourney UTF8String], -1, SQLITE_TRANSIENT);

Body:
I have the following bind statement for binding an SQLite column. I want to save this value into an NSString named journeyName. For this I have written the following statement:

NSString * journeyName = sqlite3_bind_text( compiledStatement, 1,
                                           [Gjourney UTF8String], -1,
                                           SQLITE_TRANSIENT );

This gives me a warning that

initialization makes pointer from integer without a cast

and my app crashes.


答:
I think that the problem is that you are deleting elements while iterating it. You're better off using a list comprehension:

rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
rollNumber = [num for num in rollNumber if num in sampleDict.values()]

print('After removing unwanted element from list', rollNumber)
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>After removing unwanted element from list [47, 69, 76, 97]
</code>```

Title: A difference output with difference ways for make a list that only exist from the dictionary

Body:
I think that the problem is that you are deleting elements while iterating it. You're better off using a list comprehension:

rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
rollNumber = [num for num in rollNumber if num in sampleDict.values()]

print('After removing unwanted element from list', rollNumber)

Outputs:

After removing unwanted element from list [47, 69, 76, 97]