问:
How to display circle avatar on AppBar?
I am trying to display Circle Avatar on AppBar.

Here is my code

```<code>AppBar(
    ...
    actions: <Widget>[
        CircleAvatar(
            radius: 14,
            backgroundImage: userProfilePictureValue != null
                ? NetworkImage(
                    userProfilePictureValue,
                )
                : Icon(Icons.add),
        )
)
</code>```

Here is the second way which I tried

```<code>AppBar(
    ...
    actions: <Widget>[
        Container(
            width: 20,
            height: 20,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color:Colors.blueGrey
            ),
            child: StreamBuilder<String>(
                stream: userProfilePicture,
                builder: (context, snapshot) {
                    return ClipOval(
                        child: userProfilePictureValue != null
                            ? CachedNetworkImage(
                                imageUrl:
                                    "${userProfilePictureValue}",
                                fit: BoxFit.fill,
                             )
                            : Icon(
                                Icons.person,
                                size: 40,
                                color: Colors.white,
                            ),
                    );
            }),
    )]
)
</code>```

In first case the image is not displayed as circular and in second case it is displayed as egg shaped instead of circular.

答:
Your first option is the correct approach. The reason its not appearing circular is because of the radius you defined and image size you are using.  Here is a live example of the same with correct radius according to image.

Your options are

define correct radius according to the image size you are using.

Re-scale the image if required.

When your network image is null dont pass an icon to backgroundImage since it expects and ImageProvider and not Icon. So it will fail in this case.

Title: How to display circle avatar on AppBar?

Body:
I am trying to display Circle Avatar on AppBar.

Here is my code

AppBar(
    ...
    actions: <Widget>[
        CircleAvatar(
            radius: 14,
            backgroundImage: userProfilePictureValue != null
                ? NetworkImage(
                    userProfilePictureValue,
                )
                : Icon(Icons.add),
        )
)

Here is the second way which I tried

AppBar(
    ...
    actions: <Widget>[
        Container(
            width: 20,
            height: 20,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color:Colors.blueGrey
            ),
            child: StreamBuilder<String>(
                stream: userProfilePicture,
                builder: (context, snapshot) {
                    return ClipOval(
                        child: userProfilePictureValue != null
                            ? CachedNetworkImage(
                                imageUrl:
                                    "${userProfilePictureValue}",
                                fit: BoxFit.fill,
                             )
                            : Icon(
                                Icons.person,
                                size: 40,
                                color: Colors.white,
                            ),
                    );
            }),
    )]
)

In first case the image is not displayed as circular and in second case it is displayed as egg shaped instead of circular.


来源: stackexchange

问:
Helm Chart: How do I install dependencies first?
I've been developing a prototype chart that depends on some custom resource definitions that are defined in one of the child charts.

To be more specific, I'm trying to create the resources defined in the strimzi-kafka-operator within my helm chart and would like the dependency to be explicitly installed first. I followed the helm documentation and added the following to my Chart.yaml

```<code>dependencies:
- name: strimzi-kafka-operator
  version: 0.16.2
  repository: https://strimzi.io/charts/
</code>```

I ran:

$ helm dep up ./prototype-chart
$ helm install ./prototype-chart
> Error: unable to build Kubernetes objects from release manifest: unable to recognize "": no matches for kind "KafkaTopic" in version "kafka.strimzi.io/v1beta1"
```

which shows that it's trying to deploy my chart before my dependency. What is the correct way to install dependencies first and then my parent chart?

(For reference, here is the question I opened on GitHub directly with Strimzi where they informed me they aren't sure how to use their helm as a dependency:
https://github.com/strimzi/strimzi-kafka-operator/issues/2552
)

答:
Regarding CRD's: the fact that Helm by default won't manage those1 is a feature, not a bug. It will still install them if not present; but it won't modify or delete existing CRD's. The previous version of Helm (v2) does, but (speaking from experience) that can get you into all sorts of trouble if you're not careful. Quoting from the link you referenced:

There is not support at this time for upgrading or deleting CRDs using Helm. This was an explicit decision after much community discussion due to the danger for unintentional data loss. [...] One of the distinct disadvantages of the crd-install method used in Helm 2 was the inability to properly validate charts due to changing API availability (a CRD is actually adding another available API to your Kubernetes cluster). If a chart installed a CRD, helm no longer had a valid set of API versions to work against. [...] With the new crds method of CRD installation, we now ensure that Helm has completely valid information about the current state of the cluster.

The idea here is that Helm should operate only at the level of release data (adding/removing deployments, storage, etc.); but with CRD's, you're actually modifying an extension to the Kubernetes API itself, potentially inadvertently breaking other releases that use the same definitions. Consider if you're on a team that has a "library" of CRDs shared between several charts, and you want to uninstall one — formerly, With v2, Helm would happily let you modify or even delete those at will, with no checks on if/how they were used in other releases. Changes to CRDs are changes to your control plane / core API, and should be treated as such — you're modifying global resources.

In short: with v3, Helm positions itself more as a "developer" tool to define, template, and manage releases; CRDs, however, are meant to be managed independently e.g. by a "cluster administrator". At the end of the day, it's a win for all sides, since developers can setup/teardown deployments at will, with confidence that it's not going to break functionality elsewhere... and whoever's on call won't have to deal with alerts if/when you accidentally delete/modify a CRD and break things in production :)

See also the extensive discussion here for more context behind this decision.

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
I've been developing a prototype chart that depends on some custom resource definitions that are defined in one of the child charts.

To be more specific, I'm trying to create the resources defined in the strimzi-kafka-operator within my helm chart and would like the dependency to be explicitly installed first. I followed the helm documentation and added the following to my Chart.yaml

dependencies:
- name: strimzi-kafka-operator
  version: 0.16.2
  repository: https://strimzi.io/charts/

I ran:

$ helm dep up ./prototype-chart
$ helm install ./prototype-chart
> Error: unable to build Kubernetes objects from release manifest: unable to recognize "": no matches for kind "KafkaTopic" in version "kafka.strimzi.io/v1beta1"

which shows that it's trying to deploy my chart before my dependency. What is the correct way to install dependencies first and then my parent chart?

(For reference, here is the question I opened on GitHub directly with Strimzi where they informed me they aren't sure how to use their helm as a dependency:
https://github.com/strimzi/strimzi-kafka-operator/issues/2552
)


问:
How can I change the owner of the public schema in databases created via the Google Console?
In Google's SQL Cloud Postgres service, when I create a database via the Web Console for a PostgreSQL instance, it automatically sets the owner of the database's default "public" schema to be cloudsqladmin. It seems I cannot change the ownership:

```<code>mydb=> \dn
    List of schemas
  Name  |     Owner
--------+---------------
 public | cloudsqladmin
(1 row)

mydb=> alter schema public owner to postgres;
ERROR:  must be owner of schema public

mydb=> \du
                                      List of roles
     Role name     |                   Attributes                   |      Member of
-------------------+------------------------------------------------+---------------------
 cloudsqladmin     | Superuser, Create role, Create DB, Replication | {}
 cloudsqlagent     | Create role, Create DB                         | {cloudsqlsuperuser}
 cloudsqlreplica   | Replication                                    | {}
 cloudsqlsuperuser | Create role, Create DB                         | {}
 pg_signal_backend | Cannot login                                   | {}
 postgres          | Create role, Create DB                         | {cloudsqlsuperuser}
 mynewuser         | Create role, Create DB                         | {cloudsqlsuperuser}
</code>```

I also created a "mynewuser" through the web console, and cannot remove the "mynewuser" from the "cloudsqlsuperuser" group:

```<code>mydb=> alter group cloudsqlsuperuser drop user mynewuser;
ERROR:  "cloudsqlsuperuser" can't be altered
</code>```

If I wanted to create a database with a public schema that only a new user has access to (and owns), should I be doing this outside of the Google web ui? It seems like any databases I create are owned by cloudsqladmin, and any users I create are those "cloudsqlsuperuser" members. If I wanted to restrict permissions for a user, should I create that user normally via psql and bypass the web ui altogether?

答:
Connect to the database mydb by owner user (for exaple, it is mynewuser).
If you want to change the public schema owner, first you should make the user postgres owner of your database mydb:

```<code>mydb=> ALTER DATABASE mydb OWNER TO postgres;
</code>```

After that, you can change the public schema owner:

```<code>mydb=> ALTER SCHEMA public OWNER TO postgres;
</code>```

Besides, to remove your mynewuser from the cloudsqlsuperuser group (role) use:

```<code>mydb=> REVOKE cloudsqlsuperuser FROM mynewuser;
</code>```

Note: The default postgres user in Google Cloud Platform's (GCP) Cloud SQL (PostgreSQL) is not a superuser of the instance. Also, all users created from the GCP web UI have cloudsqlsuperuser role by default, and the following attributes (privileges): CREATEROLE, CREATEDB and LOGIN. They don't have the SUPERUSER or REPLICATION attributes.

ContentLicense: CC BY-SA 3.0

Body:
In Google's SQL Cloud Postgres service, when I create a database via the Web Console for a PostgreSQL instance, it automatically sets the owner of the database's default "public" schema to be cloudsqladmin. It seems I cannot change the ownership:

mydb=> \dn
    List of schemas
  Name  |     Owner
--------+---------------
 public | cloudsqladmin
(1 row)

mydb=> alter schema public owner to postgres;
ERROR:  must be owner of schema public

mydb=> \du
                                      List of roles
     Role name     |                   Attributes                   |      Member of
-------------------+------------------------------------------------+---------------------
 cloudsqladmin     | Superuser, Create role, Create DB, Replication | {}
 cloudsqlagent     | Create role, Create DB                         | {cloudsqlsuperuser}
 cloudsqlreplica   | Replication                                    | {}
 cloudsqlsuperuser | Create role, Create DB                         | {}
 pg_signal_backend | Cannot login                                   | {}
 postgres          | Create role, Create DB                         | {cloudsqlsuperuser}
 mynewuser         | Create role, Create DB                         | {cloudsqlsuperuser}

I also created a "mynewuser" through the web console, and cannot remove the "mynewuser" from the "cloudsqlsuperuser" group:

mydb=> alter group cloudsqlsuperuser drop user mynewuser;
ERROR:  "cloudsqlsuperuser" can't be altered

If I wanted to create a database with a public schema that only a new user has access to (and owns), should I be doing this outside of the Google web ui? It seems like any databases I create are owned by cloudsqladmin, and any users I create are those "cloudsqlsuperuser" members. If I wanted to restrict permissions for a user, should I create that user normally via psql and bypass the web ui altogether?

Body:
Connect to the database mydb by owner user (for exaple, it is mynewuser).
If you want to change the public schema owner, first you should make the user postgres owner of your database mydb:

mydb=> ALTER DATABASE mydb OWNER TO postgres;

After that, you can change the public schema owner:

mydb=> ALTER SCHEMA public OWNER TO postgres;

Besides, to remove your mynewuser from the cloudsqlsuperuser group (role) use:

mydb=> REVOKE cloudsqlsuperuser FROM mynewuser;

Note: The default postgres user in Google Cloud Platform's (GCP) Cloud SQL (PostgreSQL) is not a superuser of the instance. Also, all users created from the GCP web UI have cloudsqlsuperuser role by default, and the following attributes (privileges): CREATEROLE, CREATEDB and LOGIN. They don't have the SUPERUSER or REPLICATION attributes.


答:
try this

```<code>dfw %>%
 mutate(qq = quantile(Hs.Mod, probs = c(0.99)),
        qq_gt99 = ifelse(qq<= Hs.Mod, 1, 0)) %>%
 ggplot(aes(x=Hs.Mod, y = Hs.Obs, col= as.factor(qq_gt99))) + geom_point()
