问:
How to get the IP address of Docker container using Docker SDK for Python?
I am launching a container with network_mode = bridge, when I inspect the network container in the terminal I get the container IP address.

```<code>docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id
</code>```

However, I can't get this IP address from the container object.
Is there any solution without searching the container in the network object?

答:
If the IP doesn't return from container.attrs['NetworkSettings']['IPAddress'] as suggested here, try the following:

```<code>network_name = "my_net"
container.attrs["NetworkSettings"]["Networks"][network_name]["IPAddress"]
</code>```

For me, this was the case when the containers were created with docker-compose, with an external network.

Body:
I am launching a container with network_mode = bridge, when I inspect the network container in the terminal I get the container IP address.

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id

However, I can't get this IP address from the container object.
Is there any solution without searching the container in the network object?

Body:
If the IP doesn't return from container.attrs['NetworkSettings']['IPAddress'] as suggested here, try the following:

network_name = "my_net"
container.attrs["NetworkSettings"]["Networks"][network_name]["IPAddress"]

For me, this was the case when the containers were created with docker-compose, with an external network.


来源: stackexchange

问:
How long does it take after app has released for Dynamic Link to open in App Store?
It’s been a few days since my app has released in the App Store. I have updated the App ID in the project settings.

But when clicking on the the Dynamic Link, the app preview does not work.

It still shows an empty App Preview with an Open button that doesn't actually show the app in the App Store.

答:
Looks like the issue was caused because I changed Bundle ID in the middle of development and this creates different certifications in GCP.

More information here: iOS app lacks App ID Prefix. UniversalLinks is not enabled for the app. Where to enter the App ID?

ContentLicense: CC BY-SA 4.0


问:
How to read a text file with string into a ´n undirected graph with adjacency list
Newbie here! I want to implement a class Graph that can represent an un-weighted and undirected graph using Adjacency Lists. The basic functionality should include adding and removing vertices and edges, as well as printing the graph to command line.
My main problem is that I'm having a hard time to read the file into the graph. What I am doing wrong?

My text file look like this:

```<code>Anna    Noah
Anna    Marie
Marie   Noah
Marie   Jakob
Marie   Hanna
Jakob   Felix
Hanna   Felix
Hanna   Jonas
Felix   Jonas
Felix   Emma
Felix   Finn
Felix   Ben
</code>```

(each line represents two nodes connected by an edge).

My code is:

```<code>public class UndirectedGraphs {
HashMap<String, LinkedList<String>> socialNetworkAdj;

public UndirectedGraphs() {
    socialNetworkAdj = new HashMap<String, LinkedList<String>>();

}
public void addVertex(String label){
    socialNetworkAdj.put(label, new LinkedList<String>());
}

public LinkedList<String> getEdges(String label) {
    return socialNetworkAdj.get(label);
}

public void addEdges(String ver1, String ver2) {
    if (!socialNetworkAdj.containsKey(ver1)) {
        addVertex(ver1);
    }

    if (!socialNetworkAdj.containsKey(ver2)) {
        addVertex(ver2);
    }
    socialNetworkAdj.get(ver1).add(ver2);
    socialNetworkAdj.get(ver2).add(ver1);
    System.out.println(socialNetworkAdj);

}

public static void main(String[] args) throws Exception {

    File filePath = new File("C:\\Users\\Fo\\Desktop\\A9\\network.txt");
    FileReader fr = new FileReader(filePath);
    BufferedReader br = new BufferedReader(fr);

    String[] tokens = new String[2];
    ArrayList<String> nodes = new ArrayList<>();
    UndirectedGraphs graph = new UndirectedGraphs();
    String line;
    String var1 = tokens[0];
    String var2 = tokens[1];

    while ((line = br.readLine()) != null) {
        graph.addEdges(var1, var2);
    }
    System.out.println("\nAnna: --> " + graph.getEdges("Anna"));
    br.close();

}
</code>```

}

The Output is:

```<code>{null=[null, null]}
{null=[null, null, null, null]}
{null=[null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null,
null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
</code>```

答:
As pointed out in the comments, at each iteration of the while loop you need to get the names of the read line, and add them while iterating.</p>
```<code>while((line = br.readLine()) != null) {
    String [] nodes = line.split("\\s+");
    if(nodes.length == 2)
        graph.addEdges(nodes[0], nodes[1]);
    // optional else with error handling
}
</code>```

Body:
Newbie here! I want to implement a class Graph that can represent an un-weighted and undirected graph using Adjacency Lists. The basic functionality should include adding and removing vertices and edges, as well as printing the graph to command line.
My main problem is that I'm having a hard time to read the file into the graph. What I am doing wrong?

My text file look like this:

Anna    Noah
Anna    Marie
Marie   Noah
Marie   Jakob
Marie   Hanna
Jakob   Felix
Hanna   Felix
Hanna   Jonas
Felix   Jonas
Felix   Emma
Felix   Finn
Felix   Ben

(each line represents two nodes connected by an edge).

My code is:

public class UndirectedGraphs {
HashMap<String, LinkedList<String>> socialNetworkAdj;

public UndirectedGraphs() {
    socialNetworkAdj = new HashMap<String, LinkedList<String>>();

}
public void addVertex(String label){
    socialNetworkAdj.put(label, new LinkedList<String>());
}

public LinkedList<String> getEdges(String label) {
    return socialNetworkAdj.get(label);
}

public void addEdges(String ver1, String ver2) {
    if (!socialNetworkAdj.containsKey(ver1)) {
        addVertex(ver1);
    }

    if (!socialNetworkAdj.containsKey(ver2)) {
        addVertex(ver2);
    }
    socialNetworkAdj.get(ver1).add(ver2);
    socialNetworkAdj.get(ver2).add(ver1);
    System.out.println(socialNetworkAdj);

}

public static void main(String[] args) throws Exception {

    File filePath = new File("C:\\Users\\Fo\\Desktop\\A9\\network.txt");
    FileReader fr = new FileReader(filePath);
    BufferedReader br = new BufferedReader(fr);

    String[] tokens = new String[2];
    ArrayList<String> nodes = new ArrayList<>();
    UndirectedGraphs graph = new UndirectedGraphs();
    String line;
    String var1 = tokens[0];
    String var2 = tokens[1];

    while ((line = br.readLine()) != null) {
        graph.addEdges(var1, var2);
    }
    System.out.println("\nAnna: --> " + graph.getEdges("Anna"));
    br.close();

}

}

The Output is:

{null=[null, null]}
{null=[null, null, null, null]}
{null=[null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null,
null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}
{null=[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]}

Body:
As pointed out in the comments, at each iteration of the while loop you need to get the names of the read line, and add them while iterating.

while((line = br.readLine()) != null) {
    String [] nodes = line.split("\\s+");
    if(nodes.length == 2)
        graph.addEdges(nodes[0], nodes[1]);
    // optional else with error handling
}


问:
Outputting text from an url that returns JSON
I'm more of a backend guy, this javascript stuff is a bit out of my area. I could really use a point in the right direction :)

So I have an URL that, for example, returns this JSON:

```<code>[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}},
 {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}},
 {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}},
 {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}},
 {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]
</code>```

I want to write a piece of javascript that I can embed in my HTML that will randomly choose and print one of the "fact"s from the JSON URL.

答:
Hopefully this helps:

```<code>var a = '[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}}, {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}}, {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}}, {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}}, {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]';
alert(eval(a)[0].model);
</code>```

Here's an example that uses AJAX to call out to a (local) web service:

```<code>$.ajax({
  url: "test.php",
  success: function(data){
    alert(eval(data).result);
  }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm more of a backend guy, this javascript stuff is a bit out of my area. I could really use a point in the right direction :)

So I have an URL that, for example, returns this JSON:

[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}},
 {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}},
 {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}},
 {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}},
 {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]

I want to write a piece of javascript that I can embed in my HTML that will randomly choose and print one of the "fact"s from the JSON URL.

Body:
Hopefully this helps:

var a = '[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}}, {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}}, {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}}, {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}}, {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]';
alert(eval(a)[0].model);

Here's an example that uses AJAX to call out to a (local) web service:

$.ajax({
  url: "test.php",
  success: function(data){
    alert(eval(data).result);
  }
});


问:
Cannot build Docker image for Angular 12
I an trying to build an Angular image but i'm getting this error:

```<code>#14 130.6 - Generating browser application bundles (phase: setup)...
#14 146.6 events.js:377
#14 146.6       throw er; // Unhandled 'error' event
#14 146.6       ^
#14 146.6
#14 146.6 Error: write EPIPE
#14 146.6     at afterWriteDispatched (internal/stream_base_commons.js:156:25)
#14 146.6     at writeGeneric (internal/stream_base_commons.js:147:3)
#14 146.6     at Socket._writeGeneric (net.js:787:11)
#14 146.6     at Socket._write (net.js:799:8)
#14 146.6     at writeOrBuffer (internal/streams/writable.js:358:12)
#14 146.6     at Socket.Writable.write (internal/streams/writable.js:303:10)
#14 146.6     at Object.writeToStdin (/app/node_modules/esbuild/lib/main.js:1725:19)
#14 146.6     at sendRequest (/app/node_modules/esbuild/lib/main.js:617:14)
#14 146.6     at start (/app/node_modules/esbuild/lib/main.js:1254:9)
#14 146.6     at Object.transform2 [as transform] (/app/node_modules/esbuild/lib/main.js:1304:5)
#14 146.6 Emitted 'error' event on Socket instance at:
#14 146.6     at emitErrorNT (internal/streams/destroy.js:106:8)
#14 146.6     at emitErrorCloseNT (internal/streams/destroy.js:74:3)
#14 146.6     at processTicksAndRejections (internal/process/task_queues.js:82:21)
#14 146.6     at runNextTicks (internal/process/task_queues.js:64:3)
#14 146.6     at processImmediate (internal/timers.js:437:9) {
#14 146.6   errno: -32,
#14 146.6   code: 'EPIPE',
#14 146.6   syscall: 'write'
</code>```

Here is my DockerFile:

```<code>#stage 1
FROM node:14.17.6 as node
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build --prod
#stage 2
FROM nginx:alpine
COPY --from=node /app/dist/Angular /usr/share/nginx/html
</code>```

package.json

```<code>{
  "name": "angular",
  "version": "1.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.2.0",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "~12.2.0",
    "@angular/compiler": "~12.2.0",
    "@angular/core": "~12.2.0",
    "@angular/fire": "^7.2.0",
    "@angular/forms": "~12.2.0",
    "@angular/material": "^12.2.13",
    "@angular/platform-browser": "~12.2.0",
    "@angular/platform-browser-dynamic": "~12.2.0",
    "@angular/router": "~12.2.0",
    "bootstrap": "^5.1.3",
    "font-awesome": "^4.7.0",
    "jquery": "^3.6.0",
    "ngx-bootstrap": "^7.1.2",
    "rating": "^0.1.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4",
    "firebase": "^9.4.0",
    "rxfire": "^6.0.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.5",
    "@angular/cli": "~12.2.5",
    "@angular/compiler-cli": "~12.2.0",
    "@types/jasmine": "~3.8.0",
    "@types/lodash": "^4.14.178",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.3.5"
  }
}

