问:
"OSError: Starting path not found" when importing spotifycharts
I get the following error when importing spotifycharts:

OSError: Starting path not found
```
<p>When I do <code>pip freeze</code> it's listed.</p>
<p>Full error:</p>
```OSError                                   Traceback (most recent call last)
/var/folders/fm/ck9x_7l55y93t7gkxl93g_q40000gn/T/ipykernel_57786/3799758561.py in <module>
      1 import environs
----> 2 import spotifycharts as sc

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/__init__.py in <module>
      9 from tqdm import auto
     10
---> 11 from spotifycharts import classes
     12 from spotifycharts import settings
     13 from spotifycharts import exceptions

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/classes.py in <module>
     10
     11 import spotifycharts as sc
---> 12 from spotifycharts import settings
     13 from spotifycharts import exceptions
     14 from spotifycharts.logging import logger

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/settings.py in <module>
      1 import environs
      2 configuration = environs.Env()
----> 3 configuration.read_env('spotifycharts/configuration.env')
      4
      5

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/environs/__init__.py in read_env(path, recurse, verbose, override)
    413             if not start_dir:  # Only a filename was given
    414                 start_dir = os.getcwd()
--> 415             for dirname in _walk_to_root(start_dir):
    416                 check_path = Path(dirname) / env_name
    417                 if check_path.exists():

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/dotenv/main.py in _walk_to_root(path)
    244     """
    245     if not os.path.exists(path):
--> 246         raise IOError('Starting path not found')
    247
    248     if os.path.isfile(path):

OSError: Starting path not found
```

How do I solve this?

答:
Was able to find a workaround.

Open the settings.py file located in /opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/ in above case.

Add the full path to the read_env() method

Change

```<code>configuration.read_env('spotifycharts/configuration.env')
</code>```

to

```<code>configuration.read_env('/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/configuration.env')
</code>```

Body:
I get the following error when importing spotifycharts:

OSError: Starting path not found

When I do pip freeze it's listed.

Full error:

OSError                                   Traceback (most recent call last)
/var/folders/fm/ck9x_7l55y93t7gkxl93g_q40000gn/T/ipykernel_57786/3799758561.py in <module>
      1 import environs
----> 2 import spotifycharts as sc

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/__init__.py in <module>
      9 from tqdm import auto
     10
---> 11 from spotifycharts import classes
     12 from spotifycharts import settings
     13 from spotifycharts import exceptions

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/classes.py in <module>
     10
     11 import spotifycharts as sc
---> 12 from spotifycharts import settings
     13 from spotifycharts import exceptions
     14 from spotifycharts.logging import logger

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/settings.py in <module>
      1 import environs
      2 configuration = environs.Env()
----> 3 configuration.read_env('spotifycharts/configuration.env')
      4
      5

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/environs/__init__.py in read_env(path, recurse, verbose, override)
    413             if not start_dir:  # Only a filename was given
    414                 start_dir = os.getcwd()
--> 415             for dirname in _walk_to_root(start_dir):
    416                 check_path = Path(dirname) / env_name
    417                 if check_path.exists():

/opt/anaconda3/envs/python39/lib/python3.9/site-packages/dotenv/main.py in _walk_to_root(path)
    244     """
    245     if not os.path.exists(path):
--> 246         raise IOError('Starting path not found')
    247
    248     if os.path.isfile(path):

OSError: Starting path not found

How do I solve this?

Body:
Was able to find a workaround.

Open the settings.py file located in /opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/ in above case.

Add the full path to the read_env() method

Change

configuration.read_env('spotifycharts/configuration.env')

to

configuration.read_env('/opt/anaconda3/envs/python39/lib/python3.9/site-packages/spotifycharts/configuration.env')


来源: stackexchange

问:
Why isn't "mingw32-make.exe" working in a makefile
So I have these three files:

Linking.cpp:

```<code>#include "Liking.h"

int main()
{
    print();
}
</code>```