</code>```

if you order the observations first

```<code>dfw %>%
  mutate(mod_ordered = sort(Hs.Mod),
         obs_ordered = sort(Hs.Obs),
         qq = quantile(mod_ordered, probs = c(0.99)),
         qq_gt99 = ifelse(qq<= mod_ordered, 1, 0)) %>%

   ggplot(aes(x=mod_ordered, y = obs_ordered, col=
 as.factor(qq_gt99))) + geom_point()
</code>```

Title: Colour a Q-Q plot comparing two distributions by quartiles in R

Body:
I am trying to construct a Q-Q plot comparing two distributions, with the 99th percentile colored like the following example:

However I am not sure how to achieve this, here is a subset of my data:

dfw <- structure(list(Date.Time = structure(c(848502000, 848509200,
                                               848512800, 848520000, 848523600, 848530800, 848534400, 848541600,
                                               848545200, 848552400, 848556000, 848563200, 848566800, 848574000,
                                               848577600, 848588400, 848595600, 848599200, 848606400, 848610000,
                                               848617200, 848620800, 848628000, 848631600, 848638800, 848642400,
                                               848649600, 848653200, 848660400, 848664000, 848674800, 848682000,
                                               848685600, 848692800, 848696400, 848703600, 848707200, 848714400,
                                               848718000, 848725200, 848728800, 848736000, 848739600, 848746800,
                                               848750400, 848761200, 848768400, 848772000, 848779200, 848782800,
                                               848790000, 848793600, 848800800, 848804400, 848811600, 848815200,
                                               848822400, 848826000, 848833200, 848847600, 848854800, 848858400,
                                               848865600, 848869200, 848876400, 848880000, 848887200, 848890800,
                                               848898000, 848901600, 848908800, 848912400, 848919600, 848923200,
                                               848934000, 848941200, 848944800, 848952000, 848955600, 848962800,
                                               848966400, 848973600, 848977200, 848984400, 848988000, 848995200,
                                               848998800, 849006000, 849009600, 853682400, 853686000, 853714800,
                                               853718400, 853725600, 853729200, 853736400, 853750800, 853758000,
                                               853761600, 853768800), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
                       Hs.Mod = c(1.5960001, 1.5600001, 1.5480001, 1.552, 1.552,
                                  1.534, 1.5180001, 1.462, 1.4260001, 1.3740001, 1.36, 1.3340001,
                                  1.3080001, 1.2720001, 1.256, 1.218, 1.212, 1.21, 1.2060001,
                                  1.2160001, 1.248, 1.25, 1.25, 1.264, 1.3560001, 1.394, 1.3700001,
                                  1.332, 1.2900001, 1.2800001, 1.268, 1.2800001, 1.2800001,
                                  1.3240001, 1.3240001, 1.286, 1.2540001, 1.19, 1.172, 1.1700001,
                                  1.1860001, 1.2340001, 1.274, 1.3640001, 1.4120001, 1.58,
                                  1.6580001, 1.6660001, 1.682, 1.748, 1.9280001, 1.9800001,
                                  2.026, 2.052, 2.214, 2.328, 2.4320002, 2.39, 2.2180002, 1.9080001,
                                  1.792, 1.7400001, 1.7140001, 1.7140001, 1.692, 1.6680001,
                                  1.608, 1.58, 1.536, 1.524, 1.5640001, 1.5760001, 1.6100001,
                                  1.6240001, 1.6120001, 1.5920001, 1.58, 1.542, 1.5200001,
                                  1.48, 1.4640001, 1.4260001, 1.406, 1.386, 1.3820001, 1.34,
                                  1.312, 1.268, 1.248, 1.8080001, 1.7960001, 1.644, 1.6420001,
                                  1.6600001, 1.6880001, 1.7820001, 2.138, 2.2740002, 2.2940001,
                                  2.252), Hs.Obs = c(1.741, 1.524, 1.618, 1.658, 1.697, 1.822,
                                                     1.792, 1.463, 1.433, 1.376, 1.208, 1.299, 1.255, 1.304, 1.328,
                                                     1.182, 1.282, 1.293, 1.228, 1.281, 1.45, 1.356, 1.501, 1.5,
                                                     1.356, 1.477, 1.408, 1.544, 1.497, 1.768, 2.04, 2.074, 2.042,
                                                     2.147, 2.224, 2.022, 2.017, 2.047, 2.353, 2.597, 2.838, 2.67,
                                                     2.762, 2.687, 2.734, 2.738, 2.938, 2.795, 2.549, 2.669, 2.447,
                                                     2.676, 2.577, 2.383, 2.362, 2.284, 2.341, 2.33, 2.397, 2.498,
                                                     2.317, 2.373, 2.377, 2.362, 2.218, 2.226, 1.97, 2.087, 1.874,
                                                     2.116, 2.022, 1.886, 2.046, 1.879, 1.638, 1.677, 1.638, 1.647,
                                                     1.551, 1.596, 1.591, 1.384, 1.345, 1.522, 1.469, 1.503, 1.459,
                                                     1.327, 1.453, 2.448, 2.235, 2.104, 1.958, 2.118, 2.209, 2.034,
                                                     2.229, 2.505, 2.163, 2.372)), row.names = c(NA, 100L), class = "data.frame")

Code to make the Q-Q plot:

ggplot(data=dfw, aes(x=sort(Hs.Obs), y=sort(Hs.Mod))) + geom_point(shape = 1, size =2) + xlab('Obs') + ylab('Model')+
  theme_bw()+
  geom_abline(linetype=2)

Code attempting to colour the 99th percentile:

ggplot(data=dfw, aes(x=sort(Hs.Obs), y=sort(Hs.Mod), col=cut(Hs.Mod,quantile(Hs.Mod, probs = .99)))) +
  geom_point(shape = 1, size =2) + xlab('Obs') + ylab('Model')+
  theme_bw()+
  geom_abline(linetype=2)

Resulting plot:

I'm looking for some help to sort this out, as the attempts I have tried aren't working.
Thanks in advance!

Body:
try this

dfw %>%
 mutate(qq = quantile(Hs.Mod, probs = c(0.99)),
        qq_gt99 = ifelse(qq<= Hs.Mod, 1, 0)) %>%
 ggplot(aes(x=Hs.Mod, y = Hs.Obs, col= as.factor(qq_gt99))) + geom_point()

if you order the observations first

dfw %>%
  mutate(mod_ordered = sort(Hs.Mod),
         obs_ordered = sort(Hs.Obs),
         qq = quantile(mod_ordered, probs = c(0.99)),
         qq_gt99 = ifelse(qq<= mod_ordered, 1, 0)) %>%

   ggplot(aes(x=mod_ordered, y = obs_ordered, col=
 as.factor(qq_gt99))) + geom_point()


问:
How to get the ref value in Higher order component?
I have a component where i am passing the ref value. I need to get the passed ref value in Higher Order component.
Here is the code example:
Component wrapped with HOC:

```<code>import React from "react";
import HOC from './hoc';
const MeasuredInput = () => {
  const ref = React.createRef();
  return (
    <div>
      <button ref={ref}>Click me!</button>
    </div>
  )
};
export default HOC(MeasuredInput);
</code>```

Higher Order Component:

```<code>import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
  function NewComponent(props) {
    const { forwardedRef } = props;
    return <OriginalComponent ref={forwardedRef} {...props} />;
  }
  return React.forwardRef((props, ref) => {
    return <NewComponent {...props} forwardedRef={ref} />;
  });
};
</code>```

Thanks in Advance

答:
You would need to create the ref in the HOC and pass it down, not the other way around. Data flows down and HOC is wrapping the component.

```<code>import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
  return function(props) {
    const ref = useRef();
    return <OriginalComponent ref={ref} {...props} />
  }
};
</code>```

Original Component:

```<code>import React from "react";
import HOC from './hoc';
const MeasuredInput = React.forwardRef((props, ref) => {
  return (
    <div>
      <button ref={ref}>Click me!</button>
    </div>
  )
});
export default HOC(MeasuredInput);
</code>```

Body:
I have a component where i am passing the ref value. I need to get the passed ref value in Higher Order component.
Here is the code example:
Component wrapped with HOC:

import React from "react";
import HOC from './hoc';
const MeasuredInput = () => {
  const ref = React.createRef();
  return (

      <button ref={ref}>Click me!</button>

  )
};
export default HOC(MeasuredInput);

Higher Order Component:

import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
  function NewComponent(props) {
    const { forwardedRef } = props;
    return <OriginalComponent ref={forwardedRef} {...props} />;
  }
  return React.forwardRef((props, ref) => {
    return <NewComponent {...props} forwardedRef={ref} />;
  });
};

Thanks in Advance

Body:
You would need to create the ref in the HOC and pass it down, not the other way around. Data flows down and HOC is wrapping the component.

import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
  return function(props) {
    const ref = useRef();
    return <OriginalComponent ref={ref} {...props} />
  }
};

Original Component:

import React from "react";
import HOC from './hoc';
const MeasuredInput = React.forwardRef((props, ref) => {
  return (
    <div>
      <button ref={ref}>Click me!</button>
    </div>
  )
});
export default HOC(MeasuredInput);


问:
Cleaning Unwanted Fields From GraphQL Responses
I have an object that my GraphQL client requests.

It's a reasonably simple object:

```<code>type Element {
    content: [ElementContent]
    elementId: String
    name: String
    notes: String
    type: String
    createdAt: String
    updatedAt: String
  }