</code>```

I am using Docker Desktop 4.4.4 for Windows

PS : I have already tried to incrase docker engine's memory and tried several versions of node but I have the same problem.

The application can run normally on my machine but only the Docker image cannot build.

Can any one help please?

答:
The problem is solved by adding this line in the DockerFile:

```<code>RUN npm i -g @angular/cli
</code>```

It seems that the problem occurs when launching e2e tests and Angular CLI is needes

DockefFile becomes:

```<code>#stage 1
FROM node:14.17.6 as node
WORKDIR /app
COPY . .
RUN npm i -g @angular/cli
RUN npm install
RUN npm run build --prod
#stage 2
FROM nginx:alpine
COPY --from=node /app/dist/Angular /usr/share/nginx/html
</code>```

Body:
I an trying to build an Angular image but i'm getting this error:

#14 130.6 - Generating browser application bundles (phase: setup)...
#14 146.6 events.js:377
#14 146.6       throw er; // Unhandled 'error' event
#14 146.6       ^
#14 146.6
#14 146.6 Error: write EPIPE
#14 146.6     at afterWriteDispatched (internal/stream_base_commons.js:156:25)
#14 146.6     at writeGeneric (internal/stream_base_commons.js:147:3)
#14 146.6     at Socket._writeGeneric (net.js:787:11)
#14 146.6     at Socket._write (net.js:799:8)
#14 146.6     at writeOrBuffer (internal/streams/writable.js:358:12)
#14 146.6     at Socket.Writable.write (internal/streams/writable.js:303:10)
#14 146.6     at Object.writeToStdin (/app/node_modules/esbuild/lib/main.js:1725:19)
#14 146.6     at sendRequest (/app/node_modules/esbuild/lib/main.js:617:14)
#14 146.6     at start (/app/node_modules/esbuild/lib/main.js:1254:9)
#14 146.6     at Object.transform2 [as transform] (/app/node_modules/esbuild/lib/main.js:1304:5)
#14 146.6 Emitted 'error' event on Socket instance at:
#14 146.6     at emitErrorNT (internal/streams/destroy.js:106:8)
#14 146.6     at emitErrorCloseNT (internal/streams/destroy.js:74:3)
#14 146.6     at processTicksAndRejections (internal/process/task_queues.js:82:21)
#14 146.6     at runNextTicks (internal/process/task_queues.js:64:3)
#14 146.6     at processImmediate (internal/timers.js:437:9) {
#14 146.6   errno: -32,
#14 146.6   code: 'EPIPE',
#14 146.6   syscall: 'write'

Here is my DockerFile:

#stage 1
FROM node:14.17.6 as node
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build --prod
#stage 2
FROM nginx:alpine
COPY --from=node /app/dist/Angular /usr/share/nginx/html

package.json

{
  "name": "angular",
  "version": "1.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.2.0",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "~12.2.0",
    "@angular/compiler": "~12.2.0",
    "@angular/core": "~12.2.0",
    "@angular/fire": "^7.2.0",
    "@angular/forms": "~12.2.0",
    "@angular/material": "^12.2.13",
    "@angular/platform-browser": "~12.2.0",
    "@angular/platform-browser-dynamic": "~12.2.0",
    "@angular/router": "~12.2.0",
    "bootstrap": "^5.1.3",
    "font-awesome": "^4.7.0",
    "jquery": "^3.6.0",
    "ngx-bootstrap": "^7.1.2",
    "rating": "^0.1.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4",
    "firebase": "^9.4.0",
    "rxfire": "^6.0.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.5",
    "@angular/cli": "~12.2.5",
    "@angular/compiler-cli": "~12.2.0",
    "@types/jasmine": "~3.8.0",
    "@types/lodash": "^4.14.178",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.3.5"
  }
}

I am using Docker Desktop 4.4.4 for Windows

PS : I have already tried to incrase docker engine's memory and tried several versions of node but I have the same problem.

The application can run normally on my machine but only the Docker image cannot build.

Can any one help please?

Body:
The problem is solved by adding this line in the DockerFile:

RUN npm i -g @angular/cli

It seems that the problem occurs when launching e2e tests and Angular CLI is needes

DockefFile becomes:

#stage 1
FROM node:14.17.6 as node
WORKDIR /app
COPY . .
RUN npm i -g @angular/cli
RUN npm install
RUN npm run build --prod
#stage 2
FROM nginx:alpine
COPY --from=node /app/dist/Angular /usr/share/nginx/html


问:
Add '--warning-mode all' command line argument in Android Studio
I am getting the following message when I compile an Android Studio project:

```<code>Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
</code>```

How do I add the '--warning-mode all' command line setting to my Android Studio project so I can find the deprecated feature?

答:
This error is currently being caused by the shutdown of jcenter.

"The RepositoryHandler.jcenter() method has been deprecated. This is scheduled to be removed in Gradle 8.0. JFrog announced JCenter's shutdown in February 2021. Use mavenCentral() instead. Consult the upgrading guide for further information: https://docs.gradle.org/7.0.2/userguide/upgrading_version_6.html#jcenter_deprecation"

Body:
I am getting the following message when I compile an Android Studio project:

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.

How do I add the '--warning-mode all' command line setting to my Android Studio project so I can find the deprecated feature?


问:
How to attach attribute to a PDF file programmatically?
How to attach attribute to a PDF file programmatically, without acrobat or any other reader So that it will opened  with Zoom to fit width, I've copied this attribute from Smatra pdf viewer settings file?

By default a file opened in browser with fit width, but in acrobat or other readers as fit page. So its the property of viewer instead of PDF file.
I need to change view of a very long height page view.

change in zoom view of Smatra PDF settings by default and for a file

答:
SumatraPDF uses a default FileState for when a new file is opened, Adobe Acrobat does the same.

In both you can change that DefaultZoom = Fit Width via their settings menu.

However for re-opening files SumatraPDF "Remembers" the users preference for each file in the Advanced SumatraPDF-settings.txt, so the FileState may be reopened in the next session to over-ride the default i.e. keeping some view settings for re-use. This is essential behaviour for pre-viewing a constantly changing pdf at same zoom whilst editing the contents using say LaTeX.

PDF viewers do not have to respect the internal file settings of a PDF (users must have the ultimate user control for accesibility, so can switch it off or change its behaviour in Adobe Reader).

A browser can be instructed to fit width using the external hash tag.pdf#FitWidth but again a user can change the toolbar or other interface settings to their choice by adding or removing such directives.

Both SumatraPDF and Acrobat can receive similar user command line instructions when opening a file.

Adobe Acrobat will optionally respect the settings Adobe PRO or similar PDF writer has stored within the PDF and may use those to over-ride its initial default settings (except when doubly over-riden by the user).

So using a programmable library you can set any view setting default it supports but many readers may not (and dont have to) obey that internal Adobe behaviour.


问:
How to rotate a drawable with anti-aliasing enabled
I need to rotate an ImageView by a few degrees.  I'm doing this by subclassing ImageView and overloading onDraw()

```<code>@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.scale(0.92f,0.92f);
    canvas.translate(14, 0);
    canvas.rotate(1,0,0);
    super.onDraw(canvas);
    canvas.restore();
}
</code>```

The problem is that the image that results shows a bunch of jaggies.

http://img.skitch.com/20100608-gmdy4sexsm1c71di9rgiktdjhu.png

How can I antialias an ImageView that I need to rotate in order to eliminate jaggies?  Is there a better way to do this?

答:
This rotation solves just one part of problem - jagged edges, but the image instead became wierd.

ifound only one solution yet:
in ondraw or dispatch draw method

```<code>        Bitmap bmp = ((BitmapDrawable)image.getDrawable()).getBitmap();
    double scale = (0.0+bmp.getWidth()+40.0)/getWidth();
    if (scale > 1){
        bmp = Bitmap.createScaledBitmap(bmp, getWidth()-40, (int) (bmp.getHeight()/scale), true);
    }

    canvas.drawColor(Color.TRANSPARENT);
    canvas.save();

    canvas.translate(20, yShift);

    int left = borderSize;
    int top = borderSize;
    int right = bmp.getWidth() - borderSize;
    int bottom = bmp.getHeight() - borderSize;

    if(showText){
        mPaint.setColor(Color.WHITE);
        canvas.rotate(getAngel());
        canvas.drawRect(left, top, right, bottom, mPaint);

        canvas.translate(0,0);
        textFrame.draw(canvas);
    }else{
        // rotaed bitmap
        mMatrix.setRotate(getAngel());

        // draw bitmap after creation of new rotated bitmap from rotated matrix
        canvas.drawBitmap(Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mMatrix, true)
                   , 0, 0, mPaint);
    }
    canvas.restore();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to rotate an ImageView by a few degrees.  I'm doing this by subclassing ImageView and overloading onDraw()

@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.scale(0.92f,0.92f);
    canvas.translate(14, 0);
    canvas.rotate(1,0,0);
    super.onDraw(canvas);
    canvas.restore();
}

The problem is that the image that results shows a bunch of jaggies.

http://img.skitch.com/20100608-gmdy4sexsm1c71di9rgiktdjhu.png

How can I antialias an ImageView that I need to rotate in order to eliminate jaggies?  Is there a better way to do this?

Body:
This rotation solves just one part of problem - jagged edges, but the image instead became wierd.