Liking.h (I missed the "h" in the names of the files and I'm afraid to change it and got some problems):

```<code>#pragma once

void print();
</code>```

liking2.cpp:

```<code>#include <iostream>
#include "Liking.h"
#include <string>

void print()
{
    std::string name;
    std::cout << "Insert your name: ";
    std::cin >> name;
    std::cout << "Your name is: " << name<< std::endl;
}
</code>```

Now my question is about using makefile in order to link these .cpp files so I made one and it is this:

```<code>Linking: Linking.o liking2.o
    g++ Linking.o liking2.o -o Linking

Linking.o: Linking.cpp
    g++ -c Linking.cpp

Linking.o: liking2.cpp
    g++ -c liking2.cpp

clean:
    rm *.o Linking
</code>```

But the problem comes (at least this is what I'm thinking I'm missing) when I try to use this beacuse I don't have any clues. The videos I've watched on youtube showed the "make" word but it doens't seem to work.  I've searched a lot and I found the "mingw32-make.exe" but when I open the make file in my Visual Studio code (By the way I'm also using windows) and use this command in the terminal I get this problem:

```<code>makefile:8: warning: overriding recipe for target 'Linking.o'
makefile:5: warning: ignoring old recipe for target 'Linking.o'
g++ -c liking2.cpp
g++ Linking.o liking2.o -o Linking
g++: error: Linking.o: No such file or directory
makefile:2: recipe for target 'Linking' failed
mingw32-make: *** [Linking] Error 1
</code>```

Now I know that this kind of question is asked a lot (I know because I've searched) but the  only three question I saw that could clarify had all problems so they didn't help me at all:

Makefile --mingw32-make.exe
mingw32-make.exe : *** missing separator. Stop
mingw32-make.exe: *** [All] Error 2 - Codelite

If you guys could at least put me on the right path about what I'm missing that would be really helpful

答:
Thanks to the explanations in the comments and also following their advice I'll post here the fixed code and I'll explain the differences:

```<code>Linking: Linking.o liking2.o
    g++ -o Linking Linking.o liking2.o

Linking.o: Linking.cpp
    g++ -c Linking.cpp

liking2.o: liking2.cpp
    g++ -c liking2.cpp

clean:
    rm *.o Linking
</code>```

Now taking the answer from the question: makefile error no such file or directory I changed the second line of code where I moved the -o Linking to the beginning and also, as it was pointed out in the comments, I did a mistake in the seventh line where I used two recipes to the same target, don't do this with your makefile as well. These changes that I did were enough to make the makefile work and I hope that this answer will be able to help other people as well in the future and thank you for all for the help.

ContentLicense: CC BY-SA 4.0

Body:
So I have these three files:

Linking.cpp:

#include "Liking.h"

int main()
{
    print();
}

Liking.h (I missed the "h" in the names of the files and I'm afraid to change it and got some problems):

#pragma once

void print();

liking2.cpp:

#include <iostream>
#include "Liking.h"
#include <string>

void print()
{
    std::string name;
    std::cout << "Insert your name: ";
    std::cin >> name;
    std::cout << "Your name is: " << name<< std::endl;
}

Now my question is about using makefile in order to link these .cpp files so I made one and it is this:

Linking: Linking.o liking2.o
    g++ Linking.o liking2.o -o Linking

Linking.o: Linking.cpp
    g++ -c Linking.cpp

Linking.o: liking2.cpp
    g++ -c liking2.cpp

clean:
    rm *.o Linking

But the problem comes (at least this is what I'm thinking I'm missing) when I try to use this beacuse I don't have any clues. The videos I've watched on youtube showed the "make" word but it doens't seem to work.  I've searched a lot and I found the "mingw32-make.exe" but when I open the make file in my Visual Studio code (By the way I'm also using windows) and use this command in the terminal I get this problem:

makefile:8: warning: overriding recipe for target 'Linking.o'
makefile:5: warning: ignoring old recipe for target 'Linking.o'
g++ -c liking2.cpp
g++ Linking.o liking2.o -o Linking
g++: error: Linking.o: No such file or directory
makefile:2: recipe for target 'Linking' failed
mingw32-make: *** [Linking] Error 1

Now I know that this kind of question is asked a lot (I know because I've searched) but the  only three question I saw that could clarify had all problems so they didn't help me at all:

Makefile --mingw32-make.exe
mingw32-make.exe : *** missing separator. Stop
mingw32-make.exe: *** [All] Error 2 - Codelite

If you guys could at least put me on the right path about what I'm missing that would be really helpful

Body:
Thanks to the explanations in the comments and also following their advice I'll post here the fixed code and I'll explain the differences:

Linking: Linking.o liking2.o
    g++ -o Linking Linking.o liking2.o

Linking.o: Linking.cpp
    g++ -c Linking.cpp

liking2.o: liking2.cpp
    g++ -c liking2.cpp

clean:
    rm *.o Linking

Now taking the answer from the question: makefile error no such file or directory I changed the second line of code where I moved the -o Linking to the beginning and also, as it was pointed out in the comments, I did a mistake in the seventh line where I used two recipes to the same target, don't do this with your makefile as well. These changes that I did were enough to make the makefile work and I hope that this answer will be able to help other people as well in the future and thank you for all for the help.


问:
Can't run Python 2.7 from powershell [Windows 10]
What I have tried/done so far -

I used the "Windowsx86-64 MSI Installer (2.7.0) from this link

Added environment variables by going to system properties and clicking "Environment Variables..." button. Then I click on the "Path" variable under user variables and click "edit". I then add in the path "C:/Python27" which I can confirm is where python.exe is located.

I've also tried setting the path using these commands

$env:path="$env:Path;C:\Python27"

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";C:\Python27", "Machine")

I don't really know what those commands do, but I found them in other SO threads.
I've restarted powershell, I've ran it as admin. I restarted my PC. And I am out of ideas.

EDIT - I get Python 2 is no longer supported. If I could use a newer version I would, but I can't. Still, there is no reason powershell shouldn't be able to work with python scripts.

EDIT2

```<code>PS C:\windows\system32> (Get-Command python).Source
C:\Users\BestInTOWN\AppData\Local\Microsoft\WindowsApps\python.exe
PS C:\windows\system32> [Environment]::GetEnvironmentVariable('Path',
'User') C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Users\BestInTOWN\AppData\Local\Microsoft\WindowsApps;C:\Users\BestInTOWN\AppData\Local\Programs\Microsoft VS Code\bin;C:\Python27;
</code>```

Edit3/Answer
Went to settings and searched for "Manage App Execution Aliases". Then proceeded to turn off App Installer for python.exe and python3.exe.

答:
Already put this in the post but I'll add an official answer response as well.

So I went to settings and searched for "Manage App Execution Aliases". Then proceeded to turn off App Installer for python.exe and python3.exe.

Now Python 2.7 shows up when I type python --version in the powershell. And Python scripts work when I run them from powershell

Body:
What I have tried/done so far -

I used the "Windowsx86-64 MSI Installer (2.7.0) from this link

Added environment variables by going to system properties and clicking "Environment Variables..." button. Then I click on the "Path" variable under user variables and click "edit". I then add in the path "C:/Python27" which I can confirm is where python.exe is located.

I've also tried setting the path using these commands

$env:path="$env:Path;C:\Python27"

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";C:\Python27", "Machine")

I don't really know what those commands do, but I found them in other SO threads.
I've restarted powershell, I've ran it as admin. I restarted my PC. And I am out of ideas.

EDIT - I get Python 2 is no longer supported. If I could use a newer version I would, but I can't. Still, there is no reason powershell shouldn't be able to work with python scripts.

EDIT2

PS C:\windows\system32> (Get-Command python).Source
C:\Users\BestInTOWN\AppData\Local\Microsoft\WindowsApps\python.exe
PS C:\windows\system32> [Environment]::GetEnvironmentVariable('Path',
'User') C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Users\BestInTOWN\AppData\Local\Microsoft\WindowsApps;C:\Users\BestInTOWN\AppData\Local\Programs\Microsoft VS Code\bin;C:\Python27;

Edit3/Answer
Went to settings and searched for "Manage App Execution Aliases". Then proceeded to turn off App Installer for python.exe and python3.exe.


问:
If I am creating a simple client server application in IntelliJ, how should this work?
When creating a client server application (serversocket), would I create 2 seperate projects or can I do this in a single project?

I'm a little confused as to what type of project this will be, and more confused as to how I can launch both the client and server.

Or would I have to manually fire up terminal and execute the jars?

This will be a serversock and a client that connects to it and sends simple messages.

答:
Yes you can do it in a single project. The easiest way is to create a separate thread for your serverSocket, and start it in the main method of your app wich will initiate and start the server socket first.</p>
```<code>public static void main (String[] args) {
   // CREATE AN OBJECT OF SERVER CLASS WHICH EXTENDS THREAD AND START IT.

   Server serv = New Server ();
   Serv.start ();

   Socket soc = Socket("localhost", 2000);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Yes you can do it in a single project. The easiest way is to create a separate thread for your serverSocket, and start it in the main method of your app wich will initiate and start the server socket first.

public static void main (String[] args) {
   // CREATE AN OBJECT OF SERVER CLASS WHICH EXTENDS THREAD AND START IT.

   Server serv = New Server ();
   Serv.start ();

   Socket soc = Socket("localhost", 2000);
}


问:
ResourceSet not loading items in subfolders of subfolders
I am using the typical code to load an assembly and retrieve its resources.  It finds all the resources that are in top level subfolders (e.g., "component/Images") but if I put resources such as images into subfolders of those (e.g., component/Images/MenuIcons") then none of those resources end up in the collection.  I've checked the application.g.resources file and they are in there.  I've tried two ways of scanning the resources:

```<code>System.Globalization.CultureInfo culture = Thread.CurrentThread.CurrentCulture;
string resourceName = asm.GetName().Name + ".g";
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(resourceName, asm);
System.Resources.ResourceSet resourceSet = rm.GetResourceSet(culture, true, true);
List<string> resources = new List<string>();
foreach (DictionaryEntry resource in resourceSet)
    resources.Add((string)resource.Key);
rm.ReleaseAllResources();
return resources;
</code>```

And also:

```<code>foreach (string name in assembly.GetManifestResourceNames())
{
    using (Stream stream = assembly.GetManifestResourceStream(name))
    {
            using (IResourceReader reader = new ResourceReader(stream))
            {
                foreach (DictionaryEntry entry in reader)
                {
                     // Add resource here
                }
            }
        }
    }
}
</code>```

Both methods produce an identical result, but neither one includes any of the resources in subfolders of subfolders.  Anyone know how I can get a list of those?  They work just fine when referenced with pack: URIs.

答: Maybe your resources are not copied to the bin directory on Build? Check the build Action and Copy To Output Directory properties of those files.</p>

Body:
I am using the typical code to load an assembly and retrieve its resources.  It finds all the resources that are in top level subfolders (e.g., "component/Images") but if I put resources such as images into subfolders of those (e.g., component/Images/MenuIcons") then none of those resources end up in the collection.  I've checked the application.g.resources file and they are in there.  I've tried two ways of scanning the resources:

System.Globalization.CultureInfo culture = Thread.CurrentThread.CurrentCulture;
string resourceName = asm.GetName().Name + ".g";
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(resourceName, asm);
System.Resources.ResourceSet resourceSet = rm.GetResourceSet(culture, true, true);
List<string> resources = new List<string>();
foreach (DictionaryEntry resource in resourceSet)
    resources.Add((string)resource.Key);
rm.ReleaseAllResources();
return resources;

And also:

foreach (string name in assembly.GetManifestResourceNames())
{
    using (Stream stream = assembly.GetManifestResourceStream(name))
    {
            using (IResourceReader reader = new ResourceReader(stream))
            {
                foreach (DictionaryEntry entry in reader)
                {
                     // Add resource here
                }
            }
        }
    }
}

Both methods produce an identical result, but neither one includes any of the resources in subfolders of subfolders.  Anyone know how I can get a list of those?  They work just fine when referenced with pack: URIs.


问:
Infer module name from type
Say I have the following code:

import { createConnection } from "mysql";

const connection = createConnection({
  host: "localhost",
  user: "admin",
  database: "project",
  password: "mypassword", // sensitive
  multipleStatements: true,
});
```

Acording to Using the Compiler API, one can use a TypeChecker to infer the type of e.g. createConnection (In this case, that would be "Connection").

What I am interrested in knowing is whether the TypeChecker can tell us the module name of the file where it gets it's type ("mysql" as defined in line 1).

I can infer the filename using:

typeProgram?.checker.getTypeAtLocation(node).type.symbol.valueDeclaration.parent.fileName

Which in this case would return:

"/Users/USERNAME/git/eslint-plugin-security-rules/node_modules/@types/mysql/index.d.ts"

From here, I can traverse the filename to get the module name and this is currently my best solution as to how to approach the problem. However, I would love to know if there's a function or variable that I am overlooking?

答:
You could do:

```<code>const symbol = checker.getTypeAtLocation(node).symbol;

// "mysql".createConnection
typeChecker.getFullyQualifiedName(symbol);
</code>```

Or if you don't mind depending on internal API:

```<code>// "mysql"
(symbol as any).parent?.escapedName;
</code>```

Or using your other method:

```<code>// an actual implementation would need to be more robust than this
const decl = symbol.getDeclarations()![0];
const module = decl.parent.parent as ts.ModuleDeclaration;
console.log(module.name.getText());
</code>```

Title: Infer module name from type

Body:
Say I have the following code:

import { createConnection } from "mysql";

const connection = createConnection({
  host: "localhost",
  user: "admin",
  database: "project",
  password: "mypassword", // sensitive
  multipleStatements: true,
});

Acording to Using the Compiler API, one can use a TypeChecker to infer the type of e.g. createConnection (In this case, that would be "Connection").

What I am interrested in knowing is whether the TypeChecker can tell us the module name of the file where it gets it's type ("mysql" as defined in line 1).

I can infer the filename using:

typeProgram?.checker.getTypeAtLocation(node).type.symbol.valueDeclaration.parent.fileName

Which in this case would return:

"/Users/USERNAME/git/eslint-plugin-security-rules/node_modules/@types/mysql/index.d.ts"

From here, I can traverse the filename to get the module name and this is currently my best solution as to how to approach the problem. However, I would love to know if there's a function or variable that I am overlooking?

Body:
You could do:

const symbol = checker.getTypeAtLocation(node).symbol;

// "mysql".createConnection
typeChecker.getFullyQualifiedName(symbol);

Or if you don't mind depending on internal API:

// "mysql"
(symbol as any).parent?.escapedName;

Or using your other method:

// an actual implementation would need to be more robust than this
const decl = symbol.getDeclarations()![0];
const module = decl.parent.parent as ts.ModuleDeclaration;
console.log(module.name.getText());


问:
Prometheus cannot scrape from spring-boot application over HTTPS
I'm deploying a spring-boot application and prometheus container through docker, and have exposed the spring-boot /actuator/prometheus endpoint successfully. However, when I enable prometheus debug logs, I can see it fails to scrape the metrics:

```<code>ts=2022-02-02T03:54:46.210Z
caller=scrape.go:1292
level=debug
component="scrape manager"
scrape_pool=spring-actuator
target=https://127.0.0.1:8443/actuator/prometheus/
msg="Scrape failed"
err="Get \"https://127.0.0.1:8443/actuator/prometheus/\": dial tcp 127.0.0.1:8443: connect: connection refused"
</code>```

I'm thinking it's something to do with how I've set up my spring-boot HTTPS. I am generating a self-signed certificate during the building of my spring-boot application, using the command:

```<code>keytool
  -genkey
  -alias <alias>
  -dname <dname>
  -keyalg RSA
  -keysize 4096
  -storetype PKCS12
  -keystore <path_to_keystore>
  -validity 3650
  -storepass <keystore_pass>
</code>```

I then export the cert to a .pem file, and extract the .crt and .key:

```<code>openssl pkcs12 -in cert.p12 -out cert.pem -nodes -passin pass:<pass>
</code>```

This is mounted through a shared volume to my prometheus container, which has a --web.config.file containing:

```<code>tls_server_config:
  cert_file: /path/to/cert.crt
  key_file: /path/to/cert.key
</code>```

And for good measure I added insecure_skip_verify: true to the prometheus.yml config:

```<code>- job_name: 'spring-actuator'
metrics_path: '/actuator/prometheus/'
scrape_interval: 60s
scheme: https
static_configs:
  - targets: [ '127.0.0.1:8443' ]
tls_config:
  insecure_skip_verify: true
</code>```

答:
Below is the critical part to debug the issue

```<code>target=https://127.0.0.1:8443/actuator/prometheus/
msg="Scrape failed"
err="Get \"https://127.0.0.1:8443/actuator/prometheus/\": dial tcp 127.0.0.1:8443: connect: connection refused"
</code>```

It states that scrape has failed as it unable to connect to the target server. As the target server 127.0.0.1:8443 then it is expected to be in the same host where Prometheus is running.

Prometheus retrieval job, also called the scraper, pulls data from target services, aggregates it, and passes it to the database. Prometheus takes a list of scraping targets (IP addresses and ports) from a static list (or a file) called static_configs present in Prometheus YAML-based configuration file. More complex dynamic environments, where new instances might be brought up at any time, use service discovery mechanisms, which provide a list of machines to monitor and presents information of how these machines are organized.

When Prometheus scrapes a target, it attaches some labels automatically to the scraped time series which serve to identify the scraped target.

```<code>up{job="<job-name>", instance="<instance-id>"}: 1 if the instance is healthy, i.e. reachable, or 0 if the scrape failed.
</code>```

job: The configured job name that the target belongs

instance: The : part of the target's URL that was scraped.

Configuring Prometheus instances

When Prometheus is running in localhost or same host.

```<code>scrape_configs:
- job_name: node
  static_configs:
  - targets: ['localhost:9100']
</code>```

When Prometheus is running in different environment or host

```<code>scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]
  - job_name: eventservice
    static_configs:
      - targets: ["events:9090"]
  - job_name: bookingservice
    static_configs:
      - targets: ["bookings:9090"]
</code>```

When running in multiple ports using IPs

```<code>static_configs:
  - targets: ['192.168.1.117:':8080', '192.168.1.117:8081']
</code>```

TLS Config

TLS is used for establishing a secure, private transport between the Prometheus instance and scrape targets. By default, the Prometheus instance attempts to verify the certificate exposed by the scrape targets against its trust store, for establishing authenticity of the scrape targets.

```<code>scrape_configs:
  - job_name: 'node'
    scheme: https
    tls_config:
        # Prometheus will check that the node_exporter presents a certificate
        # signed by this ca.
        ca_file: 'ca.crt'
        # The cert and key are presented to node_exporter to authenticate
        # Prometheus as a client.
        cert_file: 'client.crt'
        key_file: 'client.key'

    static_configs:
    - targets: ['myserver.net:443']
</code>```

Body:
I'm deploying a spring-boot application and prometheus container through docker, and have exposed the spring-boot /actuator/prometheus endpoint successfully. However, when I enable prometheus debug logs, I can see it fails to scrape the metrics:

ts=2022-02-02T03:54:46.210Z
caller=scrape.go:1292
level=debug
component="scrape manager"
scrape_pool=spring-actuator
target=https://127.0.0.1:8443/actuator/prometheus/
msg="Scrape failed"
err="Get \"https://127.0.0.1:8443/actuator/prometheus/\": dial tcp 127.0.0.1:8443: connect: connection refused"

I'm thinking it's something to do with how I've set up my spring-boot HTTPS. I am generating a self-signed certificate during the building of my spring-boot application, using the command:

keytool
  -genkey
  -alias <alias>
  -dname <dname>
  -keyalg RSA
  -keysize 4096
  -storetype PKCS12
  -keystore <path_to_keystore>
  -validity 3650
  -storepass <keystore_pass>

I then export the cert to a .pem file, and extract the .crt and .key:

openssl pkcs12 -in cert.p12 -out cert.pem -nodes -passin pass:<pass>

This is mounted through a shared volume to my prometheus container, which has a --web.config.file containing:

tls_server_config:
  cert_file: /path/to/cert.crt
  key_file: /path/to/cert.key

And for good measure I added insecure_skip_verify: true to the prometheus.yml config:

- job_name: 'spring-actuator'
metrics_path: '/actuator/prometheus/'
scrape_interval: 60s
scheme: https
static_configs:
  - targets: [ '127.0.0.1:8443' ]
tls_config:
  insecure_skip_verify: true

Body:
Below is the critical part to debug the issue

target=https://127.0.0.1:8443/actuator/prometheus/
msg="Scrape failed"
err="Get \"https://127.0.0.1:8443/actuator/prometheus/\": dial tcp 127.0.0.1:8443: connect: connection refused"

It states that scrape has failed as it unable to connect to the target server. As the target server 127.0.0.1:8443 then it is expected to be in the same host where Prometheus is running.

Prometheus retrieval job, also called the scraper, pulls data from target services, aggregates it, and passes it to the database. Prometheus takes a list of scraping targets (IP addresses and ports) from a static list (or a file) called static_configs present in Prometheus YAML-based configuration file. More complex dynamic environments, where new instances might be brought up at any time, use service discovery mechanisms, which provide a list of machines to monitor and presents information of how these machines are organized.

When Prometheus scrapes a target, it attaches some labels automatically to the scraped time series which serve to identify the scraped target.

up{job="<job-name>", instance="<instance-id>"}: 1 if the instance is healthy, i.e. reachable, or 0 if the scrape failed.

job: The configured job name that the target belongs

instance: The : part of the target's URL that was scraped.

Configuring Prometheus instances

When Prometheus is running in localhost or same host.

scrape_configs:
- job_name: node
  static_configs:
  - targets: ['localhost:9100']

When Prometheus is running in different environment or host

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]
  - job_name: eventservice
    static_configs:
      - targets: ["events:9090"]
  - job_name: bookingservice
    static_configs:
      - targets: ["bookings:9090"]

When running in multiple ports using IPs

static_configs:
  - targets: ['192.168.1.117:':8080', '192.168.1.117:8081']

TLS Config

TLS is used for establishing a secure, private transport between the Prometheus instance and scrape targets. By default, the Prometheus instance attempts to verify the certificate exposed by the scrape targets against its trust store, for establishing authenticity of the scrape targets.

scrape_configs:
  - job_name: 'node'
    scheme: https
    tls_config:
        # Prometheus will check that the node_exporter presents a certificate
        # signed by this ca.
        ca_file: 'ca.crt'
        # The cert and key are presented to node_exporter to authenticate
        # Prometheus as a client.
        cert_file: 'client.crt'
        key_file: 'client.key'

    static_configs:
    - targets: ['myserver.net:443']


问:
Paste Pictures and Organize
I have the following code, which sorts some pictures down according to a value in Sheet1. Horizontally the images are aligned in the required columns. But not in the Rows.

I tried to do it with another FOR loop that I called J but doesn't work, it puts the images on top of each other.

How can I align the pictures in a column and a row that I choose?

What am I doing wrong? or what am I missing?

Thank you.

-------------CODE-------------

```<code>Sub CommandButton2_Click()

Dim firma_pic As Picture
Dim pic_location As String
Dim identifier_pic As String

'For j = 14 To 23
'Next
'Worksheets("Sheet3").Cells(14, 23).Select

For i = 2 To 11
identifier_pic = Worksheets("Sheet1").Cells(i, 11).Value
pic_location = "C:\Users\User\Downloads\Docs\img\" & Worksheets("Sheet1").Cells(i, 2).Value & ".png"

With Worksheets("Sheet3").Cells(i, 24)

Set firma_pic = ActiveSheet.Pictures.Insert(pic_location)
    firma_pic.Top = .Top
    firma_pic.Left = .Left
    firma_pic.ShapeRange.LockAspectRatio = msoFalse
    firma_pic.Placement = xlMoveAndSize
    firma_pic.ShapeRange.Width = 70
    firma_pic.ShapeRange.Height = 30
End With

Next
Worksheets("Sheet3").Cells(i, 23).Select

End Sub
</code>```

答:
Width and Height need to consider your cell too. You may resize images and force them to be W=70 and H=30 where the cell begins, but it could lead to images overlapping between columns. I'd suggest you to stick to the same workflow as you did for Top and Left</p>
```<code>firma_pic.ShapeRange.Width = .Width
firma_pic.ShapeRange.Height = .Height
</code>```

Title: Paste Pictures and Organize

Body:
I have the following code, which sorts some pictures down according to a value in Sheet1. Horizontally the images are aligned in the required columns. But not in the Rows.

I tried to do it with another FOR loop that I called J but doesn't work, it puts the images on top of each other.

How can I align the pictures in a column and a row that I choose?

What am I doing wrong? or what am I missing?

Thank you.

-------------CODE-------------

Sub CommandButton2_Click()

Dim firma_pic As Picture
Dim pic_location As String
Dim identifier_pic As String

'For j = 14 To 23
'Next
'Worksheets("Sheet3").Cells(14, 23).Select

For i = 2 To 11
identifier_pic = Worksheets("Sheet1").Cells(i, 11).Value
pic_location = "C:\Users\User\Downloads\Docs\img\" & Worksheets("Sheet1").Cells(i, 2).Value & ".png"

With Worksheets("Sheet3").Cells(i, 24)

Set firma_pic = ActiveSheet.Pictures.Insert(pic_location)
    firma_pic.Top = .Top
    firma_pic.Left = .Left
    firma_pic.ShapeRange.LockAspectRatio = msoFalse
    firma_pic.Placement = xlMoveAndSize
    firma_pic.ShapeRange.Width = 70
    firma_pic.ShapeRange.Height = 30
End With

Next
Worksheets("Sheet3").Cells(i, 23).Select

End Sub

Body:
Width and Height need to consider your cell too. You may resize images and force them to be W=70 and H=30 where the cell begins, but it could lead to images overlapping between columns. I'd suggest you to stick to the same workflow as you did for Top and Left

firma_pic.ShapeRange.Width = .Width
firma_pic.ShapeRange.Height = .Height


问:
How to get current route name in react-navigation?
I want the name of the current route or screen in react-navigation which I want to use inside if condition to make some changes.</p>

答:
If you are using React Navigation v6 you can use this:

```<code>import { useRoute } from '@react-navigation/native';
...
const route = useRoute();

console.log('Current Route: ', route.name);
</code>```

And if you want to get the name of the screen that you are, and you are inside a nested navigator, you can do this:

```<code>import { useNavigationState } from '@react-navigation/native';
...
const routes = useNavigationState(state => state.routes);

const currentRouteIndex =
  routes?.length && routes[routes.length - 1].state?.index;
const currentRoute =
  routes[routes.length - 1].state?.routeNames[currentRouteIndex];

console.log('Current Route: ', currentRoute);
</code>```

Body:
If you are using React Navigation v6 you can use this:

import { useRoute } from '@react-navigation/native';
...
const route = useRoute();

console.log('Current Route: ', route.name);

And if you want to get the name of the screen that you are, and you are inside a nested navigator, you can do this:

import { useNavigationState } from '@react-navigation/native';
...
const routes = useNavigationState(state => state.routes);

const currentRouteIndex =
  routes?.length && routes[routes.length - 1].state?.index;
const currentRoute =
  routes[routes.length - 1].state?.routeNames[currentRouteIndex];

console.log('Current Route: ', currentRoute);


问:
How to Save Test Results in Postman
I have an API Collection in Postman, and I have saved a few examples for each request.

When I try to save the Test Results though, only the JavaScript code is saved in the examples, and not the actual results (same goes for when exporting the whole API Collection).

Is there any other way I can do this to export the Test Results too?

答: as far as I know, you can't save test results but you can run test collection on Newman and save the result</p>

Title: How to Save Test Results in Postman


问:
how to flush the ZipOutputStream periodically in java
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

```<code>try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}
</code>```

```<code>public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}
</code>```

答:
Another thing...you are performing your close inside your try catch block. This leaves the chance for the stream to stay open on your files if you have an exception, as well as NOT giving the stream the chance to flush to the disk.

Always make sure your close is in a finally block (at least until you can get Java 7 with its try-with-resources block)

```<code>//build the byte buffer for transferring the data from the file
//to the zip.
final int BUFFER = 2048;
byte [] data = new byte[BUFFER];

File zipFile= new File("C\:\\myZip.zip");

BufferedInputStream in = null;
ZipOutputStream zipOut = null;

try {
  //create the out stream to send the file to and zip it.
  //we want it buffered as that is more efficient.
  FileOutputStream destination = new FileOutputStream(zipFile);
  zipOut = new ZipOutputStream(new BufferedOutputStream(destination));
  zipOut.setMethod(ZipOutputStream.DEFLATED);

  //create the input stream (buffered) to read in the file so we
  //can write it to the zip.
  in = new BufferedInputStream(new FileInputStream(fileToZip), BUFFER);

  //now "add" the file to the zip (in object speak only).
  ZipEntry zipEntry = new ZipEntry(fileName);
  zipOut.putNextEntry(zipEntry);

  //now actually read from the file and write the file to the zip.
  int count;
  while((count = in.read(data, 0, BUFFER)) != -1) {
zipOut.write(data, 0, count);
  }
}
catch (FileNotFoundException e) {
  throw e;
}
catch (IOException e) {
  throw e;
}
finally {
 //whether we succeed or not, close the streams.
 if(in != null) {
try {
  in.close();
}
catch (IOException e) {
  //note and do nothing.
      e.printStackTrace();
}
 }
 if(zipOut != null) {
try {
      zipOut.close();
}
catch (IOException e) {
      //note and do nothing.
      e.printStackTrace();
    }
 }
}
</code>```

Now if you need to loop, you can just loop around the part that you need to add more files to. Perhaps pass in an array of files and loop over it. This code worked for me zipping a file up.

Body:
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}

public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}

Body:
Another thing...you are performing your close inside your try catch block. This leaves the chance for the stream to stay open on your files if you have an exception, as well as NOT giving the stream the chance to flush to the disk.

Always make sure your close is in a finally block (at least until you can get Java 7 with its try-with-resources block)

//build the byte buffer for transferring the data from the file
//to the zip.
final int BUFFER = 2048;
byte [] data = new byte[BUFFER];

File zipFile= new File("C\:\\myZip.zip");

BufferedInputStream in = null;
ZipOutputStream zipOut = null;

try {
  //create the out stream to send the file to and zip it.
  //we want it buffered as that is more efficient.
  FileOutputStream destination = new FileOutputStream(zipFile);
  zipOut = new ZipOutputStream(new BufferedOutputStream(destination));
  zipOut.setMethod(ZipOutputStream.DEFLATED);

  //create the input stream (buffered) to read in the file so we
  //can write it to the zip.
  in = new BufferedInputStream(new FileInputStream(fileToZip), BUFFER);

  //now "add" the file to the zip (in object speak only).
  ZipEntry zipEntry = new ZipEntry(fileName);
  zipOut.putNextEntry(zipEntry);

  //now actually read from the file and write the file to the zip.
  int count;
  while((count = in.read(data, 0, BUFFER)) != -1) {
zipOut.write(data, 0, count);
  }
}
catch (FileNotFoundException e) {
  throw e;
}
catch (IOException e) {
  throw e;
}
finally {
 //whether we succeed or not, close the streams.
 if(in != null) {
try {
  in.close();
}
catch (IOException e) {
  //note and do nothing.
      e.printStackTrace();
}
 }
 if(zipOut != null) {
try {
      zipOut.close();
}
catch (IOException e) {
      //note and do nothing.
      e.printStackTrace();
    }
 }
}

Now if you need to loop, you can just loop around the part that you need to add more files to. Perhaps pass in an array of files and loop over it. This code worked for me zipping a file up.


问:
Visual Studio Data Tools - Build Error - SQL71561 xxx contains an unresolved reference to an object. Either the object does not exist
On attempting to build a database project, I am getting the following errors for the view below.

```<code>create view [schema].[test]
as
select distinct
    [ai].[account_id] as [service_account]
from
    [linkedserver].[database].[dbo].[view_name] ai
where
    stage = 'start'
and
    srn not in (
    select distinct
        [ai].[account_id]
    from
        [linkedserver].[database].[dbo].[view_name] ai
    where stage = 'progressing'
    )
</code>```

SQL71561: Computed column [schema].[test].[service_account] contains
and unresolved reference to an object. Either the object does not
exist or hte reference is ambigious becuase it could refer to any of
the following objects.
[linkedserver].[database].[dbo].[view_name].[account_id] or
[linkedserver].[database].[dbo].[view_name].[ai]::[account_id]

I was wondering if anyone has experienced similar errors with Visual Studio 2019 Data Tools

From the research I have done, some others have imported a database reference for the project, but that appears to be for a different type of error.

答: I have addressed issue by clear out the "Database variable" field while adding the "Database Reference" would allow 3 parts qualified name.

Body:
On attempting to build a database project, I am getting the following errors for the view below.

create view [schema].[test]
as
select distinct
    [ai].[account_id] as [service_account]
from
    [linkedserver].[database].[dbo].[view_name] ai
where
    stage = 'start'
and
    srn not in (
    select distinct
        [ai].[account_id]
    from
        [linkedserver].[database].[dbo].[view_name] ai
    where stage = 'progressing'
    )

SQL71561: Computed column [schema].[test].[service_account] contains
and unresolved reference to an object. Either the object does not
exist or hte reference is ambigious becuase it could refer to any of
the following objects.
[linkedserver].[database].[dbo].[view_name].[account_id] or
[linkedserver].[database].[dbo].[view_name].[ai]::[account_id]

I was wondering if anyone has experienced similar errors with Visual Studio 2019 Data Tools

From the research I have done, some others have imported a database reference for the project, but that appears to be for a different type of error.


问:
Yasg schema generation for nested serializer shows incorrect requests/responses
I have a Django API and I try to create the documentation with drf-yasg. I'm having trouble with the automatically generated schema for my nested serializer and ListAPIview. It looks like this:

serializers.py

```<code>class SlideDataSerializer(serializers.ModelSerializer):
    description = SlideDataDescriptionSerializer(many=True, read_only=True, source='slidedatadescription_set')
    class Meta:
        model = SlideData
        fields = ['catch', 'title', 'description', 'icon']

class SlideSerializer(serializers.ModelSerializer):
    datas = SlideDataSerializer(many=True, read_only=True, source='slidedata_set')
    class Meta:
        model = Slide
        fields = ['datas']

class PlanDataDescriptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = PlanDataDescription
        fields = ['description']

class PlanDataSerializer(serializers.ModelSerializer):
    description = PlanDataDescriptionSerializer(many=True, read_only=True, source='plandatadescription_set')
    class Meta:
        model = PlanData
        fields = ['stripColor', 'name', 'description', 'pricePerMonth', 'currency', 'picture']

class PlanSerializer(serializers.ModelSerializer):
    datas = PlanDataSerializer(many=True, read_only=True, source='plandata_set')
    class Meta:
        model = Plan
        fields = ['mainTitle', 'datas']
</code>```

views.py

```<code>class ProjectList(generics.ListAPIView):
    permission_classes = [permissions.AllowAny]
    serializer_class_slide = SlideSerializer
    serializer_class_plan = PlanSerializer

    def get_queryset_object(self, Table, campaign, lang):
        queryset = Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang)
        return queryset[0]

    def list(self, request):
        Tables = [Slide,
                Plan]

        campaign = self.request.query_params.get('campaign') or "default"
        lang = self.request.query_params.get('lang') or "en"

        if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables):
            campaign = "default"

        if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables):
            lang = "en"

        slides = self.serializer_class_slide(self.get_queryset_object(Slide, campaign, lang))
        plans = self.serializer_class_plan(self.get_queryset_object(Plan, campaign, lang))

        return Response({
            "slides": slides.data,
            "plans": plans.data,
        })
</code>```

and the urls.py:

```<code>openapi_info = openapi.Info(
        title="Projectname",
        default_version="v1",
        description="Endpoints",
        terms_of_service="TBD",
        contact=openapi.Contact(email="abc@123.com"),
        license=openapi.License(name="BSD License"),
    )

schema_view = get_schema_view(
    openapi_info,
    public=True,
    permission_classes=(permissions.AllowAny,),
)

API_VERSION = 'v1'
urlpatterns = [
    path('swagger/', schema_view.with_ui(
        'swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('swagger/api.json', schema_view.without_ui( cache_timeout=0), name='schema-swagger-json'),
]
</code>```

The endpoint is working fine but swagger does not create the right requests or responses and when I access it it gives me this error message:

```<code>view's ProjectList raised exception during schema generation; use `getattr(self, 'swagger_fake_view', False)` to detect and short-circuit this
Traceback (most recent call last):
  File "/home/projects/env/lib/python3.8/site-packages/drf_yasg/inspectors/base.py", line 42, in call_view_method
    return view_method()
  File "/home/projects/env/lib/python3.8/site-packages/rest_framework/generics.py", line 108, in get_serializer
    serializer_class = self.get_serializer_class()
  File "/home/projects/env/lib/python3.8/site-packages/rest_framework/generics.py", line 122, in get_serializer_class
    assert self.serializer_class is not None, (
AssertionError: 'ProjectList' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method.
</code>```

I can not include a serializer class name because I use multiple serializers, I can not create a single serializer for this because they are split up over different models. Overriding the get_serializer_class() has not worked because I don't know how to incorporate these serializers there neither. How could I make this representation work? Thanks in advance

答:
it is because you didn't add your class's Serializer . those serializers you added aren't built in ones . simply add

```<code>serializer_class = SlideSerializer
</code>```

to your class variables even if you don't want to use that . as in error mentioned , you need to add a serializer_class to your ListAPIView .

Body:
I have a Django API and I try to create the documentation with drf-yasg. I'm having trouble with the automatically generated schema for my nested serializer and ListAPIview. It looks like this:

serializers.py

class SlideDataSerializer(serializers.ModelSerializer):
    description = SlideDataDescriptionSerializer(many=True, read_only=True, source='slidedatadescription_set')
    class Meta:
        model = SlideData
        fields = ['catch', 'title', 'description', 'icon']

class SlideSerializer(serializers.ModelSerializer):
    datas = SlideDataSerializer(many=True, read_only=True, source='slidedata_set')
    class Meta:
        model = Slide
        fields = ['datas']

class PlanDataDescriptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = PlanDataDescription
        fields = ['description']

class PlanDataSerializer(serializers.ModelSerializer):
    description = PlanDataDescriptionSerializer(many=True, read_only=True, source='plandatadescription_set')
    class Meta:
        model = PlanData
        fields = ['stripColor', 'name', 'description', 'pricePerMonth', 'currency', 'picture']

class PlanSerializer(serializers.ModelSerializer):
    datas = PlanDataSerializer(many=True, read_only=True, source='plandata_set')
    class Meta:
        model = Plan
        fields = ['mainTitle', 'datas']

views.py

class ProjectList(generics.ListAPIView):
    permission_classes = [permissions.AllowAny]
    serializer_class_slide = SlideSerializer
    serializer_class_plan = PlanSerializer

    def get_queryset_object(self, Table, campaign, lang):
        queryset = Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang)
        return queryset[0]

    def list(self, request):
        Tables = [Slide,
                Plan]

        campaign = self.request.query_params.get('campaign') or "default"
        lang = self.request.query_params.get('lang') or "en"

        if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables):
            campaign = "default"

        if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables):
            lang = "en"

        slides = self.serializer_class_slide(self.get_queryset_object(Slide, campaign, lang))
        plans = self.serializer_class_plan(self.get_queryset_object(Plan, campaign, lang))

        return Response({
            "slides": slides.data,
            "plans": plans.data,
        })