</code>```

With the special type ElementContent, which is tiny and looks like this:

```<code>  type ElementContent {
    content: String
    locale: String
  }
</code>```

Now, when I query this on the clientside, both the top level object and the lower level object has additional properties (which interfere with updating the object if I attempt to clone the body exactly-as-is);

Notably, GraphQL seems to supply a __typename property in the parent object, and in the child objects, they have typename and a Symbol(id) property as well.

I'd love to copy this object to state, update in state, then clone the state and ship it to my update mutation. However, I get roadblocked because of unknown properties that GraphQL itself supplies.

I've tried doing:

delete element.__typename to good effect, but then I also need to loop through the children (a dynamic array of objects), and likely have to remove those properties as well.

I'm not sure if I'm missing something during this equation, or I should just struggle through the code and loop + delete (I received errors attempting to do a forEach loop initially). Is there a better strategy for what I'm attempting to do? Or am I on the right path and just need some good loop code to clean unwanted properties?

答:
If you want to wipe up __typename from GraphQL response (from the root and its children), you can use graphql-anywhere package.

Something like:
const wipedData = filter(inputFragment, rcvData);

inputFragment is a fragment defines the fields (You can see details here)

rcvData is the received data from GraphQL query

By using the filter function, the wipedData includes only required fields you need to pass as mutation input.

Body:
I have an object that my GraphQL client requests.

It's a reasonably simple object:

type Element {
    content: [ElementContent]
    elementId: String
    name: String
    notes: String
    type: String
    createdAt: String
    updatedAt: String
  }

With the special type ElementContent, which is tiny and looks like this:

  type ElementContent {
    content: String
    locale: String
  }

Now, when I query this on the clientside, both the top level object and the lower level object has additional properties (which interfere with updating the object if I attempt to clone the body exactly-as-is);

Notably, GraphQL seems to supply a __typename property in the parent object, and in the child objects, they have typename and a Symbol(id) property as well.

I'd love to copy this object to state, update in state, then clone the state and ship it to my update mutation. However, I get roadblocked because of unknown properties that GraphQL itself supplies.

I've tried doing:

delete element.__typename to good effect, but then I also need to loop through the children (a dynamic array of objects), and likely have to remove those properties as well.

I'm not sure if I'm missing something during this equation, or I should just struggle through the code and loop + delete (I received errors attempting to do a forEach loop initially). Is there a better strategy for what I'm attempting to do? Or am I on the right path and just need some good loop code to clean unwanted properties?


问:
JSONB integer array contains value
I have a table Directory like below with jsonb column

```<code>id: 1
folder:
  {"file_ids"=>[639,12,28]},
 options:{}

id: 2
folder:
  {"file_ids"=>[28]},
options:{}

id: 3
folder:
  {"file_ids"=>[12]},
options:{}

id: 4
folder:
 "file_ids"=>[639]},
options:{}
</code>```

How we query all directories which contain any of file ids with 12,28, when trying below code it is always throwing error?

```<code>Directory.where("directories.folder->>'file_ids' = ANY(ARRAY[?]::int[])", [12,28])
</code>```

I need the result:

```<code>    id: 1
    folder:
      {"file_ids"=>[639,12,28]},
     options:{}

    id: 2
    folder:
      {"file_ids"=>[28]},
    options:{}

    id: 3
    folder:
      {"file_ids"=>[12]},
    options:{}
</code>```

Is there any other way to query details?

答:
Finally, I got one solution,

I have converted all integer value to the string  ['12','28']

```<code>Directory.where("directories.folder->>'file_ids' ~* any (ARRAY[?])", ['28','12'])
</code>```

Title: JSONB integer array contains value

Body:
I have a table Directory like below with jsonb column

id: 1
folder:
  {"file_ids"=>[639,12,28]},
 options:{}

id: 2
folder:
  {"file_ids"=>[28]},
options:{}

id: 3
folder:
  {"file_ids"=>[12]},
options:{}

id: 4
folder:
 "file_ids"=>[639]},
options:{}

How we query all directories which contain any of file ids with 12,28, when trying below code it is always throwing error?

Directory.where("directories.folder->>'file_ids' = ANY(ARRAY[?]::int[])", [12,28])

I need the result:

    id: 1
    folder:
      {"file_ids"=>[639,12,28]},
     options:{}

    id: 2
    folder:
      {"file_ids"=>[28]},
    options:{}

    id: 3
    folder:
      {"file_ids"=>[12]},
    options:{}

Is there any other way to query details?

Body:
Finally, I got one solution,

I have converted all integer value to the string  ['12','28']

Directory.where("directories.folder->>'file_ids' ~* any (ARRAY[?])", ['28','12'])


问:
EntityException: The underlying provider failed on Open. Can one server closing a db connection, make another server fail on opening?
I am experiencing database connection errors with an ASP.NET application written in VB, running on three IIS servers. The underlying database is MS Access, which is on a shared network device. It uses Entity Framework, code first implementation and JetEntityFrameworkProvider.

The application is running stable. But, approximately 1 out of 1000 attempts to open the database connection fails with either one of the following two errors:

```<code>06:33:50   DbContext  "Failed to open connection at 2/12/2020 6:33:50 AM +00:00 with error:
Cannot open database ''.  It may not be a database that your application recognizes, or the file may be corrupt.
</code>```

Or

```<code>14:04:39   DbContext  "Failed to open connection at 2/13/2020 2:04:39 PM +00:00 with error:
Could not use ''; file already in use.
</code>```

One second later, with refreshing (F5), the error is gone and it works again.

Details about the environment and used code.

Connection String

```<code><add name="DbContext" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=x:\thedatabase.mdb;Jet OLEDB:Database Password=xx;OLE DB Services=-4;" providerName="JetEntityFrameworkProvider" />
</code>```

DbContext management

The application uses public property to access DbContext. DbContext is kept in the HttpContext.Current.Items collection for the lifetime of the request, and is disposed at it’s end.

```<code>Public Shared ReadOnly Property Instance() As DbContext
    Get
        SyncLock obj
            If Not HttpContext.Current.Items.Contains("DbContext") Then
                HttpContext.Current.Items.Item("DbContext") = New DbContext()
            End If

            Return HttpContext.Current.Items.Item("DbContext")
        End SyncLock
    End Get
End Property
</code>```

BasePage inits and disposes the DbContext.

```<code>Protected Overrides Sub OnInit(e As EventArgs)
    MyBase.OnInit(e)
    DbContext = Data.DbContext.Instance
    ...
End Sub

Protected Overrides Sub OnUnload(e As EventArgs)
    MyBase.OnUnload(e)
    If DbContext IsNot Nothing Then DbContext.Dispose()