ifound only one solution yet:
in ondraw or dispatch draw method

        Bitmap bmp = ((BitmapDrawable)image.getDrawable()).getBitmap();
    double scale = (0.0+bmp.getWidth()+40.0)/getWidth();
    if (scale > 1){
        bmp = Bitmap.createScaledBitmap(bmp, getWidth()-40, (int) (bmp.getHeight()/scale), true);
    }

    canvas.drawColor(Color.TRANSPARENT);
    canvas.save();

    canvas.translate(20, yShift);

    int left = borderSize;
    int top = borderSize;
    int right = bmp.getWidth() - borderSize;
    int bottom = bmp.getHeight() - borderSize;

    if(showText){
        mPaint.setColor(Color.WHITE);
        canvas.rotate(getAngel());
        canvas.drawRect(left, top, right, bottom, mPaint);

        canvas.translate(0,0);
        textFrame.draw(canvas);
    }else{
        // rotaed bitmap
        mMatrix.setRotate(getAngel());

        // draw bitmap after creation of new rotated bitmap from rotated matrix
        canvas.drawBitmap(Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mMatrix, true)
                   , 0, 0, mPaint);
    }
    canvas.restore();


问:
Serialize array char, int8_t and int16_t in protobuf for C++
In protobuf, how would you serialize an array of char's, (u)int8_t or (u)int16_t? Should the message look like this:

```<code>message ArrayWithNotSupportedTypes
{
int32 type = 1;
string byte_stream = 2;
}
</code>```

where type could store some unique id of the element type stored in the array.
And then the byte_stream  is populated with contents of an array, where values are of one of the types above?

Also,I have seen that there is a type called bytes in protobuf, that is translated to an std::string in the corresponding grpc.pb.h files. Is there any advantage of choosing bytes ahead of string?

答:
If the array size is not big, you can waste some space to make the interface simpler.

```<code>message ArrayWithNotSupportedTypes
{
  repeated int32 data = 1; // one data entry per one element
}
</code>```

If the array size is big, you can use your solution to indicate the type

```<code>message ArrayWithNotSupportedTypes
{
  enum Type {
    CHAR = 0;
    INT8 = 1;
    INT16 = 2;
  }
  optional Type type = 1;
  optional bytes data = 2;
}
</code>```

bytes and string are similar in C++: why protocol buffer bytes is string in c++?

Reference: https://developers.google.com/protocol-buffers/docs/proto3#scalar

Body:
In protobuf, how would you serialize an array of char's, (u)int8_t or (u)int16_t? Should the message look like this:

message ArrayWithNotSupportedTypes
{
int32 type = 1;
string byte_stream = 2;
}

where type could store some unique id of the element type stored in the array.
And then the byte_stream  is populated with contents of an array, where values are of one of the types above?

Also,I have seen that there is a type called bytes in protobuf, that is translated to an std::string in the corresponding grpc.pb.h files. Is there any advantage of choosing bytes ahead of string?

Body:
If the array size is not big, you can waste some space to make the interface simpler.

message ArrayWithNotSupportedTypes
{
  repeated int32 data = 1; // one data entry per one element
}

If the array size is big, you can use your solution to indicate the type

message ArrayWithNotSupportedTypes
{
  enum Type {
    CHAR = 0;
    INT8 = 1;
    INT16 = 2;
  }
  optional Type type = 1;
  optional bytes data = 2;
}

bytes and string are similar in C++: why protocol buffer bytes is string in c++?

Reference: https://developers.google.com/protocol-buffers/docs/proto3#scalar


问:
how to call derived function using base class object
```<code>class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{
    public Child()
    {

    }

    public int GetNo()
    {
        return 2;
    }
}

Parent p = new Child();
p.GetNo();
</code>```

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo()
But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

Any sugguestions are valued.
Thanks

答:
You can force this with an explicit cast e.g.

```<code>((Child)p).GetNo();
</code>```

Or you can use hiding e.g.

```<code>public new int GetNo()
{
  return 2;
}
</code>```

Though I think the latter only gets called if the variable is typed to the class that hides the method.

If you really need to override a method properly and it's from a compiled DLL consider getting in touch with the developers to see whether they can make the method virtual (and if not why) or if an open source project just get the source code and modify it yourself.

Body:
class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{
    public Child()
    {

    }

    public int GetNo()
    {
        return 2;
    }
}

Parent p = new Child();
p.GetNo();

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo()
But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

Any sugguestions are valued.
Thanks

Body:
You can force this with an explicit cast e.g.

((Child)p).GetNo();

Or you can use hiding e.g.

public new int GetNo()
{
  return 2;
}

Though I think the latter only gets called if the variable is typed to the class that hides the method.

If you really need to override a method properly and it's from a compiled DLL consider getting in touch with the developers to see whether they can make the method virtual (and if not why) or if an open source project just get the source code and modify it yourself.


问:
Printing Armstrong Numbers from a Range in a For Loop as an Array *Python*
I'm trying to print armstrong values from a specified range in an array style format.
My current code is as below:

```<code>def main():

#Low and high set the bounds for the loop
low = 100

high = 499

#start the for loop for num in the range initialized
for num in range(low, high +1):

    #gets the exponent for each number
    ind_num = len(str(num))

    #initializes the addition of each number
    add = 0

    # sets x equal to num so we can check if the number is armstrong or not
    x = num

    #calculates the armstrong
    while x > 0:
        digit = x % 10

        add += digit ** ind_num

        x //= 10

    if num ==  add:

       print(num)

if __name__ == "__main__":
    main()
</code>```

The output comes out to be:

```<code>153
370
371
407
</code>```

and I want it to be:  [153, 370, 371, 407]
I'm probably thinking too hard on how to make the integers that come out of the for loop arrange as an array, but so far changing them to strings and appending them with a separate defined array variable did not work.

答:
If you replace print(num) with yield num your function will be a generator of armstrong numbers. Make low and high parameters and you end up with a versatile function:

```<code>def armstrong(low, high):
    for num in range(low, high +1):
        ind_num = len(str(num))
        add = 0
        x = num
        while x > 0:
            digit = x % 10
            add += digit ** ind_num
            x //= 10
        if num == add:
            yield num

result = list(armstrong(100, 499))
print(result)
</code>```

Body:
I'm trying to print armstrong values from a specified range in an array style format.
My current code is as below:

def main():

#Low and high set the bounds for the loop
low = 100

high = 499

#start the for loop for num in the range initialized
for num in range(low, high +1):

    #gets the exponent for each number
    ind_num = len(str(num))

    #initializes the addition of each number
    add = 0

    # sets x equal to num so we can check if the number is armstrong or not
    x = num

    #calculates the armstrong
    while x > 0:
        digit = x % 10

        add += digit ** ind_num

        x //= 10

    if num ==  add:

       print(num)

if __name__ == "__main__":
    main()

The output comes out to be:

153
370
371
407

and I want it to be:  [153, 370, 371, 407]
I'm probably thinking too hard on how to make the integers that come out of the for loop arrange as an array, but so far changing them to strings and appending them with a separate defined array variable did not work.

Body:
If you replace print(num) with yield num your function will be a generator of armstrong numbers. Make low and high parameters and you end up with a versatile function:

def armstrong(low, high):
    for num in range(low, high +1):
        ind_num = len(str(num))
        add = 0
        x = num
        while x > 0:
            digit = x % 10
            add += digit ** ind_num
            x //= 10
        if num == add:
            yield num

result = list(armstrong(100, 499))
print(result)


问:
How do I format a url string to pass into stored procedure
I created the below stored procedure in sql server that requires 3 parameters: Date, URL, & Table Name:

```<code>ALTER PROCEDURE [stg].[usp_Delete_Data]
    (@DateLookBack date,
     @siteUrl nvarchar(100),
     @tableName SYSNAME)
AS
BEGIN
    SET QUOTED_IDENTIFIER ON

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    DECLARE @sql NVARCHAR(MAX);

    SET @sql = N'DELETE FROM ' + CONCAT('[stg].[',@tableName,']') +
                'WHERE date = ' + FORMAT(@DateLookBack, 'yyyyMMdd')  +
                'AND siteUrl = ' + @siteUrl

    EXEC sp_executesql @Sql
END
</code>```

When I pass in a url, like 'https://stackoverflow.com', I get an error message:

Incorrect syntax near 'https:'

How do I format the url string so that it can pass into the query successfully?

答:
I'd strongly advise against this method. Having so many tables of the same structure that it requires a single procedure where the table name is dynamic is a code smell in itself.

If you must use dynamic sql though, at least use parameters as much as possible and only inject your table name, i.e.

```<code>SET @sql = CONCAT(N'DELETE FROM [stg].' QUOTENAME(@tableName),
                  ' WHERE Date = @Date AND SiteUrl = @SiteUrl;');

EXECUTE sp_executesql @sql, N'@Date date, @SiteUrl nvarchar(100)', @date, @SiteUrl;
</code>```

Body:
I created the below stored procedure in sql server that requires 3 parameters: Date, URL, & Table Name:

ALTER PROCEDURE [stg].[usp_Delete_Data]
    (@DateLookBack date,
     @siteUrl nvarchar(100),
     @tableName SYSNAME)
AS
BEGIN
    SET QUOTED_IDENTIFIER ON

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    DECLARE @sql NVARCHAR(MAX);

    SET @sql = N'DELETE FROM ' + CONCAT('[stg].[',@tableName,']') +
                'WHERE date = ' + FORMAT(@DateLookBack, 'yyyyMMdd')  +
                'AND siteUrl = ' + @siteUrl

    EXEC sp_executesql @Sql
END

When I pass in a url, like 'https://stackoverflow.com', I get an error message:

Incorrect syntax near 'https:'

How do I format the url string so that it can pass into the query successfully?

Body:
I'd strongly advise against this method. Having so many tables of the same structure that it requires a single procedure where the table name is dynamic is a code smell in itself.

If you must use dynamic sql though, at least use parameters as much as possible and only inject your table name, i.e.

SET @sql = CONCAT(N'DELETE FROM [stg].' QUOTENAME(@tableName),
                  ' WHERE Date = @Date AND SiteUrl = @SiteUrl;');

EXECUTE sp_executesql @sql, N'@Date date, @SiteUrl nvarchar(100)', @date, @SiteUrl;