and the urls.py:

openapi_info = openapi.Info(
        title="Projectname",
        default_version="v1",
        description="Endpoints",
        terms_of_service="TBD",
        contact=openapi.Contact(email="abc@123.com"),
        license=openapi.License(name="BSD License"),
    )

schema_view = get_schema_view(
    openapi_info,
    public=True,
    permission_classes=(permissions.AllowAny,),
)

API_VERSION = 'v1'
urlpatterns = [
    path('swagger/', schema_view.with_ui(
        'swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('swagger/api.json', schema_view.without_ui( cache_timeout=0), name='schema-swagger-json'),
]

The endpoint is working fine but swagger does not create the right requests or responses and when I access it it gives me this error message:

view's ProjectList raised exception during schema generation; use `getattr(self, 'swagger_fake_view', False)` to detect and short-circuit this
Traceback (most recent call last):
  File "/home/projects/env/lib/python3.8/site-packages/drf_yasg/inspectors/base.py", line 42, in call_view_method
    return view_method()
  File "/home/projects/env/lib/python3.8/site-packages/rest_framework/generics.py", line 108, in get_serializer
    serializer_class = self.get_serializer_class()
  File "/home/projects/env/lib/python3.8/site-packages/rest_framework/generics.py", line 122, in get_serializer_class
    assert self.serializer_class is not None, (
AssertionError: 'ProjectList' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method.

I can not include a serializer class name because I use multiple serializers, I can not create a single serializer for this because they are split up over different models. Overriding the get_serializer_class() has not worked because I don't know how to incorporate these serializers there neither. How could I make this representation work? Thanks in advance

Body:
it is because you didn't add your class's Serializer . those serializers you added aren't built in ones . simply add

serializer_class = SlideSerializer

to your class variables even if you don't want to use that . as in error mentioned , you need to add a serializer_class to your ListAPIView .


问:
What is the role of the package-lock.json?
npm@5 has been published, it has a new feature package-lock.json file (after npm install) which confuses me. I want to know, what is the effect of this file?

答:
Package.json file contains the main names of packages & libraries which you installed and you can edit it, but Package-lock.json contains the details of each package and the link of repository of each package (consider it's the details of the packages which came from package.json) Reference

https://web-brackets.com/discussion/69/what-is-the-use-of-package-lock-json-file


问:
OpenBSD fails to execute a.out
I wrote this program that should just exit with exitcode 44:

```<code>// prog.S
#include <sys/syscall.h>
        .text
        .globl _start
_start:
        subl $8, %esp
        pushl $44
        pushl $0
        movl $SYS_exit, %eax
        int $0x80
</code>```

I compiled with

```<code>$ cc prog.S -nostdlib -o a.out
</code>```

and run

```<code>$./a.out
</code>```

Doing so on FreeBSD 13.0-RELEASE i386 (clang 11.0.1) worked fine. In fact, the executable runs and the exit code of the program is 44 as it should be.

However, doing the same on OpenBSD 7.0 GENERIC.MP#5 i386 (clang version 11.1.0) and on NetBSD 9.2 i386 (gcc 7.5.0), the kernel refused to execute the code and it was passed to the shell, which of course failed:

```<code>openbsd$ ./a.out
./a.out[1]: syntax error: `(' unexpected
</code>```

The strange thing is also that file says it's an ELF binary and therefore should be normally executed by the kernel

```<code>openbsd$ file a.out

a.out: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, not stripped
</code>```

Even objdump prints what is expected to print

```<code>openbsd$ objdump -d a.out

a.out:     file format elf32-i386

Disassembly of section .text:

00001184 <_start>:
    1184:   83 ec 08                sub    $0x8,%esp
    1187:   6a 2c                   push   $0x2c
    1189:   b8 01 00 00 00          mov    $0x1,%eax
    118e:   6a 00                   push   $0x0
    1190:   cd 80                   int    $0x80

</code>```

Any idea about what I'm doing wrong?

PS: Changing _start with main and compiling without -nostdlib works fine both on OpenBSD and NetBSD

答:
On recent versions of NetBSD you can also link an assembler language program starting with the _start symbol and with -nostdlib by including just /usr/lib/sysident.o, for example like this:

```<code>as -o thello.o thello.s && ld -Bstatic -o thello /usr/lib/sysident.o thello.o
</code>```

On recent NetBSD this object also includes a .note.netbsd.pax section for controlling the PaX executable security features such as Mprotect, ASLR, and Segvguard.

Have a look in the #include <elf/common.h> file for definitions for similar note sections for other types of target systems.

See also https://polprog.net/blog/netbsdasmprog/

See also https://github.com/robohack/experiments/blob/master/thello.s

Title: OpenBSD fails to execute a.out

Body:
I wrote this program that should just exit with exitcode 44:

// prog.S
#include <sys/syscall.h>
        .text
        .globl _start
_start:
        subl $8, %esp
        pushl $44
        pushl $0
        movl $SYS_exit, %eax
        int $0x80

I compiled with

$ cc prog.S -nostdlib -o a.out

and run

$./a.out

Doing so on FreeBSD 13.0-RELEASE i386 (clang 11.0.1) worked fine. In fact, the executable runs and the exit code of the program is 44 as it should be.

However, doing the same on OpenBSD 7.0 GENERIC.MP#5 i386 (clang version 11.1.0) and on NetBSD 9.2 i386 (gcc 7.5.0), the kernel refused to execute the code and it was passed to the shell, which of course failed:

openbsd$ ./a.out
./a.out[1]: syntax error: `(' unexpected

The strange thing is also that file says it's an ELF binary and therefore should be normally executed by the kernel

openbsd$ file a.out

a.out: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, not stripped

Even objdump prints what is expected to print

openbsd$ objdump -d a.out

a.out:     file format elf32-i386

Disassembly of section .text:

00001184 <_start>:
    1184:   83 ec 08                sub    $0x8,%esp
    1187:   6a 2c                   push   $0x2c
    1189:   b8 01 00 00 00          mov    $0x1,%eax
    118e:   6a 00                   push   $0x0
    1190:   cd 80                   int    $0x80

Any idea about what I'm doing wrong?

PS: Changing _start with main and compiling without -nostdlib works fine both on OpenBSD and NetBSD

Body:
On recent versions of NetBSD you can also link an assembler language program starting with the _start symbol and with -nostdlib by including just /usr/lib/sysident.o, for example like this:

as -o thello.o thello.s && ld -Bstatic -o thello /usr/lib/sysident.o thello.o

On recent NetBSD this object also includes a .note.netbsd.pax section for controlling the PaX executable security features such as Mprotect, ASLR, and Segvguard.

Have a look in the #include <elf/common.h> file for definitions for similar note sections for other types of target systems.

See also https://polprog.net/blog/netbsdasmprog/

See also https://github.com/robohack/experiments/blob/master/thello.s


问:
Why column must appear in the GROUP BY?
I have this:

```<code>SELECT name, value,
       MIN(value) as find_min
FROM history
WHERE date_num >= 1609459200
  AND date_num <= 1640995200
  AND name IN('A')
GROUP BY name
</code>```

Trying to get the minimum value between dates for each subject separately :

```<code>name value
A.    3
B     4
C     9
A     0
C     2
</code>```

I keep getting this popular error:

column "history.value" must appear in the GROUP BY clause or be used in an aggregate function

I read this must appear in the GROUP BY clause or be used in an aggregate function

and I still do not understand:

Why I have to include in GROUP BY everything? what is the logic?

Why is this not working?

is Min() over (partition by name) better, and if so, how can I get only a single result per name?

EDIT:

If I try:GROUP BY name, find_min it will fail as well, even though in this case he can produce a unique result (the all the same)

答:
That is actually easy to understand.

When you say GROUP BY name, all rows where name is the same are grouped together to form a single result row. Now the original table could contain two rows with the same name, but different value. If you add value to the SELECT list, which of those should be output? On the other hand, determining min(value) for each group is no problem.

Even if there is only a single value for the whole group (like with your find_min), you have to add the column to GROUP BY.

There is actually one exception: if the primary key of a table is in the GROUP BY clause, other columns from that table need not be in GROUP BY, because this proves automatically that there can be no different values.

Title: Why column must appear in the GROUP BY?

Body:
I have this:

SELECT name, value,
       MIN(value) as find_min
FROM history
WHERE date_num >= 1609459200
  AND date_num <= 1640995200
  AND name IN('A')
GROUP BY name

Trying to get the minimum value between dates for each subject separately :

name value
A.    3
B     4
C     9
A     0
C     2

I keep getting this popular error:

column "history.value" must appear in the GROUP BY clause or be used in an aggregate function

I read this must appear in the GROUP BY clause or be used in an aggregate function

and I still do not understand:

Why I have to include in GROUP BY everything? what is the logic?

Why is this not working?

is Min() over (partition by name) better, and if so, how can I get only a single result per name?

EDIT:

If I try:GROUP BY name, find_min it will fail as well, even though in this case he can produce a unique result (the all the same)


问:
undefined $ and Duration parameter type
```<code>  int score = 0;
  Duration duration = Duration(seconds: Duration.secondsPerDay);

  void callLogs() async {

    Stopwatch stopwatch = new Stopwatch()..start();

    Iterable<CallLogEntry> entries = await CallLog.get();
    for (var item in entries) {
      duration = ${stopwatch.elapsed;};
      print('Duration ${stopwatch.elapsed}');
    }
    setState(() { duration > 5 ? score += 1 : score = 0; });
  }
</code>```

When call duration is over 5 second, the int score increase by 1. With the code above, I am still getting two errors.

Undefined name $

The argument type 'int' can't be assigned to the parameter type 'Duration'.

I thought using $ didn't need defining and still confuse with what Duration should be assigned at. Any kind of help would be appreciated. Thanks in advance

答:
It’s not clear what you’re trying to achieve. As I read the code, you are trying to read a call log from the phone, and if duration is greater than 5 seconds you increment the score by 1, otherwise you reset it to 0? Is that correct?

It may be that your setState is not called from the right place, but it could also be that the duration of stopwatch.elapsed never reach 6 seconds.

Title: undefined $ and Duration parameter type

Body:
  int score = 0;
  Duration duration = Duration(seconds: Duration.secondsPerDay);

  void callLogs() async {

    Stopwatch stopwatch = new Stopwatch()..start();

    Iterable<CallLogEntry> entries = await CallLog.get();
    for (var item in entries) {
      duration = ${stopwatch.elapsed;};
      print('Duration ${stopwatch.elapsed}');
    }
    setState(() { duration > 5 ? score += 1 : score = 0; });
  }

When call duration is over 5 second, the int score increase by 1. With the code above, I am still getting two errors.

Undefined name $

The argument type 'int' can't be assigned to the parameter type 'Duration'.

I thought using $ didn't need defining and still confuse with what Duration should be assigned at. Any kind of help would be appreciated. Thanks in advance


问:
Cloud Data Fusion ETL from PostGres to BigQuery - idempotent load
I'm trying to use Google's Cloud Data Fusion (CDF) to perform an ETL of some OLTP data in PostGres into BigQuery (BQ). We will copy the contents of a few select tables into an equivalent table in BQ every night - we will add one column with the datestamp.

So imagine we have a table with two columns A & B, and one row of data like this in PostGres

```<code>|--------------------|
|    A    |    B     |
|--------------------|
|  egg    |  milk    |
|--------------------|
</code>```

Then over two days, the BigQuery table would look like this

```<code>|-------------------------------|
|    ds    |    A    |    B     |
|-------------------------------|
| 22-01-01 |   egg   |   milk   |
|-------------------------------|
| 22-01-02 |   egg   |   milk   |
|-------------------------------|
</code>```

However, I'm worried that the way I am doing this in CDF is not idempotent and if the pipeline runs twice I'll have duplicate data for a given day in BQ (not desired)

One idea is to delete rows for that day in BQ before doing the ETL (as part of the same pipeline). However, not sure how to do this, or if it is best practice. Any ideas?

答:
You could delete the data in a BigQuery action at the start of the pipeline, though that runs into other issues if people are actively querying the table, or if the delete action succeeds but the rest of the pipeline fails.

The BigQuery sink allows you to configure it to upsert data instead of inserting. This should make it idempotent as long as your data has a key that can be used.

Some other possibilities are to place a BigQuery execute after the sink that runs a BigQuery MERGE, or to write a custom Condition plugin that queries BigQuery and only runs the rest of the pipeline if data for the date does not already exist.

Body:
I'm trying to use Google's Cloud Data Fusion (CDF) to perform an ETL of some OLTP data in PostGres into BigQuery (BQ). We will copy the contents of a few select tables into an equivalent table in BQ every night - we will add one column with the datestamp.

So imagine we have a table with two columns A & B, and one row of data like this in PostGres

|--------------------|
|    A    |    B     |
|--------------------|
|  egg    |  milk    |
|--------------------|

Then over two days, the BigQuery table would look like this

|-------------------------------|
|    ds    |    A    |    B     |
|-------------------------------|
| 22-01-01 |   egg   |   milk   |
|-------------------------------|
| 22-01-02 |   egg   |   milk   |
|-------------------------------|

However, I'm worried that the way I am doing this in CDF is not idempotent and if the pipeline runs twice I'll have duplicate data for a given day in BQ (not desired)

One idea is to delete rows for that day in BQ before doing the ETL (as part of the same pipeline). However, not sure how to do this, or if it is best practice. Any ideas?


问:
material-ui TextField disable Browser autoComplete
I use material ui v0.20.0 and I have to prohibit saving the password for a user with TextField. I added props to TextField autocomplete='nope' cause not all the browsers understand autocomplete='off'. It seems that the last version of Chrome 63 does not accept it. Sometimes it does not work and sometimes it does. I can not get why it works so hectic. When chrome asks to save password and I save it, and after that I want to edit input I still have this :

```<code>  <TextField
         name='userName'
         floatingLabelText={<FormattedMessage id='users.username' />}
         value={name || ''}
         onChange={(e, name) => this.changeUser({name})}
         // autoComplete='new-password'

    />

    <TextField
        name='password'
        floatingLabelText={<FormattedMessage id='users.passwords.new' />}
        type='password'
        value={password || ''}
        onChange={(e, password) => this.changeUser({password})}
        autoComplete='new-password'
   />
</code>```

Looks like it works in Firefox(v57.0.4)

By default TextField does not have autoComplete='off'

答:
Id like to thank and expand on @Elie Bsaisbes answer https://stackoverflow.com/a/70000217/16538978

For the life of me, autoComplete = "off" / new-password etc... would only work on some forms, and not others. Only in chrome. Finally, the solution was to add a custom name as said in the linked answer like so

```<code>             <TextField
                name="noAutoFill"
                label="Password"
                variant="standard"
                defaultValue=""
                id="password"
                type="password"
              />

</code>```

Body:
I use material ui v0.20.0 and I have to prohibit saving the password for a user with TextField. I added props to TextField autocomplete='nope' cause not all the browsers understand autocomplete='off'. It seems that the last version of Chrome 63 does not accept it. Sometimes it does not work and sometimes it does. I can not get why it works so hectic. When chrome asks to save password and I save it, and after that I want to edit input I still have this :

  <TextField
         name='userName'
         floatingLabelText={<FormattedMessage id='users.username' />}
         value={name || ''}
         onChange={(e, name) => this.changeUser({name})}
         // autoComplete='new-password'

    />

    <TextField
        name='password'
        floatingLabelText={<FormattedMessage id='users.passwords.new' />}
        type='password'
        value={password || ''}
        onChange={(e, password) => this.changeUser({password})}
        autoComplete='new-password'
   />

Looks like it works in Firefox(v57.0.4)

By default TextField does not have autoComplete='off'

Body:
Id like to thank and expand on @Elie Bsaisbes answer https://stackoverflow.com/a/70000217/16538978

For the life of me, autoComplete = "off" / new-password etc... would only work on some forms, and not others. Only in chrome. Finally, the solution was to add a custom name as said in the linked answer like so

             <TextField
                name="noAutoFill"
                label="Password"
                variant="standard"
                defaultValue=""
                id="password"
                type="password"
              />


问:
Element "align" is obsolete or non-standard: what should I use instead?
I have this HTML code:

```<code><td align="center">
</code>```

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

答:
You did not explain your goal, but using CSS is more modern...

```<code><td style="text-align: center;">
</code>```

Using that within a stylesheet, rather than inline would be even better...

```<code>td {
    text-align: center;
}
</code>```

Body:
I have this HTML code:

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

Body:
You did not explain your goal, but using CSS is more modern...

<td style="text-align: center;">

Using that within a stylesheet, rather than inline would be even better...

td {
    text-align: center;
}


问:
Qdebug display hex value
I am trying to display a number using QDebug in the Hex format. Below is the code which I have written.  It is working but the output has string contents enclosed in double quotes:

How to remove these quotes?

```<code>m_CanMsg_ptr->id = 0x720;
m_CanMsg_ptr->sizeData = 1;
m_CanMsg_ptr->data[0] = 0x05;

MessageID.setNum(m_CanMsg_ptr->id,16);
DataSize  = QString("%1").arg(m_CanMsg_ptr->sizeData, 0, 16);
data      = QString("%1").arg(m_CanMsg_ptr->data[0], 0, 16)

qDebug() << "Heart-Beat : Msg ID = " << MessageID << "  Msg DLC = " << DataSize;
qDebug() << "Msg Data " << " = " << data;
</code>```

I did as per these resources:

http://forum.qt.io/topic/5003/moved-how-to-display-a-local-variable-in-hex-when-debugging-a-qt-app/2
http://qt.shoutwiki.com/wiki/Convert_hexadecimal_to_decimal_and_vice-versa_in_Qt

答:
Just a note! The method using <<hex is deprecieted now, so it's recommended to use:

#include <QDebug>

int num = 0x4321;
qDebug() << "Hex num: " <<Qt::hex << num;

```

Because, if you compile this way just using <<hex you will got some warnings, what means that soon this form to write will not be compatible anymore. For more infos take a look at  Qt documentation

Title: Qdebug display hex value

Body:
I am trying to display a number using QDebug in the Hex format. Below is the code which I have written.  It is working but the output has string contents enclosed in double quotes:

How to remove these quotes?

m_CanMsg_ptr->id = 0x720;
m_CanMsg_ptr->sizeData = 1;
m_CanMsg_ptr->data[0] = 0x05;

MessageID.setNum(m_CanMsg_ptr->id,16);
DataSize  = QString("%1").arg(m_CanMsg_ptr->sizeData, 0, 16);
data      = QString("%1").arg(m_CanMsg_ptr->data[0], 0, 16)

qDebug() << "Heart-Beat : Msg ID = " << MessageID << "  Msg DLC = " << DataSize;
qDebug() << "Msg Data " << " = " << data;

I did as per these resources:

http://forum.qt.io/topic/5003/moved-how-to-display-a-local-variable-in-hex-when-debugging-a-qt-app/2
http://qt.shoutwiki.com/wiki/Convert_hexadecimal_to_decimal_and_vice-versa_in_Qt

Body:
Just a note! The method using <<hex is deprecieted now, so it's recommended to use:

#include <QDebug>

int num = 0x4321;
qDebug() << "Hex num: " <<Qt::hex << num;

Because, if you compile this way just using <<hex you will got some warnings, what means that soon this form to write will not be compatible anymore. For more infos take a look at  Qt documentation


答:
To answer your question, GROUP BY groups similar data in a table.
For example this table:

```<code>A B C
a d 1
a k 2
b d 3
</code>```

And you have the query:

```<code>SELECT A, B, MIN(C)
FROM t
GROUP BY A
</code>```

and this would not work you can't give a decisive answer what to do with the entry a k 2 because you don't group by Column B, but you group by column A, is there now two entries but they are different. Therefore you have to group by all non min,max,sum,etc. columns.

Title: Why column must appear in the GROUP BY?

Body:
To answer your question, GROUP BY groups similar data in a table.
For example this table:

A B C
a d 1
a k 2
b d 3

And you have the query:

SELECT A, B, MIN(C)
FROM t
GROUP BY A

and this would not work you can't give a decisive answer what to do with the entry a k 2 because you don't group by Column B, but you group by column A, is there now two entries but they are different. Therefore you have to group by all non min,max,sum,etc. columns.


问:
How do you make someone admin using discord.py?
I tried using this:

await name.Permissions.administrator()
but it didn't work any suggestions?

答: You cannot directly give users permissions. Create a role with the Administrator permission, and then take a look at user.add_roles


问:
Multiprocessing.Process running entire script instead of just target function in python
I have a simple example script that uses multiprocessing to execute a very simple function and return the runtimes for all parts of the process. The script is fully reproducible and looks as such:

```<code>import time
start_time = time.perf_counter()

import multiprocessing
print(f'Libraries loaded: {round(time.perf_counter()-start_time,2)} sec')
start_time = time.perf_counter()

def test():
    print('Sleeping 1 sec')
    time.sleep(1)
    print('Done Sleeping')

print(f'Functions loaded: {round(time.perf_counter()-start_time,2)} sec')
start_time = time.perf_counter()

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=test)
    p2 = multiprocessing.Process(target=test)
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    finish = time.perf_counter()
    print(f'Multiprocessing finished in {round(finish - start_time, 2)} sec')
</code>```

The output of the script looks as such:

```<code>Libraries loaded: 0.03 sec
Functions loaded: 0.0 sec
Libraries loaded: 0.0 sec
Functions loaded: 0.0 sec
Sleeping 1 sec
Libraries loaded: 0.0 sec
Functions loaded: 0.0 sec
Sleeping 1 sec
Done SleepingDone Sleeping

Multiprocessing finished in 1.12 sec

Process finished with exit code 0
</code>```

As you can see, whilst the multiprocesses are running in parallel, they run the entire script each time as opposed to just executing the target function test. The script is therefore being run twice completely unnecessarily and I don't understand why.

Could someone explain this to me please?

Thanks

答:
Do this:

```<code>if __name__ == "__main__":
    <execute main thread here>
</code>```

inside main thread you create the process. That new process won't call the whole script cause you only allow the main thread to call the whole process.

Body:
I have a simple example script that uses multiprocessing to execute a very simple function and return the runtimes for all parts of the process. The script is fully reproducible and looks as such:

import time
start_time = time.perf_counter()

import multiprocessing
print(f'Libraries loaded: {round(time.perf_counter()-start_time,2)} sec')
start_time = time.perf_counter()

def test():
    print('Sleeping 1 sec')
    time.sleep(1)
    print('Done Sleeping')

print(f'Functions loaded: {round(time.perf_counter()-start_time,2)} sec')
start_time = time.perf_counter()

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=test)
    p2 = multiprocessing.Process(target=test)
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    finish = time.perf_counter()
    print(f'Multiprocessing finished in {round(finish - start_time, 2)} sec')

The output of the script looks as such:

Libraries loaded: 0.03 sec
Functions loaded: 0.0 sec
Libraries loaded: 0.0 sec
Functions loaded: 0.0 sec
Sleeping 1 sec
Libraries loaded: 0.0 sec
Functions loaded: 0.0 sec
Sleeping 1 sec
Done SleepingDone Sleeping

Multiprocessing finished in 1.12 sec

Process finished with exit code 0

As you can see, whilst the multiprocesses are running in parallel, they run the entire script each time as opposed to just executing the target function test. The script is therefore being run twice completely unnecessarily and I don't understand why.

Could someone explain this to me please?

Thanks

Body:
Do this:

if __name__ == "__main__":
    <execute main thread here>

inside main thread you create the process. That new process won't call the whole script cause you only allow the main thread to call the whole process.


问:
Selenium with firefox self signed certificate issue, cannot bypass
Let me preface by saying I am definitely novice and apologies if I improperly describe or name something. I am trying to automate the interactions with a web page served up by an application on a server in my local subnet, not over the internet, and it is using a self signed cert.

I am on windows 10, using the pycharm IDE with Python 3.9.10, Selenium 3.141.0, Firefox 95.0.2 and the latest geckodriver version 0.30.0.

I have browsed the many posts with fixes for this issue. I started with Selenium 4.1 but learned that everything the fixes used, like desired capabilities, was deprecated and replaced with service and options objects that I just couldn't get to work.

So I downgraded to Selenium 3.141.0 to try and implement the fixes suggested.

First, when starting with a simple webdriver instantiation without any options other than pointing to the driver, I got a popup for login. I could not inspect it so I figured it was not an html element.

Login prompt

With some googling i found it to be basic browser based authentication and bypassed it by  adding <user>:<pass>@<address> URL format. This then got me past the login prompt and actually to the landing page of the webUI. It was still an unsecure connection and you can see in the following screenshot, it said there was a security exception was added.

Security exception

However, within a couple of seconds of the page loading I got a popup that there was no repsonse from the server, which I knew was not the case, as I could manually access the site and accept the cert security warning to access the site.

No response from server

If I reloaded the page manually, or with a refresh from selenium, I then got the certificate error page.

Certificate warning

I have tried any combination of the below fixes I have found in various posts, using options, profile and capabilities parameters, and all of them give me the same result as I explained above when I use nothing but a webdriver instance.

```<code>options = Options()
options.add_argument("--ignore-certificate-errors")
options.accept_insecure_certs = True

profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
profile.assume_untrusted_cert_issuer = True

capabilities = DesiredCapabilities().FIREFOX.copy()
capabilities["acceptSslCerts"] = True
capabilities["acceptInsecureCerts"] = True

browser = webdriver.Firefox(executable_path="<path>", firefox_profile=profile, capabilities=capabilities, options=options)
</code>```

Any help is greatly appreciated, and if anyone knows a fix for Selenium 4.1 using service and options objects let me know, I am willing to try that too. But looking at the documentation and code for the firefox options class, it looks like there is no longer an add_arguments function, Options doc, as I think they have moved solely to set_preferences. As for the service object that every error told me to use due to deprecation, looking at that Service doc the only function that looked promising was the command_line_args, but looking at the code, it simply raises a NotImplementedError..... That is why I gave up on getting anything to work with Selenium 4.1, because I could not find any preferences that would work, as that seemed like the only thing that could be modified in the options object.

答:
Looking into the geckodriver logs I found that the --ignore-certificate-errors arg was being passed to the firefox call. I only found these logs because they were in the IDE project files, or else I would have never thought to look at them.

In the log file, you can see that there is a warning that a settings file doesn't exist. I am using the FirefoxProfile class without sending a path to an existing profile, wherein Selenium will create its own temporary profile. I think this profile is causing issues, as passing the path to the default firefox profile solved the issue.

geckodriver log

Body:
Let me preface by saying I am definitely novice and apologies if I improperly describe or name something. I am trying to automate the interactions with a web page served up by an application on a server in my local subnet, not over the internet, and it is using a self signed cert.

I am on windows 10, using the pycharm IDE with Python 3.9.10, Selenium 3.141.0, Firefox 95.0.2 and the latest geckodriver version 0.30.0.

I have browsed the many posts with fixes for this issue. I started with Selenium 4.1 but learned that everything the fixes used, like desired capabilities, was deprecated and replaced with service and options objects that I just couldn't get to work.

So I downgraded to Selenium 3.141.0 to try and implement the fixes suggested.

First, when starting with a simple webdriver instantiation without any options other than pointing to the driver, I got a popup for login. I could not inspect it so I figured it was not an html element.

Login prompt

With some googling i found it to be basic browser based authentication and bypassed it by  adding <user>:<pass>@<address> URL format. This then got me past the login prompt and actually to the landing page of the webUI. It was still an unsecure connection and you can see in the following screenshot, it said there was a security exception was added.

Security exception

However, within a couple of seconds of the page loading I got a popup that there was no repsonse from the server, which I knew was not the case, as I could manually access the site and accept the cert security warning to access the site.

No response from server

If I reloaded the page manually, or with a refresh from selenium, I then got the certificate error page.

Certificate warning

I have tried any combination of the below fixes I have found in various posts, using options, profile and capabilities parameters, and all of them give me the same result as I explained above when I use nothing but a webdriver instance.

options = Options()
options.add_argument("--ignore-certificate-errors")
options.accept_insecure_certs = True

profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
profile.assume_untrusted_cert_issuer = True

capabilities = DesiredCapabilities().FIREFOX.copy()
capabilities["acceptSslCerts"] = True
capabilities["acceptInsecureCerts"] = True

browser = webdriver.Firefox(executable_path="<path>", firefox_profile=profile, capabilities=capabilities, options=options)

Any help is greatly appreciated, and if anyone knows a fix for Selenium 4.1 using service and options objects let me know, I am willing to try that too. But looking at the documentation and code for the firefox options class, it looks like there is no longer an add_arguments function, Options doc, as I think they have moved solely to set_preferences. As for the service object that every error told me to use due to deprecation, looking at that Service doc the only function that looked promising was the command_line_args, but looking at the code, it simply raises a NotImplementedError..... That is why I gave up on getting anything to work with Selenium 4.1, because I could not find any preferences that would work, as that seemed like the only thing that could be modified in the options object.


问:
Is that possible to show that there is 0 rows of specified criteria with UNION and COUNT() usage?
my table: "tfr_general_charges" has a column called MANDANT_ID. The column can have only two different values:

001 and 002

There are many records with the value 002 in MANDANT_ID column and my SELECT shows it as follows:

I marked red the missing row, which also has to be displayed. So far, it has been returning number of rows with MANDANT_ID = '002', but zero rows with MANDANT_ID '001' should also be visible.
Here is my code:

```<code>SELECT
    "tfr_gen_ch" AS tabnam
    , run_date
    , mandant_id
    , count(*) as total
FROM tfr_general_charges
GROUP BY
    run_date
    , mandant_id
having mandant_id = '002'
union
SELECT
    "tfr_gen_ch" AS tabnam
    , run_date
    , mandant_id
    , count(*) as total
FROM tfr_general_charges
GROUP BY
    run_date
    , mandant_id
having mandant_id = '001'
</code>```

In addition, I work with HIVE SQL and tried to use ISNULL() function, but without success.
Can You please help?

答:
Use UNION ALL to create a resultset with only 2 rows with 1 column containing the values '001' and '002' and do a LEFT join to your table before you aggregate:

```<code>SELECT "tfr_gen_ch" tabnam,
       tcg.run_date,
       t.mandant_id,
       COUNT(tcg.mandant_id) AS total
FROM (SELECT '001' AS mandant_id UNION ALL SELECT '002') t
LEFT JOIN tfr_general_charges tcg
ON t.mandant_id = tcg.mandant_id
GROUP BY tcg.run_date, t.mandant_id;
</code>```

Body:
my table: "tfr_general_charges" has a column called MANDANT_ID. The column can have only two different values:

001 and 002

There are many records with the value 002 in MANDANT_ID column and my SELECT shows it as follows:

I marked red the missing row, which also has to be displayed. So far, it has been returning number of rows with MANDANT_ID = '002', but zero rows with MANDANT_ID '001' should also be visible.
Here is my code:

SELECT
    "tfr_gen_ch" AS tabnam
    , run_date
    , mandant_id
    , count(*) as total
FROM tfr_general_charges
GROUP BY
    run_date
    , mandant_id
having mandant_id = '002'
union
SELECT
    "tfr_gen_ch" AS tabnam
    , run_date
    , mandant_id
    , count(*) as total
FROM tfr_general_charges
GROUP BY
    run_date
    , mandant_id
having mandant_id = '001'

In addition, I work with HIVE SQL and tried to use ISNULL() function, but without success.
Can You please help?

Body:
Use UNION ALL to create a resultset with only 2 rows with 1 column containing the values '001' and '002' and do a LEFT join to your table before you aggregate:

SELECT "tfr_gen_ch" tabnam,
       tcg.run_date,
       t.mandant_id,
       COUNT(tcg.mandant_id) AS total
FROM (SELECT '001' AS mandant_id UNION ALL SELECT '002') t
LEFT JOIN tfr_general_charges tcg
ON t.mandant_id = tcg.mandant_id
GROUP BY tcg.run_date, t.mandant_id;


问:
MySQL Workbench EER diagram: edges of display cut off
I'm having an issue where the edges of the display are cut off when viewing an EER diagram in MySQL Workbench:

I'm running on Ubuntu 20.04. I've tried the following already:

Resizing the window

Changing display resolution (default is 1920 x 1080, I tried reducing to 1680 x 1050)

Changing display scale (default is 100%, I tried 125%)

Setting environment variable GDK_SCALE=1 on startup

When I run from the command line, everything looks fine until I open EER diagram, at which point I get this output:

(mysql-workbench-bin:13508): Gtk-CRITICAL **: 15:01:10.921: gtk_container_foreach: assertion 'GTK_IS_CONTAINER (container)' failed

This is what my wb.1.log file looks like:

```<code>    base dir: /usr/share/mysql-workbench
    plugin path: /usr/lib/mysql-workbench/plugins
    struct path: /usr/share/mysql-workbench/grt
    module path: /usr/lib/mysql-workbench/modules
    library path: /usr/share/mysql-workbench/libraries
    user data dir: /home/shura/.mysql/workbench
    open at start:
    open type:
    run at startup:
    run type:
    Force SW rendering: No
    Force OpenGL: No
    quit when done: No
15:05:22 [INF][      WBContext]: WbContext::init
15:05:22 [INF][            WBA]: Looking for extension modules for WBA...
15:05:22 [INF][            WBA]: 0 extension modules found
15:05:22 [WRN][            grt]: Duplicate plugin name wb.tools.cmdlineClient   There is more than one plugin with the name wb.tools.cmdlineClient (in PyWbUtils and PyWbUtils).
15:05:22 [WRN][            grt]: /home/shura/.mysql/workbench/connections.xml:23: link 'f4a743c2-498c-11ec-b08f-f34455d9e052' <object GrtObject> key=owner could not be resolved
15:05:22 [WRN][            grt]: Duplicate plugin name wb.tools.cmdlineClient   There is more than one plugin with the name wb.tools.cmdlineClient (in PyWbUtils and PyWbUtils).
15:05:22 [INF][      WBContext]: System info:
    MySQL Workbench Community (GPL) for Linux/Unix version 8.0.27 CE build 1228725 (64 bit)
    Configuration Directory: /home/shura/.mysql/workbench
    Data Directory: /usr/share/mysql-workbench
    Cairo Version: 1.16.0
    OS: Ubuntu 20.04 x86_64
    CPU: 16x Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz (3800.000MHz) - 31.14GiB RAM
No video adapter info available
    Distribution: Ubuntu 20.04.3 LTS

    Fips mode enabled: no
</code>```

I've tried googling the warnings, and haven't found anything that points me in an obvious direction. Grateful for any advice!

答:
There should be draggable resizing arrows on the borders of the panels from the center out.
Navigator panel and the whole left side have it on the right edge of the navigator panel.
Likewise, Templates panel and the whole right side has it on the left side of the panel itself.</p>

Body:
I'm having an issue where the edges of the display are cut off when viewing an EER diagram in MySQL Workbench:

I'm running on Ubuntu 20.04. I've tried the following already:

Resizing the window

Changing display resolution (default is 1920 x 1080, I tried reducing to 1680 x 1050)

Changing display scale (default is 100%, I tried 125%)

Setting environment variable GDK_SCALE=1 on startup

When I run from the command line, everything looks fine until I open EER diagram, at which point I get this output:

(mysql-workbench-bin:13508): Gtk-CRITICAL **: 15:01:10.921: gtk_container_foreach: assertion 'GTK_IS_CONTAINER (container)' failed

This is what my wb.1.log file looks like:

    base dir: /usr/share/mysql-workbench
    plugin path: /usr/lib/mysql-workbench/plugins
    struct path: /usr/share/mysql-workbench/grt
    module path: /usr/lib/mysql-workbench/modules
    library path: /usr/share/mysql-workbench/libraries
    user data dir: /home/shura/.mysql/workbench
    open at start:
    open type:
    run at startup:
    run type:
    Force SW rendering: No
    Force OpenGL: No
    quit when done: No
15:05:22 [INF][      WBContext]: WbContext::init
15:05:22 [INF][            WBA]: Looking for extension modules for WBA...
15:05:22 [INF][            WBA]: 0 extension modules found
15:05:22 [WRN][            grt]: Duplicate plugin name wb.tools.cmdlineClient   There is more than one plugin with the name wb.tools.cmdlineClient (in PyWbUtils and PyWbUtils).
15:05:22 [WRN][            grt]: /home/shura/.mysql/workbench/connections.xml:23: link 'f4a743c2-498c-11ec-b08f-f34455d9e052' <object GrtObject> key=owner could not be resolved
15:05:22 [WRN][            grt]: Duplicate plugin name wb.tools.cmdlineClient   There is more than one plugin with the name wb.tools.cmdlineClient (in PyWbUtils and PyWbUtils).
15:05:22 [INF][      WBContext]: System info:
    MySQL Workbench Community (GPL) for Linux/Unix version 8.0.27 CE build 1228725 (64 bit)
    Configuration Directory: /home/shura/.mysql/workbench
    Data Directory: /usr/share/mysql-workbench
    Cairo Version: 1.16.0
    OS: Ubuntu 20.04 x86_64
    CPU: 16x Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz (3800.000MHz) - 31.14GiB RAM
No video adapter info available
    Distribution: Ubuntu 20.04.3 LTS

    Fips mode enabled: no

I've tried googling the warnings, and haven't found anything that points me in an obvious direction. Grateful for any advice!


问:
Current URL (from address bar) in a Bookmarklet
I'm building a bookmarklet and I need to get the current URL of the webpage the user is on when they activate the bookmarklet.

I tried using

```<code>$current_url = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
</code>```

But that will just get me the URL of the server where the JS for the bookmarklet is hosted. Is there anyway of getting the URL straight from the address bar?

答:
If by bookmarklet you mean http://en.wikipedia.org/wiki/Bookmarklet than I think this code will help:

```<code>javascript:alert(document.location.href);
</code>```

To test it, select the code and drag it in your bookmark browser bar than click it.

Body:
I'm building a bookmarklet and I need to get the current URL of the webpage the user is on when they activate the bookmarklet.

I tried using

$current_url = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

But that will just get me the URL of the server where the JS for the bookmarklet is hosted. Is there anyway of getting the URL straight from the address bar?

Body:
If by bookmarklet you mean http://en.wikipedia.org/wiki/Bookmarklet than I think this code will help:

javascript:alert(document.location.href);

To test it, select the code and drag it in your bookmark browser bar than click it.