End Sub
</code>```

What I have tried

Many of the questions on SO which address above error messages, deal with generally not being able to establish a connection to the database – they can’t connect at all. That’s  different with this case. Connection works 99,99% of the time.

Besides that, I have checked:

Permissions: Full access is granted for share where .mdb (database) and .ldb (locking file) resides.

Network connection: there are no connection issues to the shared device; it’s a Gigabit LAN connection

Maximum number of 255 concurrent connections is not reached

Maximum size of database not exceeded (db has only 5 MB)

Changed the compile option from “Any CPU” to “x86” as suggested in this MS Dev-Net post

Quote: I was getting the same "Cannot open database ''" error, but completely randomly (it seemed). The MDB file was less than 1Mb, so no issue with a 2Gb limit as mentioned a lot with this error.
  It worked 100% on 32 bit versions of windows, but I discovered that the issues were on 64 bit installations.
  The app was being compiled as "Any CPU".
  I changed the compile option from "Any CPU" to "x86" and the problem has disappeared.

Nothing helped so far.

To gather more information, I attached an Nlog logger to the DbContext which writes all database actions and queries to a log file.

```<code>Shared Log As Logger = LogManager.GetLogger("DbContext")
Me.Database.Log = Sub(s) Log.Debug(s)
</code>```

Investigating the logs I figured out that when one of the above errors occured on one server, another one of the servers (3 in total) has closed the db connection at exactly the same time.
Here two examples which correspond to the above errors:

```<code>06:33:50   DbContext  "Closed connection at 2/12/2020 6:33:50 AM +00:00
14:04:39   DbContext  "Closed connection at 2/13/2020 2:04:39 PM +00:00
</code>```

Assumption

When all connections of a DbContext have been closed, the according record is removed from the .ldb lock file. When a connection to the db is being opened, a record will be added to the lock file. When these two events occur at the exact same time, from two different servers, there is a write conflict to the .ldb lock file, which results in on of the errors from above.

Question

Can anyone confirm or prove this wrong? Has anyone experienced this behaviour? Maybe I am missing something else. I’d appreciate your input and experience on this.

If my assumption is true, a solution could be to use a helper class for accessing db, which catches and handles this error, waiting for a minimal time period and trying again.

But this feels kind of wrong. So I am also open to suggestions for a “proper” solution.

EDIT: The "proper" solution would be using a DBMS Server (as stated in the comments below). I'm aware of this. For now, I have to deal with this design mistake without being responsible for it. Also, I can't change it in the short run.

答:
You went wrong at the design stage: The MS Access database engine is unfit for ASP.Net sites, and this is explicitly stated on multiple places, e.g. the official download page under details.

The Access Database Engine 2016 Redistributable is not intended .... To be used by ... a program called from server-side web application such as ASP.NET

If you really have to work with an Access database, you can run a helper class that retries in case of common errors. But I don't recommend it.

The proper solution here is using a different RDBMS which exhibits stateless behavior. I recommend SQL Server Express, which has limitations, but if you exceed those you will be far beyond what Access supports, and wont cause errors like this.

Body:
I am experiencing database connection errors with an ASP.NET application written in VB, running on three IIS servers. The underlying database is MS Access, which is on a shared network device. It uses Entity Framework, code first implementation and JetEntityFrameworkProvider.

The application is running stable. But, approximately 1 out of 1000 attempts to open the database connection fails with either one of the following two errors:

06:33:50   DbContext  "Failed to open connection at 2/12/2020 6:33:50 AM +00:00 with error:
Cannot open database ''.  It may not be a database that your application recognizes, or the file may be corrupt.

Or

14:04:39   DbContext  "Failed to open connection at 2/13/2020 2:04:39 PM +00:00 with error:
Could not use ''; file already in use.

One second later, with refreshing (F5), the error is gone and it works again.

Details about the environment and used code.

Connection String

<add name="DbContext" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=x:\thedatabase.mdb;Jet OLEDB:Database Password=xx;OLE DB Services=-4;" providerName="JetEntityFrameworkProvider" />

DbContext management

The application uses public property to access DbContext. DbContext is kept in the HttpContext.Current.Items collection for the lifetime of the request, and is disposed at it’s end.

Public Shared ReadOnly Property Instance() As DbContext
    Get
        SyncLock obj
            If Not HttpContext.Current.Items.Contains("DbContext") Then
                HttpContext.Current.Items.Item("DbContext") = New DbContext()
            End If

            Return HttpContext.Current.Items.Item("DbContext")
        End SyncLock
    End Get
End Property

BasePage inits and disposes the DbContext.

Protected Overrides Sub OnInit(e As EventArgs)
    MyBase.OnInit(e)
    DbContext = Data.DbContext.Instance
    ...
End Sub

Protected Overrides Sub OnUnload(e As EventArgs)
    MyBase.OnUnload(e)
    If DbContext IsNot Nothing Then DbContext.Dispose()
End Sub

What I have tried

Many of the questions on SO which address above error messages, deal with generally not being able to establish a connection to the database – they can’t connect at all. That’s  different with this case. Connection works 99,99% of the time.

Besides that, I have checked:

Permissions: Full access is granted for share where .mdb (database) and .ldb (locking file) resides.

Network connection: there are no connection issues to the shared device; it’s a Gigabit LAN connection

Maximum number of 255 concurrent connections is not reached

Maximum size of database not exceeded (db has only 5 MB)

Changed the compile option from “Any CPU” to “x86” as suggested in this MS Dev-Net post

Quote: I was getting the same "Cannot open database ''" error, but completely randomly (it seemed). The MDB file was less than 1Mb, so no issue with a 2Gb limit as mentioned a lot with this error.
  It worked 100% on 32 bit versions of windows, but I discovered that the issues were on 64 bit installations.
  The app was being compiled as "Any CPU".
  I changed the compile option from "Any CPU" to "x86" and the problem has disappeared.

Nothing helped so far.

To gather more information, I attached an Nlog logger to the DbContext which writes all database actions and queries to a log file.

Shared Log As Logger = LogManager.GetLogger("DbContext")
Me.Database.Log = Sub(s) Log.Debug(s)

Investigating the logs I figured out that when one of the above errors occured on one server, another one of the servers (3 in total) has closed the db connection at exactly the same time.
Here two examples which correspond to the above errors:

06:33:50   DbContext  "Closed connection at 2/12/2020 6:33:50 AM +00:00
14:04:39   DbContext  "Closed connection at 2/13/2020 2:04:39 PM +00:00

Assumption

When all connections of a DbContext have been closed, the according record is removed from the .ldb lock file. When a connection to the db is being opened, a record will be added to the lock file. When these two events occur at the exact same time, from two different servers, there is a write conflict to the .ldb lock file, which results in on of the errors from above.

Question

Can anyone confirm or prove this wrong? Has anyone experienced this behaviour? Maybe I am missing something else. I’d appreciate your input and experience on this.

If my assumption is true, a solution could be to use a helper class for accessing db, which catches and handles this error, waiting for a minimal time period and trying again.

But this feels kind of wrong. So I am also open to suggestions for a “proper” solution.

EDIT: The "proper" solution would be using a DBMS Server (as stated in the comments below). I'm aware of this. For now, I have to deal with this design mistake without being responsible for it. Also, I can't change it in the short run.


问:
How to hide NullPointer Warnings (due to NoArgsConstructor with force=true) in IntelliJ?
I have created a Java application using Dropwizard and Weld. I have also included Lombok and I have currently annotated my service classes like:

```<code>@Slf4j
@ApplicationScoped
@NoArgsConstructor(force = true)
@RequiredArgsConstructor(onConstructor = @__({@Inject}))
public class MovieRequestService {

    private final MovieService movieService;
    private final ActorService actorService;
</code>```

It works fine and I am happy with it. The RequiredArgsConstructor is useful for my Unit tests. The NoArgsConstructor is necessary for Weld. force = true has to be set because of the final keywords... But this also leads to the fact that IntelliJ warns me on every single place where I use the movieService or actorService....

What should I do? Can I get rid of the warnings?

答: "Force=true" parameter of @NoArgsConstructor annotation means that fields are initialized to @Nullable value, so the warnings of "Constant conditions & exceptions" inspection (Java | Probable bugs | Constant conditions & exceptions) about possible NullPointerException are correct. You may disable the inspection's option "Report problems that happen only on some code paths" to get rid of the warning.</p>

Body:
I have created a Java application using Dropwizard and Weld. I have also included Lombok and I have currently annotated my service classes like:

@Slf4j
@ApplicationScoped
@NoArgsConstructor(force = true)
@RequiredArgsConstructor(onConstructor = @__({@Inject}))
public class MovieRequestService {

    private final MovieService movieService;
    private final ActorService actorService;

It works fine and I am happy with it. The RequiredArgsConstructor is useful for my Unit tests. The NoArgsConstructor is necessary for Weld. force = true has to be set because of the final keywords... But this also leads to the fact that IntelliJ warns me on every single place where I use the movieService or actorService....

What should I do? Can I get rid of the warnings?


问:
Why does apache http client about 2 time slower then URL.openConnection in java?
Consider this code:

```<code>package com.zip;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Date;

import static com.diffplug.common.base.Errors.rethrow;

/**
 * @author nsheremet
 */
public class ParallelDownload2 {
  public static int THREADCOUNT = 20;
  private static final String URL = "https://server.com/myfile.zip";
  public static String OUTPUT = "C:\\!deleteme\\myfile.zip";
  public static void main(String[] args) throws Exception {
    System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
    System.out.println(new Date());

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet request = new HttpGet(URL);
    request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
    CloseableHttpResponse response = rethrow().wrap(() -> httpClient.execute(request)).get();
    Long contentLength = Long.parseLong(response.getFirstHeader("Content-Length").getValue());
    long blocksize = contentLength / THREADCOUNT;

    RandomAccessFile randomAccessFile = new RandomAccessFile(new File(OUTPUT), "rwd");
    randomAccessFile.setLength(contentLength);
    randomAccessFile.close();
    response.close();

    for (long i = 0; i <THREADCOUNT; i++) {
      long startpos = i * blocksize;
      long endpos = (i + 1) * blocksize - 1;
      if (i == THREADCOUNT - 1) {
        endpos = contentLength;
      }
      new Thread(new DownloadTask(i, startpos, endpos)).start();
    }
    System.out.println(new Date());
  }

  public static class DownloadTask implements Runnable {

    public DownloadTask(
        long id,
        long startpos,
        long endpos
    ) {
      this.id = id;
      this.startpos = startpos;
      this.endpos = endpos;
    }

    long id;
    long startpos;
    long endpos;