问:
Typescript Mongoose: Why are methods of aggregated documents undefined
When using mongoose aggregate it returns an array of ProfileDocuments.
The Documents in the result array do not contain the methods of the ProfileDocument implementation.
Which leads to being unable to call document methods like checkPassword on the documents from the database.

Aggregate Example

```<code>ProfileSchema.statics.findByLogin = async function (login: string) {
  // why do methods of aggregated documents not work?
  const results = await this.aggregate([{
    $match: {
      $or:[{username: login}, {mail: login}]
    }
  }])

  if (results.length === 0) {
    throw new Error('Profile not found')
  }

  const profile = await this.findById(results[0]._id)

  console.log(results[0].checkPassword)
  console.log(profile.checkPassword)

  return profile
}
</code>```

Console Output

```<code>undefined
[Function (anonymous)]
</code>```

Method implementation

```<code>interface ProfileDocument extends IProfile, Document {
  getDisplayname: () => Promise<string>
}

ProfileSchema.methods.checkPassword = async function (password: string) {
  return await bcrypt.compare(password, this.pass)
}
</code>```

答:
As @Thakur mentioned aggregate returns raw documents. Mongoose offers a hydrate method to add the methods to a document.

Use ProfileSchema.hydrate(doc) or in the context of the static method this.hydrate(doc) returns ProfileDocuments.

```<code>/**
 * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
 * The document returned has no paths marked as modified initially.
 */
hydrate(obj: any): EnforceDocument<T, TMethods>;
</code>```

Body:
When using mongoose aggregate it returns an array of ProfileDocuments.
The Documents in the result array do not contain the methods of the ProfileDocument implementation.
Which leads to being unable to call document methods like checkPassword on the documents from the database.

Aggregate Example

ProfileSchema.statics.findByLogin = async function (login: string) {
  // why do methods of aggregated documents not work?
  const results = await this.aggregate([{
    $match: {
      $or:[{username: login}, {mail: login}]
    }
  }])

  if (results.length === 0) {
    throw new Error('Profile not found')
  }

  const profile = await this.findById(results[0]._id)

  console.log(results[0].checkPassword)
  console.log(profile.checkPassword)

  return profile
}

Console Output

undefined
[Function (anonymous)]

Method implementation

interface ProfileDocument extends IProfile, Document {
  getDisplayname: () => Promise<string>
}

ProfileSchema.methods.checkPassword = async function (password: string) {
  return await bcrypt.compare(password, this.pass)
}

Body:
As @Thakur mentioned aggregate returns raw documents. Mongoose offers a hydrate method to add the methods to a document.

Use ProfileSchema.hydrate(doc) or in the context of the static method this.hydrate(doc) returns ProfileDocuments.

/**
 * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
 * The document returned has no paths marked as modified initially.
 */
hydrate(obj: any): EnforceDocument<T, TMethods>;


问:
Finding Maximum Part
I'm Having tables with columns in parentheses like this:

```<code>Employee (Empno, Empname, City)
Project (Pno, Pname)
Part (Partno, Partname, Color)
Use (Pno, Partno)
Works (Empno, Pno)
</code>```

I'm Using ORACLE 11g Express Edition

My Query:

SELECT *
  FROM (SELECT p.Pname AS Project_name
          FROM (SELECT COUNT(Color) AS colorPart, U.Pno, P.Color
                  FROM Part P
                  JOIN Use u
                    ON u.Partno = p.Partno
                   and p.Color = 'Red'
                 GROUP BY Color, Pno
                 ORDER BY colorPart DESC)
         WHERE rownum = 1) AS Final
  JOIN Project p
    ON Final.Pno = p.Pno;
```

Here I'm getting the error: ORA-00933: SQL command not properly ended

答:
You can rewrite the current query as

SELECT p.Pname AS Project_name
  FROM (SELECT Pno
          FROM (SELECT Pno, COUNT(Color) AS ColorPart
                  FROM Part P
                  JOIN Use u
                    ON u.Partno = p.Partno
                   AND p.Color = 'Red'
                 GROUP BY Color, Pno
                 ORDER BY ColorPart DESC)
         WHERE rownum = 1) Final
  JOIN Project p
    ON Final.Pno = p.Pno
```

where

AS preceding the alias Final should be removed, since aliasing a
subquery is not allowed in Oracle DB unlike to some other DBMS

p.Pname should be in the outermost query

Title: Finding Maximum Part

Body:
I'm Having tables with columns in parentheses like this:

Employee (Empno, Empname, City)
Project (Pno, Pname)
Part (Partno, Partname, Color)
Use (Pno, Partno)
Works (Empno, Pno)

I'm Using ORACLE 11g Express Edition

My Query:

SELECT *
  FROM (SELECT p.Pname AS Project_name
          FROM (SELECT COUNT(Color) AS colorPart, U.Pno, P.Color
                  FROM Part P
                  JOIN Use u
                    ON u.Partno = p.Partno
                   and p.Color = 'Red'
                 GROUP BY Color, Pno
                 ORDER BY colorPart DESC)
         WHERE rownum = 1) AS Final
  JOIN Project p
    ON Final.Pno = p.Pno;

Here I'm getting the error: ORA-00933: SQL command not properly ended

Body:
You can rewrite the current query as

SELECT p.Pname AS Project_name
  FROM (SELECT Pno
          FROM (SELECT Pno, COUNT(Color) AS ColorPart
                  FROM Part P
                  JOIN Use u
                    ON u.Partno = p.Partno
                   AND p.Color = 'Red'
                 GROUP BY Color, Pno
                 ORDER BY ColorPart DESC)
         WHERE rownum = 1) Final
  JOIN Project p
    ON Final.Pno = p.Pno

where

AS preceding the alias Final should be removed, since aliasing a
subquery is not allowed in Oracle DB unlike to some other DBMS

p.Pname should be in the outermost query


问:
Jetpack Compose Textfield Alignment
I'm new to jetpack compose. I want to start typing from TextField's centervertically-start
position but I can't put "Example" to center
vertically-start position.

```<code>Row(
    modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .shadow(5.dp)
        .background(Color.Yellow),

) {

    BasicTextField(
        value = text,
        onValueChange = {onvalueChange(it)},
        modifier = Modifier.weight(10f).background(Color.Blue).fillMaxSize(),
        singleLine = true,
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Center
        )

    )
    Image(painter = painterResource(id = R.drawable.ic_baseline_search_24),
        contentDescription = "Search",
        modifier = Modifier.weight(2f).fillMaxSize()

    )
</code>```

This is my code

And this is what I want to do.

答:
Row has a verticalAlignment for this. Also, if you want your TextField left align like the picture, remove the textAlign (or change it but it default to start)

```<code>Row(
    modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .shadow(5.dp)
        .background(Color.Yellow),
    verticalAlignment = Alignment.CenterVertically,
) {

    BasicTextField(
        value = text,
        onValueChange = {onvalueChange(it)},
        modifier = Modifier.weight(10f).background(Color.Blue).fillMaxSize(),
        singleLine = true,
    )
    Image(painter = painterResource(id = R.drawable.ic_baseline_search_24),
        contentDescription = "Search",
        modifier = Modifier.weight(2f).fillMaxSize()

    )
}
</code>```

Title: Jetpack Compose Textfield Alignment

Body:
I'm new to jetpack compose. I want to start typing from TextField's centervertically-start
position but I can't put "Example" to center
vertically-start position.

Row(
    modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .shadow(5.dp)
        .background(Color.Yellow),

) {

    BasicTextField(
        value = text,
        onValueChange = {onvalueChange(it)},
        modifier = Modifier.weight(10f).background(Color.Blue).fillMaxSize(),
        singleLine = true,
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Center
        )

    )
    Image(painter = painterResource(id = R.drawable.ic_baseline_search_24),
        contentDescription = "Search",
        modifier = Modifier.weight(2f).fillMaxSize()

    )

This is my code

And this is what I want to do.

Body:
Row has a verticalAlignment for this. Also, if you want your TextField left align like the picture, remove the textAlign (or change it but it default to start)

Row(
    modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .shadow(5.dp)
        .background(Color.Yellow),
    verticalAlignment = Alignment.CenterVertically,
) {

    BasicTextField(
        value = text,
        onValueChange = {onvalueChange(it)},
        modifier = Modifier.weight(10f).background(Color.Blue).fillMaxSize(),
        singleLine = true,
    )
    Image(painter = painterResource(id = R.drawable.ic_baseline_search_24),
        contentDescription = "Search",
        modifier = Modifier.weight(2f).fillMaxSize()

    )
}


问:
VBA Merging two strings excluding overlap part
Is it possible to merge two strings but when end of s1 is the same as beginning of s2 do not repeat that part of the string? For example:

```<code>s1 = "The quick "          s2 = "brown fox"       -> "The quick brown fox"
s1 = "The quick brown fox" s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown "    s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown fox" s2 = ""                -> "The quick brown fox"
s1 = ""                    s2 = "fox"             -> "fox"
</code>```

答:
Just for fun, I'll add a formula:

Formula in C1:

```<code>=@LET(X,LEN(A1),Y,SEQUENCE(X),Z,MID(A1,Y,X),SORT(IF(IFERROR(SEARCH(Z&"*",B1),0)=1,LEFT(A1,X-LEN(Z)),A1)))&B1
</code>```

Body:
Is it possible to merge two strings but when end of s1 is the same as beginning of s2 do not repeat that part of the string? For example:

s1 = "The quick "          s2 = "brown fox"       -> "The quick brown fox"
s1 = "The quick brown fox" s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown "    s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown fox" s2 = ""                -> "The quick brown fox"
s1 = ""                    s2 = "fox"             -> "fox"

Body:
Just for fun, I'll add a formula:

Formula in C1:

=@LET(X,LEN(A1),Y,SEQUENCE(X),Z,MID(A1,Y,X),SORT(IF(IFERROR(SEARCH(Z&"*",B1),0)=1,LEFT(A1,X-LEN(Z)),A1)))&B1


问:
How to make buttons stay selected?
the rating buttons on my site lose their state when I click on any other place on the page.

How can I make them stay selected (red)? Please see the screenshots below:

button {
  width: 100%;
  background-color: #8e95a2;
  border: none;
  padding: 15px;
}

button:active {
  background: blue;
}

button:hover {
  border-collapse: collapse;
  text-align: center;
  color: #ffffff;
  background-color: #ad0f0f;
  border-radius: 0px;
}