    @Override
    public void run() {
      try {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet request = new HttpGet(URL);
        request.addHeader("Range", "bytes=" + startpos + "-" + endpos + "");
        request.addHeader("Connection", "keep-alive");
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
        CloseableHttpResponse response = rethrow().wrap(() -> httpClient.execute(request)).get();

        if (response.getStatusLine().getStatusCode() == 206) {

          InputStream is = response.getEntity().getContent();
          RandomAccessFile randomAccessFile = new RandomAccessFile(new File(OUTPUT), "rwd");
          randomAccessFile.seek(startpos);
          int len = 0;
          byte[] buffer = new byte[1024*10];
          while ((len = is.read(buffer)) != -1) {
            randomAccessFile.write(buffer, 0, len);
          }
          is.close();
          randomAccessFile.close();
          System.out.println("Thread "+ Thread.currentThread().getId() +": Download");
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      System.out.println(new Date());
    }

  }

}
</code>```

This is a modified copy from this one which is written via simple URL.openConnection. Why URL.openConnection with multithreading donwload the file with 10 Mb/sec while apach http client version speed mostly between 1-5 Mb/sec? Am I missed something in http apache client settings?

UPDATED

I use multiple HttpClients because single object leads to same performance as 1 connection via URL

Http apache client is used in mane high performance servers ,so I believe there is definitelly configuration issue. But what exactly?

About code

This of course not production ready code and should be considered as protote where I want to make multithreading download work fast.

About nultithreading

I can not explain why because I am not owner of downloading resource but multi threading downloading speed much faster (10 times) the single thread.

答:
Few possibilities.

(1) The difference might not be transfer speed but initial latency when connecting. I had a similar problem in the past and the culprit turned out to be IPv6. Initial request was done on IPv6 and it was falling back to IPv4 silently, but only after a timeout.

Try running with -Djava.net.preferIPv4Stack=true, or specify host as numerical IPv4 quad and see if it makes a difference.

(2) The difference might be due to https implementation possibly cheking certificate paths, online revocation lists etc. Check with http URL if it makes a difference. If it does, look at Apache's documentation how to configure https behaviour to your liking.

(3) In any case, runing tcpdump or wireshark will likely give you more useful information.

Body:
Consider this code:

package com.zip;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Date;

import static com.diffplug.common.base.Errors.rethrow;

/**
 * @author nsheremet
 */
public class ParallelDownload2 {
  public static int THREADCOUNT = 20;
  private static final String URL = "https://server.com/myfile.zip";
  public static String OUTPUT = "C:\\!deleteme\\myfile.zip";
  public static void main(String[] args) throws Exception {
    System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
    System.out.println(new Date());

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet request = new HttpGet(URL);
    request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
    CloseableHttpResponse response = rethrow().wrap(() -> httpClient.execute(request)).get();
    Long contentLength = Long.parseLong(response.getFirstHeader("Content-Length").getValue());
    long blocksize = contentLength / THREADCOUNT;

    RandomAccessFile randomAccessFile = new RandomAccessFile(new File(OUTPUT), "rwd");
    randomAccessFile.setLength(contentLength);
    randomAccessFile.close();
    response.close();

    for (long i = 0; i <THREADCOUNT; i++) {
      long startpos = i * blocksize;
      long endpos = (i + 1) * blocksize - 1;
      if (i == THREADCOUNT - 1) {
        endpos = contentLength;
      }
      new Thread(new DownloadTask(i, startpos, endpos)).start();
    }
    System.out.println(new Date());
  }

  public static class DownloadTask implements Runnable {

    public DownloadTask(
        long id,
        long startpos,
        long endpos
    ) {
      this.id = id;
      this.startpos = startpos;
      this.endpos = endpos;
    }

    long id;
    long startpos;
    long endpos;

    @Override
    public void run() {
      try {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet request = new HttpGet(URL);
        request.addHeader("Range", "bytes=" + startpos + "-" + endpos + "");
        request.addHeader("Connection", "keep-alive");
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
        CloseableHttpResponse response = rethrow().wrap(() -> httpClient.execute(request)).get();

        if (response.getStatusLine().getStatusCode() == 206) {

          InputStream is = response.getEntity().getContent();
          RandomAccessFile randomAccessFile = new RandomAccessFile(new File(OUTPUT), "rwd");
          randomAccessFile.seek(startpos);
          int len = 0;
          byte[] buffer = new byte[1024*10];
          while ((len = is.read(buffer)) != -1) {
            randomAccessFile.write(buffer, 0, len);
          }
          is.close();
          randomAccessFile.close();
          System.out.println("Thread "+ Thread.currentThread().getId() +": Download");
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      System.out.println(new Date());
    }

  }

}

This is a modified copy from this one which is written via simple URL.openConnection. Why URL.openConnection with multithreading donwload the file with 10 Mb/sec while apach http client version speed mostly between 1-5 Mb/sec? Am I missed something in http apache client settings?

UPDATED

I use multiple HttpClients because single object leads to same performance as 1 connection via URL

Http apache client is used in mane high performance servers ,so I believe there is definitelly configuration issue. But what exactly?

About code

This of course not production ready code and should be considered as protote where I want to make multithreading download work fast.

About nultithreading

I can not explain why because I am not owner of downloading resource but multi threading downloading speed much faster (10 times) the single thread.


问:
A common ICommonService pattern for multiple Domain objects
I'm writing up the Data layer of server-side blazor SPA (one project only) and I'm following a sample where the teacher plays with a single domain object: an Employee. So he has a class EmployeeService to be injected and this class implements IEmployeeService. In my case, I have a few more such classes:

```<code>public interface IDesignManagerService
{
    Task<List<DesignManager>> GetDesignManagers();
    Task<bool> CreateDesignManager(DesignManager newStage);
    Task<bool> EditDesignManager(byte id, DesignManager modifiedDesignManager);
    Task<DesignManager> SingleDesignManager(byte id);
    Task<bool> DeleteEmployee(byte id);
}

public interface IFundedService
{
    Task<List<Funded>> GetFunded();
    Task<bool> CreateFunded(Funded newStage);
    Task<bool> EditFunded(byte id, Funded modifiedFunded);
    Task<Funded> SingleFunded(byte id);
    Task<bool> DeleteEmployee(byte id);
}

public interface IGateService
{
    Task<List<Gate>> GetGates();
    Task<bool> CreateGate(Gate newStage);
    Task<bool> EditGate(byte id, Gate modifiedGate);
    Task<Gate> SingleGate(byte id);
    Task<bool> DeleteEmployee(byte id);
}
</code>```

Immediately, I feel like there should be a common interface having the basic methods so I can somehow use the dynamic type like Create<Employee> or Create<Gate>. Can this be accomplished here? I know what I might want but am unable to dig for help due to a lack of familiarity with the pattern.

答:
Microsoft has already provide a sample for this pattern. See official docs and the source code on GitHub.

To answer your question it self, you need a generic IAsyncRepository as the common interface:

// an empty marker interface
public interface IAggregateRoot{ }

// a common entity that has an `Id` property
public abstract class BaseEntity
{
    public virtual int Id { get; protected set; }
}

// the common Repo interface
public interface IAsyncRepository<T> where T : BaseEntity, IAggregateRoot
{
    Task<T> GetByIdAsync(int id);
    Task<IReadOnlyList<T>> ListAllAsync();
    Task<IReadOnlyList<T>> ListAsync(ISpecification<T> spec);
    Task<T> AddAsync(T entity);
    Task UpdateAsync(T entity);
    Task DeleteAsync(T entity);
    Task<int> CountAsync(ISpecification<T> spec);
}
```

<p>And then make your specific repo service inherit the <code>IRepository<T></code>. For example, your <code>IGateRepository</code> can be refactored as:</p>

```public class Gate: BaseEntity, IAggregateRoot
{
    // Add Gate props here
}

public interface IGateService : IAsyncRepository<Gate>
{
    // add more interface methods if you want
}
```

<p>By this way, you can invoke the service with generic types inference:</p>

```await gateSvc.AddAsync(gate);
await fundedSvc.AddAsync(funded);
...
```

Body:
I'm writing up the Data layer of server-side blazor SPA (one project only) and I'm following a sample where the teacher plays with a single domain object: an Employee. So he has a class EmployeeService to be injected and this class implements IEmployeeService. In my case, I have a few more such classes:

public interface IDesignManagerService
{
    Task<List<DesignManager>> GetDesignManagers();
    Task<bool> CreateDesignManager(DesignManager newStage);
    Task<bool> EditDesignManager(byte id, DesignManager modifiedDesignManager);
    Task<DesignManager> SingleDesignManager(byte id);
    Task<bool> DeleteEmployee(byte id);
}

public interface IFundedService
{
    Task<List<Funded>> GetFunded();
    Task<bool> CreateFunded(Funded newStage);
    Task<bool> EditFunded(byte id, Funded modifiedFunded);
    Task<Funded> SingleFunded(byte id);
    Task<bool> DeleteEmployee(byte id);
}

public interface IGateService
{
    Task<List<Gate>> GetGates();
    Task<bool> CreateGate(Gate newStage);
    Task<bool> EditGate(byte id, Gate modifiedGate);
    Task<Gate> SingleGate(byte id);
    Task<bool> DeleteEmployee(byte id);
}

Immediately, I feel like there should be a common interface having the basic methods so I can somehow use the dynamic type like Create<Employee> or Create<Gate>. Can this be accomplished here? I know what I might want but am unable to dig for help due to a lack of familiarity with the pattern.

Body:
Microsoft has already provide a sample for this pattern. See official docs and the source code on GitHub.

To answer your question it self, you need a generic IAsyncRepository as the common interface:

// an empty marker interface
public interface IAggregateRoot{ }

// a common entity that has an `Id` property
public abstract class BaseEntity
{
    public virtual int Id { get; protected set; }
}

// the common Repo interface
public interface IAsyncRepository<T> where T : BaseEntity, IAggregateRoot
{
    Task<T> GetByIdAsync(int id);
    Task<IReadOnlyList<T>> ListAllAsync();
    Task<IReadOnlyList<T>> ListAsync(ISpecification<T> spec);
    Task<T> AddAsync(T entity);
    Task UpdateAsync(T entity);
    Task DeleteAsync(T entity);
    Task<int> CountAsync(ISpecification<T> spec);
}

And then make your specific repo service inherit the IRepository<T>. For example, your IGateRepository can be refactored as:

public class Gate: BaseEntity, IAggregateRoot
{
    // Add Gate props here
}

public interface IGateService : IAsyncRepository<Gate>
{
    // add more interface methods if you want
}

By this way, you can invoke the service with generic types inference:

await gateSvc.AddAsync(gate);
await fundedSvc.AddAsync(funded);
...


问:
Python staticmethod decorator with inheritance
My case:

```<code>class BaseClass:

    @staticmethod
    def dummy_decorator(fnc):
        def wrapper():
            print('Im so dummy')
        return wrapper

class InheritedClass(BaseClass):
    def __init__(self):
        pass

    def anymethod(self):
        print('hello world')
</code>```

When I look at dir(), I see my staticmethod

```<code>>>> c = InheritedClass()
>>> dir(c)
['__doc__', '__init__', '__module__', 'anymethod', 'dummy_decorator']
</code>```

Also, I can use my dummy operator as simple staticmethod inside new class.
But when I try to use it as decorator -- I get error

```<code>class InheritedClass(BaseClass):
    def __init__(self):
        pass

    @dummy_decorator
    def anymethod(self):
        print('hello world')

>>> NameError: name 'dummy_decorator' is not defined
</code>```

Why it works so?
I know, that if I change @dummy_decorator to @BaseClass.dummy_decorator -- everything will work, but why I can't use decorator without ref to parent class?

答:
The reason why is baecause it is a static method, it belongs to the class as you have figured out when you put @BaseClass.dummy_decorator and it worked.

It is an attribute of the class so you can't just refer to it by dummy_decorator unless you move it out of the class or save it into the global namespace

Body:
My case:

class BaseClass:

    @staticmethod
    def dummy_decorator(fnc):
        def wrapper():
            print('Im so dummy')
        return wrapper

class InheritedClass(BaseClass):
    def __init__(self):
        pass

    def anymethod(self):
        print('hello world')

When I look at dir(), I see my staticmethod

>>> c = InheritedClass()
>>> dir(c)
['__doc__', '__init__', '__module__', 'anymethod', 'dummy_decorator']

Also, I can use my dummy operator as simple staticmethod inside new class.
But when I try to use it as decorator -- I get error

class InheritedClass(BaseClass):
    def __init__(self):
        pass

    @dummy_decorator
    def anymethod(self):
        print('hello world')

>>> NameError: name 'dummy_decorator' is not defined

Why it works so?
I know, that if I change @dummy_decorator to @BaseClass.dummy_decorator -- everything will work, but why I can't use decorator without ref to parent class?


问:
How to set an initial value to daterangepicker?
I have a DateRangePicker as follows:

HTTP:

```<code><input id="date" name="date" ng-model="FilesDate" class="form-control"/>
</code>```

JQuery:

```<code>$('input[name="date"]').daterangepicker({
        opens: 'left'
 });
</code>```

The DateRangePicker works totally fine but when the program initializes, its empty by default. If I remove ng-model, the date initializes properly.

Body:
I have a DateRangePicker as follows:

HTTP:

<input id="date" name="date" ng-model="FilesDate" class="form-control"/>

JQuery:

$('input[name="date"]').daterangepicker({
        opens: 'left'
 });

The DateRangePicker works totally fine but when the program initializes, its empty by default. If I remove ng-model, the date initializes properly.

Body: $('input[name="date"]').attr('value', '01/01/2018 - 01/15/2018');


问:
Jenkins does not show configured git credentials
I have Jenkins 2.204.2 and want to configure a project with my git credentials for our gitlab server.

I created under Jenkins > Credentials > System > Global credentials an entry with a secret key.

Nevertheless, if I create a freestyle project and set git as source code management, the opttions for Credentials remain empty.

Also if I use the Add button next to the credentials options and add the same secret key again, this does not show up in the options (though the new entry is shown in the Global credentials menu).

How can I configure the credentials to be used for Jenkins ? What do I miss, that I cannot select my created credentials ?

答:
To use the git protocol (and not the https protocol) your Jenkins credentials must be of type "SSH Username with private key".

Even so, those credentials won't appear in the dropdown list due to this known issue: likely you have installed the "Authorize Project" Plugin and in the "Configure Global Security" > "Project Default Build Authorization" section, "Strategy" field configured to "Run as specified user" (and a user) or "Run as anonymous". As a workaround for the issue, you can select "Run as SYSTEM" and the SSH credentials will appear in the list.

See:

Why credentials are not listed in the GIT SCM section?
https://support.cloudbees.com/hc/en-us/articles/360017499672-Why-credentials-are-not-listed-in-the-GIT-SCM-section-


问:
How can i get data from model file?
I have this model files which I use to get data of Vimeo videos using Retrofit and Gson.

It's all working fine, I get title, description and other things with no problem but I can't get the thumbnail.

This is my adapter

```<code>class YoutubeHolder extends RecyclerView.ViewHolder {

        ImageView thumbnail;
        TextView title, description, publishedAt;

        YoutubeHolder(@NonNull View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.ImageThumb);
            title = itemView.findViewById(R.id.textViewTitle);
            description = itemView.findViewById(R.id.textViewDes);
            publishedAt = itemView.findViewById(R.id.textViewDate);
        }

        public void setData(VimeoVideo data) {
            String getTitle = data.getName();
            String getDescription = data.getDescription();
            String getPublishedAt = data.getCreated_time();

            // I want get it like this
            String getThumbnail = data.getPictures().getSizes().getLink;

            title.setText(getTitle);
            description.setText(getDescription);
            publishedAt.setText(getPublishedAt);

        }

    }
</code>```

And this is my models

```<code>public class VimeoPictures {
    @SerializedName("sizes")
    @Expose
    private List<VimeoSizes> sizes;

    public VimeoPictures() {
    }

    public VimeoPictures(List<VimeoSizes> sizes) {
        this.sizes = sizes;
    }

    public List<VimeoSizes> getSizes() {
        return sizes;
    }

    public void setSizes(List<VimeoSizes> sizes) {
        this.sizes = sizes;
    }
}
</code>```

And one for sizes

```<code>@SerializedName("width")
    @Expose
    private String width;

    @SerializedName("height")
    @Expose
    private String height;

    @SerializedName("link")
    @Expose
    private String link;

    ... Getters and Setters,  etc...
</code>```

I searched for an answer but no success :(

答:
I think the problem is in this line :

```<code>String getThumbnail = data.getPictures().getSizes().getLink;
</code>```

when you call getSizes(), it return list of object. You cannot call getLink from a list. You need to get a certain element from the list.

As an example if you want to get the link of the first element in the list, you can do this :

```<code>String getThumbnail = data.getPictures().getSizes().get(0).getLink;
</code>```

Title: How can i get data from model file?

Body:
I have this model files which I use to get data of Vimeo videos using Retrofit and Gson.

It's all working fine, I get title, description and other things with no problem but I can't get the thumbnail.

This is my adapter

class YoutubeHolder extends RecyclerView.ViewHolder {

        ImageView thumbnail;
        TextView title, description, publishedAt;

        YoutubeHolder(@NonNull View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.ImageThumb);
            title = itemView.findViewById(R.id.textViewTitle);
            description = itemView.findViewById(R.id.textViewDes);
            publishedAt = itemView.findViewById(R.id.textViewDate);
        }

        public void setData(VimeoVideo data) {
            String getTitle = data.getName();
            String getDescription = data.getDescription();
            String getPublishedAt = data.getCreated_time();

            // I want get it like this
            String getThumbnail = data.getPictures().getSizes().getLink;

            title.setText(getTitle);
            description.setText(getDescription);
            publishedAt.setText(getPublishedAt);

        }

    }

And this is my models

public class VimeoPictures {
    @SerializedName("sizes")
    @Expose
    private List<VimeoSizes> sizes;

    public VimeoPictures() {
    }

    public VimeoPictures(List<VimeoSizes> sizes) {
        this.sizes = sizes;
    }

    public List<VimeoSizes> getSizes() {
        return sizes;
    }

    public void setSizes(List<VimeoSizes> sizes) {
        this.sizes = sizes;
    }
}

And one for sizes

@SerializedName("width")
    @Expose
    private String width;

    @SerializedName("height")
    @Expose
    private String height;

    @SerializedName("link")
    @Expose
    private String link;

    ... Getters and Setters,  etc...

I searched for an answer but no success :(

Body:
I think the problem is in this line :

String getThumbnail = data.getPictures().getSizes().getLink;

when you call getSizes(), it return list of object. You cannot call getLink from a list. You need to get a certain element from the list.

As an example if you want to get the link of the first element in the list, you can do this :

String getThumbnail = data.getPictures().getSizes().get(0).getLink;


问:
AVPlayerItemStatusUnknown showing up when doing Live HTTP streaming
I am using AVPlayer to view videos stored on Amazon's CloudFront -- Live HTTP protocol is used and the playlist and segments are stored on S3 and hosted using CloudFront.

After playing a few videos I start getting a status of AVPlayerItemStatusUnknown from the AVPlayer item

```<code>AVPlayer.currentItem.status == AVPlayerItemStatusUnknown
</code>```

This status persists when a new video playlist is selected -- I've tried de-allocating the AVPlayer before setting a new playlist URL and still the AVPlayerItemStatusUnknown status remains until I terminate the application.

Two questions.  Is anybody using Amazaon CloudFront to host video experiencing the same issue?  Does anybody know a work around so i can recover the state of the AVPlayer to prevent the user from having to terminate the app to view any more videos?

Many Thanks,

//aaron

答:
For streaming media this looks like a normal behavior to me. Do you add an observer for the 'status' property? You should start playback when status changes to    AVPlayerItemStatusReadyToPlay.</p>

```<code>[item addObserver:self forKeyPath:@"status" options:0 context:nil];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem *)object;
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            //Ready
        }
    }
}
</code>```

Body:
I am using AVPlayer to view videos stored on Amazon's CloudFront -- Live HTTP protocol is used and the playlist and segments are stored on S3 and hosted using CloudFront.

After playing a few videos I start getting a status of AVPlayerItemStatusUnknown from the AVPlayer item

AVPlayer.currentItem.status == AVPlayerItemStatusUnknown

This status persists when a new video playlist is selected -- I've tried de-allocating the AVPlayer before setting a new playlist URL and still the AVPlayerItemStatusUnknown status remains until I terminate the application.

Two questions.  Is anybody using Amazaon CloudFront to host video experiencing the same issue?  Does anybody know a work around so i can recover the state of the AVPlayer to prevent the user from having to terminate the app to view any more videos?

Many Thanks,

//aaron

Body:
For streaming media this looks like a normal behavior to me. Do you add an observer for the 'status' property? You should start playback when status changes to    AVPlayerItemStatusReadyToPlay.

[item addObserver:self forKeyPath:@"status" options:0 context:nil];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem *)object;
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            //Ready
        }
    }
}


问:
How to get previous/next row when ordering by date/time then ID in MySQL?
I have table like

```<code>SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...
</code>```

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

答:
Try this query:

```<code>SELECT MAX(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=8) b
ON     a.id <> b.id AND a.date < b.date
UNION ALL
SELECT MIN(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=8) b
ON     a.id > b.id AND a.date >= b.date;
</code>```

Fiddle here : https://www.db-fiddle.com/f/gTv6Hyeq9opHW83r6Cxfck/4

Or you can use a variable to single define the value:

```<code>SET @val = 8;
SELECT MAX(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=@val) b
ON     a.id <> b.id AND a.date < b.date
UNION ALL
SELECT MIN(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=@val) b
ON     a.id > b.id AND a.date >= b.date;
</code>```

Body:
I have table like

SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

Body:
Try this query:

SELECT MAX(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=8) b
ON     a.id <> b.id AND a.date < b.date
UNION ALL
SELECT MIN(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=8) b
ON     a.id > b.id AND a.date >= b.date;

Fiddle here : https://www.db-fiddle.com/f/gTv6Hyeq9opHW83r6Cxfck/4

Or you can use a variable to single define the value:

SET @val = 8;
SELECT MAX(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=@val) b
ON     a.id <> b.id AND a.date < b.date
UNION ALL
SELECT MIN(a.id) AS id
FROM   mytable a
JOIN  (SELECT id,NAME,DATE FROM mytable WHERE id=@val) b
ON     a.id > b.id AND a.date >= b.date;


问:
Which task scheduler is used by default when starting/running/invoking tasks in .NET?
Which task scheduler is used when I start tasks from a task that was run with a specific scheduler?

```<code>Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, new MyTaskScheduler());

// ...

void A()
{
    // 1
    Parallel.Invoke(sometasks);

    // 2
    Task.Run(sometask);

    // 3
    Parallel.For(/*...*/);

    // 4
    // Any other task execution that isn't specifying a scheduler explicitly
}
</code>```