button:focus {
  border-collapse: collapse;
  text-align: center;
  color: #ffffff;
  background-color: #ad0f0f;
  border-radius: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table style="width:100%">
  <tr>
    <td><button type="button">1</button></td>
    <td><button type="button">2</button></td>
    <td><button type="button">3</button></td>
    <td><button type="button">4</button></td>
    <td><button type="button">5</button></td>
    <td><button type="button">6</button></td>
    <td><button type="button">7</button></td>
    <td><button type="button">8</button></td>
    <td><button type="button">9</button></td>
    <td><button type="button">10</button></td>
  </tr>
</table></code>```

答:
Here's an example using <input type="radio">:

.rating {
  display: flex;
  gap: 15px;
}

.rating label {
  flex: 1 1 auto;
  cursor: pointer;
}

.rating span {
  background-color: #8e95a2;
  padding: 15px;
  display: flex;
  align-content: center;
  justify-content: center;
}

.rating input {
  display: none;
}

.rating input:checked + span {
  background-color: blue;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>How satisfied were you overall?</p>
<div class="rating">
  <label for="rate-1">
    <input type="radio" id="rate-1" name="rate" value="1" />
    <span>1</span>
  </label>
  <label for="rate-2">
    <input type="radio" id="rate-2" name="rate" value="2" />
    <span>2</span>
  </label>
  <label for="rate-3">
    <input type="radio" id="rate-3" name="rate" value="3" />
    <span>3</span>
  </label>
  <label for="rate-4">
    <input type="radio" id="rate-4" name="rate" value="4" />
    <span>4</span>
  </label>
  <label for="rate-5">
    <input type="radio" id="rate-5" name="rate" value="5" />
    <span>5</span>
  </label>
  <label for="rate-6">
    <input type="radio" id="rate-6" name="rate" value="6" />
    <span>6</span>
  </label>
  <label for="rate-7">
    <input type="radio" id="rate-7" name="rate" value="7" />
    <span>7</span>
  </label>
  <label for="rate-8">
    <input type="radio" id="rate-8" name="rate" value="8" />
    <span>8</span>
  </label>
  <label for="rate-9">
    <input type="radio" id="rate-9" name="rate" value="9" />
    <span>9</span>
  </label>
  <label for="rate-10">
    <input type="radio" id="rate-10" name="rate" value="10" />
    <span>10</span>
  </label>
</div>

<p>Name:</p>
<p><input type="text" name="name"></p>
<p><button type="button">Submit</button></p></code>```

Title: How to make buttons stay selected?

Body:
the rating buttons on my site lose their state when I click on any other place on the page.

How can I make them stay selected (red)? Please see the screenshots below:

button {
  width: 100%;
  background-color: #8e95a2;
  border: none;
  padding: 15px;
}

button:active {
  background: blue;
}

button:hover {
  border-collapse: collapse;
  text-align: center;
  color: #ffffff;
  background-color: #ad0f0f;
  border-radius: 0px;
}

button:focus {
  border-collapse: collapse;
  text-align: center;
  color: #ffffff;
  background-color: #ad0f0f;
  border-radius: 0px;
}

    <button type="button">1</button>
    <button type="button">2</button>
    <button type="button">3</button>
    <button type="button">4</button>
    <button type="button">5</button>
    <button type="button">6</button>
    <button type="button">7</button>
    <button type="button">8</button>
    <button type="button">9</button>
    <button type="button">10</button>

Body:
Here's an example using <input type="radio">:

.rating {
  display: flex;
  gap: 15px;
}

.rating label {
  flex: 1 1 auto;
  cursor: pointer;
}

.rating span {
  background-color: #8e95a2;
  padding: 15px;
  display: flex;
  align-content: center;
  justify-content: center;
}

.rating input {
  display: none;
}

.rating input:checked + span {
  background-color: blue;
  color: white;
}

<p>How satisfied were you overall?</p>
<div class="rating">
  <label for="rate-1">
    <input type="radio" id="rate-1" name="rate" value="1" />
    <span>1</span>
  </label>
  <label for="rate-2">
    <input type="radio" id="rate-2" name="rate" value="2" />
    <span>2</span>
  </label>
  <label for="rate-3">
    <input type="radio" id="rate-3" name="rate" value="3" />
    <span>3</span>
  </label>
  <label for="rate-4">
    <input type="radio" id="rate-4" name="rate" value="4" />
    <span>4</span>
  </label>
  <label for="rate-5">
    <input type="radio" id="rate-5" name="rate" value="5" />
    <span>5</span>
  </label>
  <label for="rate-6">
    <input type="radio" id="rate-6" name="rate" value="6" />
    <span>6</span>
  </label>
  <label for="rate-7">
    <input type="radio" id="rate-7" name="rate" value="7" />
    <span>7</span>
  </label>
  <label for="rate-8">
    <input type="radio" id="rate-8" name="rate" value="8" />
    <span>8</span>
  </label>
  <label for="rate-9">
    <input type="radio" id="rate-9" name="rate" value="9" />
    <span>9</span>
  </label>
  <label for="rate-10">
    <input type="radio" id="rate-10" name="rate" value="10" />
    <span>10</span>
  </label>
</div>

<p>Name:</p>
<p><input type="text" name="name"></p>
<p><button type="button">Submit</button></p>


问:
How to test an abstract superclass in Java
I'm a student studying software development (1st year) and the teaching language we are using is Java. We have covered basics, and most of OOP, but I've been practicing making a Shop Administration System and I've come up against something I can't reckon with.

I'm trying to unit test two classes which are both abstract superclasses of several other classes I plan on implementing, as per the UML below

Person Superclass and Employee subclass - both abstract

I've read through a series of posts on here and I see a lot of people were recommending things like power mock and mockito for making mock objects.  I'm probably trying to learn too much at once as it is but basically I landed on concrete "wrapper" private classes in the unit test class that i used to polymorphically create the Employee objects (technically EmployeeWrapper objects), then unit testing all the public methods through the wrapper class.

I'm vaugely familiar with the term "bad code smell" and this really stinks. Is there a standard way of testing abstract superclasses without using things like Mockito and Power Mock? Or do i just need to suck it up and use things like that?

This is the code for the classes (with all method bodies removed so you dont have to read through a load of unimportant details

```<code>    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Iterator;

    public abstract class Employee extends Person {

        private double hourlyRate;
        private double hoursPerWeek;
        private LocalDateTime dateOfEmploymentStart;
        private LocalDateTime dateOfEmploymentEnd;
        private Hashtable<LocalDateTime, Integer> shifts;

        private static final double MINIMUM_WAGE = 8.0;

        /**
         * Constructor for Employee for all fields except dateOfHire, which is set to {@code LocalDateTime.now()}
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @param hourlyRate
         * @param weeklyHours
         * @throws IllegalArgumentException if name if blank or null
         */
        public Employee(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
            super(name, email, phoneNumber);
            this.setHourlyRate(hourlyRate);
            this.setWeeklyHours(weeklyHours);
            this.setDateOfEmploymentStart(LocalDateTime.now());
            this.shifts = new Hashtable<LocalDateTime, Integer>();
        }

        /**
         * Constructor for Employee that sets name, email and phoneNumber to provided args; and sets hourly rate and weeklyHours to 0
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @throws IllegalArgumentException if name is blank or null
         */
        public Employee(String name, String email, String phoneNumber) throws IllegalArgumentException {
            this(name, email, phoneNumber, MINIMUM_WAGE, 0);
        }

        /**
         * Constructor for Employee that sets only name
         *
         * @param name
         * @throws IllegalArgumentException
         */
        public Employee(String name) throws IllegalArgumentException {
            this(name, null, null);
        }
    }
</code>```

and the Unit test class (with all test cases bar one removed, and that one method body is left empty - again to stop clutter:

```<code>    import static org.junit.jupiter.api.Assertions.*;

    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Set;

    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;

    class EmployeeTest {

        private class EmployeeWrapper extends Employee {

            public EmployeeWrapper(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
                super(name, email, phoneNumber, hourlyRate, weeklyHours);
            }

            public EmployeeWrapper(String name, String email, String phoneNumber) throws IllegalArgumentException {
                super(name, email, phoneNumber);
            }

            public EmployeeWrapper(String name) throws IllegalArgumentException {
                super(name);
            }
        }

        private String nameValid, emailValid, phoneNumberValid;
        private String nameInvalid, emailInvalid, phoneNumberInvalid;
        private double hourlyRateValid, hourlyRateInvalidLow;
        private double weeklyHoursValid, weeklyHoursInvalid;

        private final double DEFAULT_HOURLY_RATE = 8;
        private final double DEFAULT_WEEKLY_HOURS = 0;
        private final String DEFAULT_EMAIL = "no email provided";
        private final String DEFAULT_PHONE_NUMBER = "no phone number provided";
        private final double MINIMUM_WAGE = 8.0;

        private Employee employee;

        private Hashtable<LocalDateTime, Integer> shiftsValid, shiftsInvalidEmpty;

        private LocalDateTime dateTimeValid, dateTimePast, dateTimeFuture;

        @BeforeEach
        void setUp() throws Exception {

            // valid employee
            nameValid = "testname";
            phoneNumberValid = "123456789";
            emailValid = "test@test.test.com";
            hourlyRateValid = 10.50;
            weeklyHoursValid = 7.5;

            employee = new EmployeeWrapper(nameValid, emailValid, phoneNumberValid, hourlyRateValid, weeklyHoursValid);

            // test data
            nameInvalid = "";
            emailInvalid = ".test@test.com";
            phoneNumberInvalid = "";
            hourlyRateInvalidLow = 5;
            weeklyHoursInvalid = -10;

            dateTimeValid = LocalDateTime.of(2015, 6, 15, 13, 30);
            dateTimePast = LocalDateTime.MIN;
            dateTimeFuture = LocalDateTime.MAX;

            shiftsValid = new Hashtable<LocalDateTime, Integer>();
            shiftsValid.put(dateTimeValid, 6);
            shiftsValid.put(dateTimeFuture, 3);

            shiftsInvalidEmpty = new Hashtable<LocalDateTime, Integer>();

        }

        @Test
        void testEmployeeConstructorValidAllArgs() {
        }

    }

</code>```

This is my first post of Stack Overflow so i apologise profusely if i have omitted any revelent details.

If you see any other stupid things i've done in the code I'll also gladly take any criticism!

edit: thanks everyone for the responses they have been amazing, i really really appreciate it!

答:
as you stated you can't test abstract classes in Java. You need a mocking framework like Mockito or a concrete class that extends your superclass, in this case Employee.
And that's what you have done with your class EmployeeWrapper. Except for the name (i would name it EmployeeImpl) i'm fine with your solution.

Body:
I'm a student studying software development (1st year) and the teaching language we are using is Java. We have covered basics, and most of OOP, but I've been practicing making a Shop Administration System and I've come up against something I can't reckon with.

I'm trying to unit test two classes which are both abstract superclasses of several other classes I plan on implementing, as per the UML below

Person Superclass and Employee subclass - both abstract

I've read through a series of posts on here and I see a lot of people were recommending things like power mock and mockito for making mock objects.  I'm probably trying to learn too much at once as it is but basically I landed on concrete "wrapper" private classes in the unit test class that i used to polymorphically create the Employee objects (technically EmployeeWrapper objects), then unit testing all the public methods through the wrapper class.

I'm vaugely familiar with the term "bad code smell" and this really stinks. Is there a standard way of testing abstract superclasses without using things like Mockito and Power Mock? Or do i just need to suck it up and use things like that?

This is the code for the classes (with all method bodies removed so you dont have to read through a load of unimportant details

    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Iterator;

    public abstract class Employee extends Person {

        private double hourlyRate;
        private double hoursPerWeek;
        private LocalDateTime dateOfEmploymentStart;
        private LocalDateTime dateOfEmploymentEnd;
        private Hashtable<LocalDateTime, Integer> shifts;

        private static final double MINIMUM_WAGE = 8.0;

        /**
         * Constructor for Employee for all fields except dateOfHire, which is set to {@code LocalDateTime.now()}
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @param hourlyRate
         * @param weeklyHours
         * @throws IllegalArgumentException if name if blank or null
         */
        public Employee(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
            super(name, email, phoneNumber);
            this.setHourlyRate(hourlyRate);
            this.setWeeklyHours(weeklyHours);
            this.setDateOfEmploymentStart(LocalDateTime.now());
            this.shifts = new Hashtable<LocalDateTime, Integer>();
        }

        /**
         * Constructor for Employee that sets name, email and phoneNumber to provided args; and sets hourly rate and weeklyHours to 0
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @throws IllegalArgumentException if name is blank or null
         */
        public Employee(String name, String email, String phoneNumber) throws IllegalArgumentException {
            this(name, email, phoneNumber, MINIMUM_WAGE, 0);
        }

        /**
         * Constructor for Employee that sets only name
         *
         * @param name
         * @throws IllegalArgumentException
         */
        public Employee(String name) throws IllegalArgumentException {
            this(name, null, null);
        }
    }

and the Unit test class (with all test cases bar one removed, and that one method body is left empty - again to stop clutter:

    import static org.junit.jupiter.api.Assertions.*;

    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Set;

    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;

    class EmployeeTest {

        private class EmployeeWrapper extends Employee {

            public EmployeeWrapper(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
                super(name, email, phoneNumber, hourlyRate, weeklyHours);
            }

            public EmployeeWrapper(String name, String email, String phoneNumber) throws IllegalArgumentException {
                super(name, email, phoneNumber);
            }

            public EmployeeWrapper(String name) throws IllegalArgumentException {
                super(name);
            }
        }

        private String nameValid, emailValid, phoneNumberValid;
        private String nameInvalid, emailInvalid, phoneNumberInvalid;
        private double hourlyRateValid, hourlyRateInvalidLow;
        private double weeklyHoursValid, weeklyHoursInvalid;

        private final double DEFAULT_HOURLY_RATE = 8;
        private final double DEFAULT_WEEKLY_HOURS = 0;
        private final String DEFAULT_EMAIL = "no email provided";
        private final String DEFAULT_PHONE_NUMBER = "no phone number provided";
        private final double MINIMUM_WAGE = 8.0;

        private Employee employee;

        private Hashtable<LocalDateTime, Integer> shiftsValid, shiftsInvalidEmpty;

        private LocalDateTime dateTimeValid, dateTimePast, dateTimeFuture;

        @BeforeEach
        void setUp() throws Exception {

            // valid employee
            nameValid = "testname";
            phoneNumberValid = "123456789";
            emailValid = "test@test.test.com";
            hourlyRateValid = 10.50;
            weeklyHoursValid = 7.5;

            employee = new EmployeeWrapper(nameValid, emailValid, phoneNumberValid, hourlyRateValid, weeklyHoursValid);

            // test data
            nameInvalid = "";
            emailInvalid = ".test@test.com";
            phoneNumberInvalid = "";
            hourlyRateInvalidLow = 5;
            weeklyHoursInvalid = -10;

            dateTimeValid = LocalDateTime.of(2015, 6, 15, 13, 30);
            dateTimePast = LocalDateTime.MIN;
            dateTimeFuture = LocalDateTime.MAX;

            shiftsValid = new Hashtable<LocalDateTime, Integer>();
            shiftsValid.put(dateTimeValid, 6);
            shiftsValid.put(dateTimeFuture, 3);

            shiftsInvalidEmpty = new Hashtable<LocalDateTime, Integer>();

        }

        @Test
        void testEmployeeConstructorValidAllArgs() {
        }

    }

This is my first post of Stack Overflow so i apologise profusely if i have omitted any revelent details.

If you see any other stupid things i've done in the code I'll also gladly take any criticism!

edit: thanks everyone for the responses they have been amazing, i really really appreciate it!


问:
How to add a filter to Mixpanel (like in Google analytics)
I want to filter my home ip from mixpanel.  In Google Analytics, I can do this by adding a filter to my profile.  Is there something similar in mixpanel or a work around to achieve the same result? My app is built in Rails 3, hosted on heroku.  Thanks.</p>

答: Spoke to their support and they'd suggested that I block api.mixpanel.com in my host file, which works.</p>


问:
Flutter Send user to another screen if response is 401 or 403
I have functions witch I use to get data from the api, and the user can be logged in, but the admin can change the password of the employee, so when the user comes back to the app the besic auth token that is saved in local storage isnt the same as the one that the admin changed to since the admin changed the password, so all i need is that if there is status code such as 401 or 403 to send the user back to the log in screen. And if the response code is 500 to show like an image to come back later.</p>
```<code>Future<Response> fetchWorkingLocationData() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var authorization = prefs.getString('authorization');
  var url = 'https://dev.api.wurk.skyver.co/api/v1/projects';
  basicAuth = 'Basic ' +
      base64Encode(
        utf8.encode('${phoneNumberController.text}:${passwordController.text}'),
      );
  response2 = await http.get(
    Uri.parse(url),
    headers: <String, String>{
      'authorization': authorization ?? basicAuth.toString()
    },
  );
  return response2;
}
</code>```

答:
You can write custom logic based on the statusCode
So something like:

```<code>if (response2.statusCode == HttpStatus.unauthorized) {
  Navigator.pushNamed(
    context,
    'login',
  );
}
</code>```

If you don't have context for the Navigator, check out https://medium.com/flutter-community/navigate-without-context-in-flutter-with-a-navigation-service-e6d76e880c1c

Body:
I have functions witch I use to get data from the api, and the user can be logged in, but the admin can change the password of the employee, so when the user comes back to the app the besic auth token that is saved in local storage isnt the same as the one that the admin changed to since the admin changed the password, so all i need is that if there is status code such as 401 or 403 to send the user back to the log in screen. And if the response code is 500 to show like an image to come back later.

Future<Response> fetchWorkingLocationData() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var authorization = prefs.getString('authorization');
  var url = 'https://dev.api.wurk.skyver.co/api/v1/projects';
  basicAuth = 'Basic ' +
      base64Encode(
        utf8.encode('${phoneNumberController.text}:${passwordController.text}'),
      );
  response2 = await http.get(
    Uri.parse(url),
    headers: <String, String>{
      'authorization': authorization ?? basicAuth.toString()
    },
  );
  return response2;
}

Body:
You can write custom logic based on the statusCode
So something like:

if (response2.statusCode == HttpStatus.unauthorized) {
  Navigator.pushNamed(
    context,
    'login',
  );
}

If you don't have context for the Navigator, check out https://medium.com/flutter-community/navigate-without-context-in-flutter-with-a-navigation-service-e6d76e880c1c


问:
Outputting text from an url that returns JSON
I'm more of a backend guy, this javascript stuff is a bit out of my area. I could really use a point in the right direction :)

So I have an URL that, for example, returns this JSON:

```<code>[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}},
 {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}},
 {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}},
 {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}},
 {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]
</code>```

I want to write a piece of javascript that I can embed in my HTML that will randomly choose and print one of the "fact"s from the JSON URL.

答: Use JSON.parse to convert into an array and pick a random element. If you still can't get it to work post your code.

Body:
I'm more of a backend guy, this javascript stuff is a bit out of my area. I could really use a point in the right direction :)

So I have an URL that, for example, returns this JSON:

[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}},
 {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}},
 {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}},
 {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}},
 {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]