Do all example will be scheduled by MyTaskScheduler? I want to use the QueuedTaskScheduler (From ParallelExtensionsExtras) to handle priorities and concurrency limitations for complex web api requests (which may start tasks and/or use other TPL functionality).

答:
When it comes to most TPL methods, the rule-of-thumb is the default task scheduler is used regardless of which task scheduler is associated with the current thread unless you have explicitly told it otherwise.

You will find most methods will either take options which will have a task scheduler property or you can supply one in the method itself as on overload

Body:
Which task scheduler is used when I start tasks from a task that was run with a specific scheduler?

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, new MyTaskScheduler());

// ...

void A()
{
    // 1
    Parallel.Invoke(sometasks);

    // 2
    Task.Run(sometask);

    // 3
    Parallel.For(/*...*/);

    // 4
    // Any other task execution that isn't specifying a scheduler explicitly
}

Do all example will be scheduled by MyTaskScheduler? I want to use the QueuedTaskScheduler (From ParallelExtensionsExtras) to handle priorities and concurrency limitations for complex web api requests (which may start tasks and/or use other TPL functionality).


问:
Trying to login to ECR fails with -no-include-email error
I am using this command to login to docker on my EC2

$(aws ecr get-login --registry-ids xxxxxxx --region us-west-1 --no-include-email)

when I do that, I get following error:

Unknown options: --no-include-email

what am I missing?

答:
You can try the below steps. It worked for me.

aws ecr get-login

The resulting output is a docker login command that you can use to authenticate your Docker client to your ECR registry.

Sample output: docker login -u AWS -p [your-password] -e none https:// [your-aws_account_id].dkr.ecr.[your-region].amazonaws.com

Then remove "-e none" from the above output and Run the remaining command.

You will get be able to login successfully.


问:
python del vs pandas drop
I know it might be old debate, but out of pandas.drop and python del function which is better in terms of performance over large dataset?

I am learning machine learning using python 3 and not sure which one to use. My data is in pandas data frame format. But python del function is in built-in function for python.

答:
Summarizing a few points about functionality:

drop operates on both columns and rows; del operates on column only.

drop can operate on multiple items at a time; del operates only on one at a time.

drop can operate in-place or return a copy; del is an in-place operation only.

The documentation at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html has more details on drop's features.

Title: python del vs pandas drop


问:
How to get environment variables based on build environment dynamically in external extconfig.js file in angular
I have configuration in angular.json file pointing towards different "urls" for different build

angular.json

```<code>configuration:{
   'dev':{
      "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
    },
   qa:{

  }
}
</code>```

environment.dev.ts

```<code>export const environment = {
 appServer: "https://....."
}
</code>```

environment.prod.ts

```<code>export const environment = {
 appServer: "https://....."
}
</code>```

I want to create a extconfig.js file(external js) keeping in assets and putting it in angular.json file

config.js

```<code>var baseUrl = '' ; <==========// environment.appServer based on build condition
</code>```

It should serve the purpose of handling "appServer" of environment variables based on build environment when run through either "ng serve --configuration=dev or ng build --configuration=prod.

This is required beacuse "extconfig.js" file will hold global variables containing configuration variables serving for other external js which may require baseUrl for ajax call

答:
If i am understanding correctly, you can create a config.prod.ts and a config.ts under the same folder, each one holds a version of your appServer url. then you can import your config from the folder in your services.

import { extConfig } from './config-specifics';

var baseUrl = extConfig.appServerUrl

and in your angular.json.

```<code>"fileReplacements": [
        {
          "replace": "apps/app-name/src/app/config-specifics/config.ts",
          "with": "apps/app-name/src/app/config-specifics/config.prod.ts"
        }
      ]
</code>```

Body:
I have configuration in angular.json file pointing towards different "urls" for different build

angular.json

configuration:{
   'dev':{
      "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
    },
   qa:{

  }
}

environment.dev.ts

export const environment = {
 appServer: "https://....."
}

environment.prod.ts

export const environment = {
 appServer: "https://....."
}

I want to create a extconfig.js file(external js) keeping in assets and putting it in angular.json file

config.js

var baseUrl = '' ; <==========// environment.appServer based on build condition

It should serve the purpose of handling "appServer" of environment variables based on build environment when run through either "ng serve --configuration=dev or ng build --configuration=prod.

This is required beacuse "extconfig.js" file will hold global variables containing configuration variables serving for other external js which may require baseUrl for ajax call

Body:
If i am understanding correctly, you can create a config.prod.ts and a config.ts under the same folder, each one holds a version of your appServer url. then you can import your config from the folder in your services.

import { extConfig } from './config-specifics';

var baseUrl = extConfig.appServerUrl

and in your angular.json.

"fileReplacements": [
        {
          "replace": "apps/app-name/src/app/config-specifics/config.ts",
          "with": "apps/app-name/src/app/config-specifics/config.prod.ts"
        }
      ]


问:
What unix command can we use to append some text to a specific line in a file?
Does anyone know of a series of unix commands that allows someone to append some text to the end of a specific line in a file?

eg

Line 1

Line 2

Line 3

Line 4

I wish to append the text ", extra information" to Line 3 so that the File will now look like this:

Line 1

Line 2

Line 3, extra information

Line 4

答:
```<code>awk 'NR == 3 { print $0 ", extra information" } NR != 3' myfile
</code>```

The part before the braces is the condition: If we are in line 3, we append some text. If braces are omitted, the default action is to just print out $0. Redirect to a new file or pipe to another program as appropriate. You cannot redirect to the same file you are just reading. A common workaround is to redirect to a new file, and then move over if the command was successful:

```<code>somecommand > oldfile.tmp && mv oldfile.tmp oldfile
</code>```

OwnerDisplayName: Alex Wong

ContentLicense: CC BY-SA 2.5

Body:
awk 'NR == 3 { print $0 ", extra information" } NR != 3' myfile

The part before the braces is the condition: If we are in line 3, we append some text. If braces are omitted, the default action is to just print out $0. Redirect to a new file or pipe to another program as appropriate. You cannot redirect to the same file you are just reading. A common workaround is to redirect to a new file, and then move over if the command was successful:

somecommand > oldfile.tmp && mv oldfile.tmp oldfile

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
Using Artifactory plugin for Jenkins, is there a way to search repos for images with a property?
I'm using the Artifactory plugin in Jenkins. I have a situation where I need to pull docker images from Artifactory which have a particular property set. I can search for them using the REST API, but I have not found a way to do this using the Jenkins plugin. Anybody know if there is a way?

Thanks.

答:
This is the download spec schema from the documentation:

```<code>{
  "files": [
     {
       "pattern" or "aql": "[Mandatory]",
       "target": "[Mandatory]",
       "props": "[Optional]",
       "recursive": "[Optional, Default: true]",
       "flat" : "[Optional, Default: false]"
     }
   ]
 }
</code>```

Where from my point of view you have a couple of options to search by propeties; one would be using aql where you have such option. Second one would be directly using props, which main purpose seems to be exactly that:

props: List of "key=value" pairs separated by a semi-colon. (For
  example, "key1=value1;key2=value2;key3=value3). Only artifacts with
  all of the specified properties and values will be downloaded.

Body:
This is the download spec schema from the documentation:

{
  "files": [
     {
       "pattern" or "aql": "[Mandatory]",
       "target": "[Mandatory]",
       "props": "[Optional]",
       "recursive": "[Optional, Default: true]",
       "flat" : "[Optional, Default: false]"
     }
   ]
 }

Where from my point of view you have a couple of options to search by propeties; one would be using aql where you have such option. Second one would be directly using props, which main purpose seems to be exactly that:

props: List of "key=value" pairs separated by a semi-colon. (For
  example, "key1=value1;key2=value2;key3=value3). Only artifacts with
  all of the specified properties and values will be downloaded.


问:
0 in integer part of a decimal variable is not displaying
Below is the code to display a decimal(18,2) value from database:

```<code>document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + response + " US$/kg";
</code>```

So it displayed as:

```<code>Total Knitting Cost : .55 US$/kg
</code>```

How to make it display 0.55 US$/kg?

Update - response is from Ajax:

```<code>function fetch_select(val, obj)
{
    $.ajax({
            type:'post',
            url: 'get.php',
            data: {
                    get_option:val, "get_object":obj.id
                  },
            success: function (response)
                {
                    switch (obj.id) {
                        case "Yarn":
                            //code to process yarndivid here
                            document.getElementById(yarndivid).innerHTML=response;

                            break;

                        case "Knitting":
                            document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + parseFloat(response) + " US$/kg";
                        break;

                        case "Dyestuff":
                        break;

                    }
                }

        });
}
</code>```

get.php:

```<code><?php
 if(isset($_POST['get_option']) or isset($_POST['get_object']))
{

 $connectionInfo = array("Database"=>$db, "UID"=>$user, "PWD"=>$pass);
 $dbhandle = sqlsrv_connect($server,$connectionInfo) or die("Couldn’t connect to SQL Server on $server");
 if( $dbhandle === false )
    {
    die( print_r( sqlsrv_errors(), true));
    }

 $id = $_POST['get_option'];
 $objid = $_POST['get_object'];
 $tblname = $sql = "";

 switch ($objid) {
    case "Yarn":
        $tblname = "tblYarnFilament";
        break;
    case "Knitting":
        $tblname = "tblKnitting";
        break;
    case "Coloration":
        $tblname = "tblDyestuff";
        break;
    }

 $sql = "select price2 from ".$tblname." where id = '$id'";

 $find=sqlsrv_query($dbhandle, $sql);

    while($row=sqlsrv_fetch_array($find))
    {
        echo $row['price2'];
    }
}
?>

</code>```

答:
I just found out, response is actually returning this whole section:

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>

.55
</code>```

This <!DOCTYPE html> part is actually placed on top of get.php document. I thought it doesn't matter!

So I removed that part and parseFloat(response) works perfectly. Thank you everyone for helping.

Lesson learnt, check your variable properly!

Body:
Below is the code to display a decimal(18,2) value from database:

document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + response + " US$/kg";

So it displayed as:

Total Knitting Cost : .55 US$/kg

How to make it display 0.55 US$/kg?

Update - response is from Ajax:

function fetch_select(val, obj)
{
    $.ajax({
            type:'post',
            url: 'get.php',
            data: {
                    get_option:val, "get_object":obj.id
                  },
            success: function (response)
                {
                    switch (obj.id) {
                        case "Yarn":
                            //code to process yarndivid here
                            document.getElementById(yarndivid).innerHTML=response;

                            break;

                        case "Knitting":
                            document.getElementById("knittingcost").innerHTML = "Total Knitting Cost : " + parseFloat(response) + " US$/kg";
                        break;

                        case "Dyestuff":
                        break;

                    }
                }

        });
}

get.php:

<?php
 if(isset($_POST['get_option']) or isset($_POST['get_object']))
{

 $connectionInfo = array("Database"=>$db, "UID"=>$user, "PWD"=>$pass);
 $dbhandle = sqlsrv_connect($server,$connectionInfo) or die("Couldn’t connect to SQL Server on $server");
 if( $dbhandle === false )
    {
    die( print_r( sqlsrv_errors(), true));
    }

 $id = $_POST['get_option'];
 $objid = $_POST['get_object'];
 $tblname = $sql = "";

 switch ($objid) {
    case "Yarn":
        $tblname = "tblYarnFilament";
        break;
    case "Knitting":
        $tblname = "tblKnitting";
        break;
    case "Coloration":
        $tblname = "tblDyestuff";
        break;
    }

 $sql = "select price2 from ".$tblname." where id = '$id'";

 $find=sqlsrv_query($dbhandle, $sql);

    while($row=sqlsrv_fetch_array($find))
    {
        echo $row['price2'];
    }
}
?>

Body:
I just found out, response is actually returning this whole section:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

.55

This <!DOCTYPE html> part is actually placed on top of get.php document. I thought it doesn't matter!

So I removed that part and parseFloat(response) works perfectly. Thank you everyone for helping.

Lesson learnt, check your variable properly!


问:
close microsoft edge tab from powershell script
I am using below powershell script to open a webpage using microsoft edge.
start microsoft-edge:https://stackoverflow.com

I need to close the same using powershell. I have a piece of code that will work for IE but need the similar for edge.

```<code>$url = 'https://stackoverflow.com'

Function Close-IETab {
param($url)

    $oWindows = (New-Object -ComObject Shell.Application).Windows

    foreach ($oWindow in $oWindows.Invoke()) {

        if ($oWindow.Fullname -match "IEXPLORE.EXE" -and $oWindow.LocationURL -eq $url) {

            Write-verbose "Closing tab $($oWindow.LocationURL)"
            $oWindow.Quit()
        }
    }

}

try
{
Close-IETab($url )
}
</code>```

答:
MS Edge browser cannot be automated like the IE browser. It does not support this kind of automation.

I suggest you try to use a selenium web driver to automate the MS Edge browser.

It is the best suitable approach to automate the Edge browser.

Microsoft web driver

Reference:

Will Microsoft Edge support COM automation (InternetExplorer object)?

Body:
I am using below powershell script to open a webpage using microsoft edge.
start microsoft-edge:https://stackoverflow.com

I need to close the same using powershell. I have a piece of code that will work for IE but need the similar for edge.

$url = 'https://stackoverflow.com'

Function Close-IETab {
param($url)

    $oWindows = (New-Object -ComObject Shell.Application).Windows

    foreach ($oWindow in $oWindows.Invoke()) {

        if ($oWindow.Fullname -match "IEXPLORE.EXE" -and $oWindow.LocationURL -eq $url) {

            Write-verbose "Closing tab $($oWindow.LocationURL)"
            $oWindow.Quit()
        }
    }

}

try
{
Close-IETab($url )
}


问:
Kotlin Handler class: How to stop a thread - from inside of run() - when a condition is met?
I am currently learning how to develop android applications. For my first app, I wanted to build a simple clicker with a primitive combat sistem.

In my code, I have created a Handler instance and a Runnable object. Inside of this "delayed loop" the enemy attacks the player instance every 3 seconds, dealing damage. Inside the loop I also test when the player's hp is less or equals 0; when the condition is met I want to stop the runnable object.

How do i do this? I tried calling a function stopCombat() which contains Handler.removeCallbacks, but i can't call a function before declaration. I tried putting .removeCallbacks(this) inside run(), but it also doesn't work.

```<code>val mainHandler = Handler(Looper.getMainLooper())

    fun playerDied() {
        ongoingFight = false
        combatLog.append("${myPlayer.name} has been defeated!\n")
        myPlayer.currentHitPoints = myPlayer.maxHitPoints / 2
        myPlayer.gold = 0
        gold.text = "${myPlayer.gold} gold"
    }

    val performTask = object : Runnable {
        override fun run() {
            val enemyHit = enemyAttack(myPlayer, myEnemy)
            // Call a function to stop this thread if the condition is met:
            if (myPlayer.takeDamage(enemyHit)) { //myPlayer.takeDamage returns true if hp <= 0
                playerDied()
                stopCombat() // called before declaration
                mainHandler.removeCallbacks(this) // tried, doesn't work
            }
            playerHP.text = "${myPlayer.currentHitPoints} / ${myPlayer.maxHitPoints}"
            combatLog.append("${myEnemy.name} deals $enemyHit damage!\n")
            mainHandler.postDelayed(this, 3000)
        }
    }

    fun stopCombat(){
        mainHandler.removeCallbacks(performTask)
    }
</code>```

答:
I notice that you are using kotlin. I think you can use coroutines. It's more concise and lightweight. Cancellation and Timeouts

If you still want to use thread. Try the following code.

```<code>    val executorService = Executors.newSingleThreadExecutor()
    val runnables = Runnable {

    }
    val task = executorService.submit(runnables)
    task.cancel(true)
</code>```

Body:
I am currently learning how to develop android applications. For my first app, I wanted to build a simple clicker with a primitive combat sistem.

In my code, I have created a Handler instance and a Runnable object. Inside of this "delayed loop" the enemy attacks the player instance every 3 seconds, dealing damage. Inside the loop I also test when the player's hp is less or equals 0; when the condition is met I want to stop the runnable object.

How do i do this? I tried calling a function stopCombat() which contains Handler.removeCallbacks, but i can't call a function before declaration. I tried putting .removeCallbacks(this) inside run(), but it also doesn't work.

val mainHandler = Handler(Looper.getMainLooper())

    fun playerDied() {
        ongoingFight = false
        combatLog.append("${myPlayer.name} has been defeated!\n")
        myPlayer.currentHitPoints = myPlayer.maxHitPoints / 2
        myPlayer.gold = 0
        gold.text = "${myPlayer.gold} gold"
    }

    val performTask = object : Runnable {
        override fun run() {
            val enemyHit = enemyAttack(myPlayer, myEnemy)
            // Call a function to stop this thread if the condition is met:
            if (myPlayer.takeDamage(enemyHit)) { //myPlayer.takeDamage returns true if hp <= 0
                playerDied()
                stopCombat() // called before declaration
                mainHandler.removeCallbacks(this) // tried, doesn't work
            }
            playerHP.text = "${myPlayer.currentHitPoints} / ${myPlayer.maxHitPoints}"
            combatLog.append("${myEnemy.name} deals $enemyHit damage!\n")
            mainHandler.postDelayed(this, 3000)
        }
    }

    fun stopCombat(){
        mainHandler.removeCallbacks(performTask)
    }

Body:
I notice that you are using kotlin. I think you can use coroutines. It's more concise and lightweight. Cancellation and Timeouts

If you still want to use thread. Try the following code.

    val executorService = Executors.newSingleThreadExecutor()
    val runnables = Runnable {

    }
    val task = executorService.submit(runnables)
    task.cancel(true)


问:
Deleting a row from MySQL after 24 hours in JEE?
I am trying to delete a row in my table. Here is my sample code

```<code>String DBDate = new String();
Long date = new Date().getTime();
String dateToday = date.toString();
dbobj.clear();
dbobj.put(LAST_TIME_ANSWERED, "");
int hasDB = dbobj.getFromDB(tableName,column key, primary key);

if(hasDB != 0) {
    DBDate = dbobj.get(LAST_TIME_ANSWERED);
    if(DBDate != dateToday) {
        dbobj.deleteClientDB(tableName, column key, primary key);
    }
}
</code>```

How could I change the date of a timer?
Any help would be nice. Thanks in advance!

答:
This is awkward to achieve in java, because you need to run a job on a schedule to achieve this. You should strongly consider using the mysql event scheduler. See this answer for an example of this.

When you insert the row in the db you should set up an event that is triggered exactly once, 24-hours later, with the necessary sql to delete the row. You would end up with one event per row.

Alternatively, with java and a properly configured server, after each row insert you could add a cron or quartz job that would trigger once, 24-hours later, that would invoke a java function to remove the row. This is harder than using the db's built-in event scheduler.

Depending on your JEE version (>6) you could use an EJB 3.1 timer, as detailed in this blog post.

Of these options, the db event scheduler is probably the best, because the others can go wrong if the JEE sever is down.

Body:
I am trying to delete a row in my table. Here is my sample code

String DBDate = new String();
Long date = new Date().getTime();
String dateToday = date.toString();
dbobj.clear();
dbobj.put(LAST_TIME_ANSWERED, "");
int hasDB = dbobj.getFromDB(tableName,column key, primary key);

if(hasDB != 0) {
    DBDate = dbobj.get(LAST_TIME_ANSWERED);
    if(DBDate != dateToday) {
        dbobj.deleteClientDB(tableName, column key, primary key);
    }
}

How could I change the date of a timer?
Any help would be nice. Thanks in advance!


问:
Jhipster Azure Cosmos DB SQL API
Does Jhipster support Azures Cosmos DB SQL API? In the below site, it was mentioned that Jhipster  is compatible with Cosmos DB - cassandra and Mongo DB API, but nothing mentioned about SQL API

https://www.jhipster.tech/azure/#nosql-databases

Did any one successfully implemented Jhipster with Cosmos DB SQL API?

答:
If jHipster supports Cassandra and MongoDB (as the documentation states), then you would need to use Cosmos DB with those APIs. The SQL API is a different API layer for interacting with Cosmos DB, and if the jHipster documentation doesn't state is supports SQL API, then it doesn't.

CosmosDB is a globally distributed, managed database from Microsoft. It is compatible at the API level with Cassandra and MongoDB, so it can be used with a JHipster application that is generated using those technologies.

Title: Jhipster Azure Cosmos DB SQL API