I want to write a piece of javascript that I can embed in my HTML that will randomly choose and print one of the "fact"s from the JSON URL.


问:
Dynamic Data Masking in SSAS cube process
I have dynamic masked data in my SQL Server DB and I want to know what will happen to that if I used this data in  my cube processing . would it be still a masked data is the cube , and can I use the roll security for that or not?</p>

答:
Everything depends on the credential that is being used to connect to the database via cube.
In case if the account has admin access or non masking, then original data would be available else masked data would be in cube</p>


问:
How can I add a counter column that records the number of occurrences of a value in a data frame in R?
I have the following data frame:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6))

and I want to record the number of occurrences of each category so the output would be:

```<code>df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
category_count=c(2,4,4,4,4,2,1))
</code>```

Is there a simple way to do this?

答:
```<code># load package
library(data.table)

# set as data.table
setDT(df)

# count by category
df[, category_count := .N, category]
</code>```

Body:
I have the following data frame:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6))

and I want to record the number of occurrences of each category so the output would be:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
category_count=c(2,4,4,4,4,2,1))

Is there a simple way to do this?


问:
paste on top of the row instead of the bottom row
at the moment I have a sheet that has a script that is time triggered, the script at the end of the day will copy sheets at the bottom of the target sheet, everytime I am trying to do targetSheet.getrange(1,1) + 1; it's not  converting range to int. can someone please help?</p>
```<code>   function copyData() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let rowCount = sourceValues.length;
  let columnCount = sourceValues[0].length;

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  let lastrowCount = targetSheet.getLastRow() + 1;

  let targetRange = targetSheet.getRange(lastrowCount,1, rowCount,columnCount);

  targetRange.setValues(sourceValues);
}
</code>```

答:
Do you mean this?</p>
```<code>function copyDataOnTop() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  var targetValues = targetSheet.getDataRange().getValues();

  var allValues = [...sourceValues, ...targetValues];

  let targetRange = targetSheet.getRange(1,1,allValues.length,allValues[0].length);
  targetRange.setValues(allValues);
}
</code>```

Body:
at the moment I have a sheet that has a script that is time triggered, the script at the end of the day will copy sheets at the bottom of the target sheet, everytime I am trying to do targetSheet.getrange(1,1) + 1; it's not  converting range to int. can someone please help?

   function copyData() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let rowCount = sourceValues.length;
  let columnCount = sourceValues[0].length;

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  let lastrowCount = targetSheet.getLastRow() + 1;

  let targetRange = targetSheet.getRange(lastrowCount,1, rowCount,columnCount);

  targetRange.setValues(sourceValues);
}

Body:
Do you mean this?

function copyDataOnTop() {

  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = spreadSheet.getSheetByName('copiedPausingSheet');

  let sourceRange = sourceSheet.getDataRange();
  let sourceValues = sourceRange.getValues();

  let targetSheet = spreadSheet.getSheetByName('collectivePausingData');
  var targetValues = targetSheet.getDataRange().getValues();

  var allValues = [...sourceValues, ...targetValues];

  let targetRange = targetSheet.getRange(1,1,allValues.length,allValues[0].length);
  targetRange.setValues(allValues);
}


问:
Read a .gz file from Google Cloud storage via Python (Jupyter)
I'm trying to read a .gz file from Google Cloud storage via Python on Jupyter notebook.

I get error by the first code.

TypeError: can't concat str to bytes

```<code>from google.cloud import storage
import pandas as pd
from io import StringIO

client = storage.Client()
bucket = client.get_bucket("nttcomware")
blob = bucket.get_blob(f"test.csv.gz")
df = pd.read_csv(s, compression='gzip', float_precision="high")
df.head()
</code>```

I get second error by the second code.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

```<code>from google.cloud import storage
import pandas as pd
from io import StringIO

client = storage.Client()
bucket = client.get_bucket("nttcomware")
blob = bucket.get_blob(f"test.csv.gz")
bt = blob.download_as_string()
s = str(bt, "utf-8")
s = StringIO(s)
df = pd.read_csv(s, compression='gzip', float_precision="high")
df.head()
</code>```

Please suggest.

答:
This works for me for reading json.gz to a dataframe directly from GCS.

client = storage.Client()

def gcs_read_json_gz(gcs_filepath, nrows=None):

    # Validate input path
    if not gcs_filepath.startswith("gs://") or not gcs_filepath.endswith(".json.gz"):
        raise ValueError(F"Invalid path: {gcs_filepath}")

    # Get the bucket
    bucket_name = gcs_filepath.split("/")[2]
    bucket = client.get_bucket(bucket_name)

    # Get the blob object
    blob_name = "/".join(gcs_filepath.split("/")[3:])
    blob = bucket.get_blob(blob_name)

    # Convert blob into string and consider as BytesIO object. Still compressed by gzip
    data = io.BytesIO(blob.download_as_string())

    # Open gzip into csv
    with gzip.open(data) as gz:
        # Read compressed file as a file object
        file = gz.read()
        # Decode the byte type into string by utf-8
        blob_decompress = file.decode('utf-8')
        # StringIO object
        s = io.StringIO(blob_decompress)

    df = pd.read_json(s, precise_float="high", nrows=nrows, lines=True)

    return df
```

Body:
I'm trying to read a .gz file from Google Cloud storage via Python on Jupyter notebook.

I get error by the first code.

TypeError: can't concat str to bytes

from google.cloud import storage
import pandas as pd
from io import StringIO

client = storage.Client()
bucket = client.get_bucket("nttcomware")
blob = bucket.get_blob(f"test.csv.gz")
df = pd.read_csv(s, compression='gzip', float_precision="high")
df.head()

I get second error by the second code.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

from google.cloud import storage
import pandas as pd
from io import StringIO

client = storage.Client()
bucket = client.get_bucket("nttcomware")
blob = bucket.get_blob(f"test.csv.gz")
bt = blob.download_as_string()
s = str(bt, "utf-8")
s = StringIO(s)
df = pd.read_csv(s, compression='gzip', float_precision="high")
df.head()

Please suggest.


问:
Create menu using Map but to remove the { } and ", "
I have this menu created :

```<code>@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
HashMap<Integer, String> menu = new HashMap<>();

menu.put(1, "Show clients from banks" + "\n");
menu.put(2, "Create new bank" + "\n");
menu.put(3, """
        \t. "Choose a bank from where you want to see the clients:
             A. BNP
             B. ING
             C. KBC
        \s""");
System.out.println(menu);
</code>```

and I get the output bit as  you can see in the output down , there are some { } and ", "  that I do not want them, is there other way  by using HashMap to create  something similar ?

OUTPUT:

```<code>{1=Show clients from banks
, 2=Create new bank
, 3=    . "Choose a bank from where you want to see the clients:
     A. BNP
     B. ING
     C. KBC
 }
</code>```

Desired OUTPUT - as it will  be is i  will use  sout , but i must use   this instead HashMap<Integer, String> menu = new HashMap<>();:

```<code> 1=Show clients from banks
 2=Create new bank
 3= . "Choose a bank from where you want to see the clients:
     A. BNP
     B. ING
     C. KBC

</code>```

答:
You would need to override the toString() for HashMap, that's a bad way to do it.  Create your own printMenu() method to iterate yourself.  I'd also remove the new lines from your options.</p>
```<code>public void printMenu(Map<Integer, String> menu) {
    for (Entry<Integer, String> entry : menu) {
       System.out.println(String.format("%d) %s", entry.getKey(), entry.getValue()));
    }
}
</code>```

Body:
I have this menu created :

@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
HashMap<Integer, String> menu = new HashMap<>();

menu.put(1, "Show clients from banks" + "\n");
menu.put(2, "Create new bank" + "\n");
menu.put(3, """
        \t. "Choose a bank from where you want to see the clients:
             A. BNP
             B. ING
             C. KBC
        \s""");
System.out.println(menu);

and I get the output bit as  you can see in the output down , there are some { } and ", "  that I do not want them, is there other way  by using HashMap to create  something similar ?

OUTPUT:

{1=Show clients from banks
, 2=Create new bank
, 3=    . "Choose a bank from where you want to see the clients:
     A. BNP
     B. ING
     C. KBC
 }

Desired OUTPUT - as it will  be is i  will use  sout , but i must use   this instead HashMap<Integer, String> menu = new HashMap<>();:

 1=Show clients from banks
 2=Create new bank
 3= . "Choose a bank from where you want to see the clients:
     A. BNP
     B. ING
     C. KBC

Body:
You would need to override the toString() for HashMap, that's a bad way to do it.  Create your own printMenu() method to iterate yourself.  I'd also remove the new lines from your options.

public void printMenu(Map<Integer, String> menu) {
    for (Entry<Integer, String> entry : menu) {
       System.out.println(String.format("%d) %s", entry.getKey(), entry.getValue()));
    }
}


问:
Pandas DataFrame merging with aggregation
Let's create 2 dataframes, df1 and df2:

```<code>import pandas as pd
df1 = pd.DataFrame([["A", "A", "B", "B", "C"], ["a1", "a2", "b1", "b2", "c1"], [10, 10, 20, 20, 30], [1, 5, 6, 3, 4]]).T
df2 = pd.DataFrame([["B", "B", "C", "F"], ["b1", "b3", "c1", "f2"], [30, 30, 40, 40], [8, 3, 5, 2]]).T
df1.columns = df2.columns = ["label1", "label2", "total", "count"]
</code>```

Please notice, "total" must be the same for each "label1"

I need to merge theses 2 dataframes following these rules :

All "count" with same "label2" are simply added. ex: in df1, b1=6, in df2, b1=8, when merged, b1=14

"total" with same "label1" are added (and must be the same for each "label1"). ex: in df1, all B=20, in df2, all B=30, when merged, all B=50

In df3, this is what I'm trying to get:

I think I should maybe use pandas.DataFrame.merge, 1 or 2 times, but I don't even understand how to aggregate data. Any clue is appreciated.

答:
Try this:</p>
```<code>import pandas as pd
df1 = pd.DataFrame([["A", "A", "B", "B", "C"], ["a1", "a2", "b1", "b2", "c1"], [10, 10, 20, 20, 30], [1, 5, 6, 3, 4]]).T
df2 = pd.DataFrame([["B", "B", "C", "F"], ["b1", "b3", "c1", "f2"], [30, 30, 40, 40], [8, 3, 5, 2]]).T
df1.columns = df2.columns = ["label1", "label2", "total", "count"]

df_both = df1.assign(df=1).append(df2.assign(df=2))

df_lable1 = df_both.drop_duplicates(['label1', 'df']).groupby('label1')['total'].sum().reset_index()
df_lable2 = df_both.groupby('label2')['count'].sum().reset_index()

df3 = df_both[['label1', 'label2']].drop_duplicates(["label1", "label2"]).sort_values(["label1", "label2"])

df3 = df3.merge(df_lable1, on=['label1'], how='left')
df3 = df3.merge(df_lable2, on=['label2'], how='left')

#   label1 label2 total count
# 0      A     a1    10     1
# 1      A     a2    10     5
# 2      B     b1    50    14
# 3      B     b2    50     3
# 4      B     b3    50     3
# 5      C     c1    70     9
# 6      F     f2    40     2
</code>```

Body:
Let's create 2 dataframes, df1 and df2:

import pandas as pd
df1 = pd.DataFrame([["A", "A", "B", "B", "C"], ["a1", "a2", "b1", "b2", "c1"], [10, 10, 20, 20, 30], [1, 5, 6, 3, 4]]).T
df2 = pd.DataFrame([["B", "B", "C", "F"], ["b1", "b3", "c1", "f2"], [30, 30, 40, 40], [8, 3, 5, 2]]).T
df1.columns = df2.columns = ["label1", "label2", "total", "count"]

Please notice, "total" must be the same for each "label1"

I need to merge theses 2 dataframes following these rules :

All "count" with same "label2" are simply added. ex: in df1, b1=6, in df2, b1=8, when merged, b1=14

"total" with same "label1" are added (and must be the same for each "label1"). ex: in df1, all B=20, in df2, all B=30, when merged, all B=50

In df3, this is what I'm trying to get:

I think I should maybe use pandas.DataFrame.merge, 1 or 2 times, but I don't even understand how to aggregate data. Any clue is appreciated.

Body:
Try this:

import pandas as pd
df1 = pd.DataFrame([["A", "A", "B", "B", "C"], ["a1", "a2", "b1", "b2", "c1"], [10, 10, 20, 20, 30], [1, 5, 6, 3, 4]]).T
df2 = pd.DataFrame([["B", "B", "C", "F"], ["b1", "b3", "c1", "f2"], [30, 30, 40, 40], [8, 3, 5, 2]]).T
df1.columns = df2.columns = ["label1", "label2", "total", "count"]

df_both = df1.assign(df=1).append(df2.assign(df=2))

df_lable1 = df_both.drop_duplicates(['label1', 'df']).groupby('label1')['total'].sum().reset_index()
df_lable2 = df_both.groupby('label2')['count'].sum().reset_index()

df3 = df_both[['label1', 'label2']].drop_duplicates(["label1", "label2"]).sort_values(["label1", "label2"])

df3 = df3.merge(df_lable1, on=['label1'], how='left')
df3 = df3.merge(df_lable2, on=['label2'], how='left')

#   label1 label2 total count
# 0      A     a1    10     1
# 1      A     a2    10     5
# 2      B     b1    50    14
# 3      B     b2    50     3
# 4      B     b3    50     3
# 5      C     c1    70     9
# 6      F     f2    40     2


问:
asp.net core services.AddHttpClient - IHttpClientFactory vs HttpClient injection
I'm trying to understand something I've seen in some production code and when investigating it I found this page: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

The code I've seen is an ASP.NET Core Web App. It uses the AddHttpClient() extension:

```<code>services.AddHttpClient();
</code>```

According to the documentation this injects an IHttpClientFactory into the controllers. But the production code declares the constructors like so:

```<code>public SomeController(ILogger<SomeController> logger, HttpClient client) {...}
</code>```

I did some testing and this works too (with necessary adjustments of course):

```<code>public SomeController(ILogger<SomeController> logger, IHttpClientFactory factory) {...}
</code>```

According to the documentation an HttpClient is injected into typed clients. But doesn't that require me to specify the type by using

```<code>services.AddHttpClient<T>();
</code>```

?

I don't do that so is the type infered some way?

The IServiceCollection must do some magic based on what I choose to declare in the constructor. I cannot find any examples that use the combination of

```<code>services.AddHttpClient();
</code>```

and

```<code>public SomeController(HttpClient client){...}
</code>```

Can I find that documented somewhere?

答:
IHttpClientFactory has several consumption patterns of which typed clients is one among: named, generated or basic client.

What you are asking for (not registering a typed client, but resolving httpclient from DI) is possible but not recommended, so the usage patterns here don't show that. Also its not a "TypedClient" but a client reserved by type- this client itself doesnt change, just its 'stickiness' to the type that is using it. The redesign around the client factory is built around improper usage of clientfactory, from the doc you quoted:

However, the issue isn't really with HttpClient per se, but with the
default constructor for HttpClient, because it creates a new concrete
instance of HttpMessageHandler, which is the one that has sockets
exhaustion and DNS changes issues mentioned above.

this stack overflow question might help clarify further.

Regarding how DI actually works, Here is the code doing the registration, see how it adds a HttpClient and bits of code which would be called on resolution - How it reserves a client by type, name etc.

Body:
I'm trying to understand something I've seen in some production code and when investigating it I found this page: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

The code I've seen is an ASP.NET Core Web App. It uses the AddHttpClient() extension:

services.AddHttpClient();

According to the documentation this injects an IHttpClientFactory into the controllers. But the production code declares the constructors like so:

public SomeController(ILogger<SomeController> logger, HttpClient client) {...}

I did some testing and this works too (with necessary adjustments of course):

public SomeController(ILogger<SomeController> logger, IHttpClientFactory factory) {...}

According to the documentation an HttpClient is injected into typed clients. But doesn't that require me to specify the type by using

services.AddHttpClient<T>();

?

I don't do that so is the type infered some way?

The IServiceCollection must do some magic based on what I choose to declare in the constructor. I cannot find any examples that use the combination of

services.AddHttpClient();

and

public SomeController(HttpClient client){...}

Can I find that documented somewhere?


问:
What should you consider when scaling a set of databases that must synchronise data?
I have a MongoDB db and have just set up elasticsearch to handle full text search on subsets of that data (e.g. titles of pages, a bit like functionality on Wikipedia).

I have implemented this most likely naively, using Logstash to sync every 10 seconds (every 10s, the title field of any new documents is copied into elasticsearch index).

As of implementation, I found an article discussing other methods to sync the two databases, as well as reading one person implementing a python script to sync for them (this idea is appealing).

I was wondering whether anyone with experience in this area could let me know what methods are most scalable and what their preferred method has been so far.

Any advice is much appreciated!

答:
You should use a change stream to get a stream of all document changes then you can feed those documents into Elastic Search.

If you are hosted in Atlas we will build a full text index automatically using our built in Atlas Search tool (which is built on Lucene).


问:
How to get names of embedded audio resource in .Net application
I have added few audio wav files to my .net project. I want to get names of all the audio wav files within my .net application. My audio wav files are within resources.resx file which is internal to my project and will compile with it.</p>

答:
Following is my solution for playing embedded audio resource in .net application.</p>

```<code>            Dim mSound As String = "Bell"
            Dim strNameSpace As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString()
            Dim mRes As Resources.ResourceManager = New Resources.ResourceManager(strNameSpace & ".Resources", Assembly.GetExecutingAssembly)
            If mRes IsNot Nothing Then
                Dim mSoundStream As Stream = mRes.GetStream(mSound)
                If mSoundStream IsNot Nothing Then
                    Dim mPlayer As SoundPlayer = New SoundPlayer(mSoundStream)
                    mPlayer.Play()
                    mPlayer.Dispose()
                    mSoundStream.Close()
                    mSoundStream.Dispose()
                End If
            End If
</code>```

Body:
Following is my solution for playing embedded audio resource in .net application.

            Dim mSound As String = "Bell"
            Dim strNameSpace As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString()
            Dim mRes As Resources.ResourceManager = New Resources.ResourceManager(strNameSpace & ".Resources", Assembly.GetExecutingAssembly)
            If mRes IsNot Nothing Then
                Dim mSoundStream As Stream = mRes.GetStream(mSound)
                If mSoundStream IsNot Nothing Then
                    Dim mPlayer As SoundPlayer = New SoundPlayer(mSoundStream)
                    mPlayer.Play()
                    mPlayer.Dispose()
                    mSoundStream.Close()
                    mSoundStream.Dispose()
                End If
            End If


答:
Merge first then aggregate:</p>
```<code>cols = ['label1', 'label2']
prefix = lambda x: x.split('_')[0]

out = df1.merge(df2, on=cols, how='outer').set_index(cols) \
         .groupby(by=prefix, sort=False, axis=1).sum().reset_index()
print(out)

# Output
  label1 label2  total  count
0      A     a1     10      1
1      A     a2     10      5
2      B     b1     50     14
3      B     b2     20      3
4      C     c1     70      9
5      B     b3     30      3
6      F     f2     40      2
</code>```

Title: Pandas DataFrame merging with aggregation

Body:
Merge first then aggregate:

cols = ['label1', 'label2']
prefix = lambda x: x.split('_')[0]

out = df1.merge(df2, on=cols, how='outer').set_index(cols) \
         .groupby(by=prefix, sort=False, axis=1).sum().reset_index()
print(out)

# Output
  label1 label2  total  count
0      A     a1     10      1
1      A     a2     10      5
2      B     b1     50     14
3      B     b2     20      3
4      C     c1     70      9
5      B     b3     30      3
6      F     f2     40      2


问:
How to check Alamofire failure of bad internet connection?
How can i check if my Alamofire request Failed because of bad internet connection? I get an error but how can i know that it failed because of that

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x6000007fe6a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey={length = 28, capacity = 28, bytes = 0x1c1e1f96000000000000000000000000 ... 0000000100000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask .<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
      "LocalUploadTask .<1>"
  )

答:
You can check the failure reason through the underlyingError property from AFError as follows

```<code>Alamofire.request("url", method: .post, parameters: parameters)
.responseJSON { response in
  if let afError = response.error,
  let underlyingError = afError.underlyingError as? URLError {
    switch underlyingError.code {
    case URLError.notConnectedToInternet:
        // do your thing here
    default:
        // any other URLError code handling
  }
}
</code>```

Body:
You can check the failure reason through the underlyingError property from AFError as follows

Alamofire.request("url", method: .post, parameters: parameters)
.responseJSON { response in
  if let afError = response.error,
  let underlyingError = afError.underlyingError as? URLError {
    switch underlyingError.code {
    case URLError.notConnectedToInternet:
        // do your thing here
    default:
        // any other URLError code handling
  }
}


问:
reading input till EOF in java
In C++ if I wish to read input till the EOF I can do it in the following manner

```<code>while(scanf("%d",&n))
{
    A[i]=n;
    i++;
}
</code>```

I can then run this code as ./a.out < input.txt. What is the java equivalent of this code?

答: The eof() function is used to check if the End Of File (EOF) is reached. It returns 1 if EOF is reached or if the FileHandle is not open and undef in all other cases.</p>

Title: reading input till EOF in java

Body:
In C++ if I wish to read input till the EOF I can do it in the following manner

while(scanf("%d",&n))
{
    A[i]=n;
    i++;
}

I can then run this code as ./a.out < input.txt. What is the java equivalent of this code?